diff
stringlengths
164
2.11M
is_single_chunk
bool
2 classes
is_single_function
bool
2 classes
buggy_function
stringlengths
0
335k
fixed_function
stringlengths
23
335k
diff --git a/src/com/qiniu/resumableio/ResumableClient.java b/src/com/qiniu/resumableio/ResumableClient.java index 5dd0348..20cad3c 100644 --- a/src/com/qiniu/resumableio/ResumableClient.java +++ b/src/com/qiniu/resumableio/ResumableClient.java @@ -1,131 +1,131 @@ package com.qiniu.resumableio; import android.util.Base64; import com.qiniu.auth.CallRet; import com.qiniu.auth.Client; import com.qiniu.auth.JSONObjectRet; import com.qiniu.conf.Conf; import com.qiniu.utils.ICancel; import com.qiniu.utils.InputStreamAt; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.StringEntity; import org.json.JSONObject; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map; public class ResumableClient extends Client { String mUpToken; int CHUNK_SIZE = 256 * 1024; int BLOCK_SIZE = 4 * 1024 * 1024; public ResumableClient(HttpClient client, String uptoken) { super(client); mUpToken = uptoken; } @Override - protected HttpResponse roundtrip(HttpPost httpPost) throws IOException { + protected HttpResponse roundtrip(HttpRequestBase httpRequest) throws IOException { if (mUpToken != null) { - httpPost.setHeader("Authorization", "UpToken " + mUpToken); + httpRequest.setHeader("Authorization", "UpToken " + mUpToken); } - return super.roundtrip(httpPost); + return super.roundtrip(httpRequest); } public ICancel[] putblock(final InputStreamAt input, final PutExtra extra, final PutRet putRet, final long offset, final JSONObjectRet callback) { final int writeNeed = (int) Math.min(input.length()-offset, BLOCK_SIZE); final ICancel[] canceler = new ICancel[] {null}; JSONObjectRet ret = new JSONObjectRet() { long crc32, wrote, writing = 0; public void onInit(int flag) { flag = putRet.isInvalid() ? 0 : 1; if (flag == 0) putInit(); if (flag == 1) putNext(); } public void putInit() { int chunkSize = Math.min(writeNeed, CHUNK_SIZE); crc32 = input.getCrc32(offset, chunkSize); canceler[0] = mkblk(input, offset, writeNeed, chunkSize, this); } public void putNext() { wrote = putRet.offset; int remainLength = Math.min((int) (input.length() - offset - putRet.offset), CHUNK_SIZE); crc32 = input.getCrc32(offset+putRet.offset, remainLength); canceler[0] = bput(putRet.host, input, putRet.ctx, offset, putRet.offset, remainLength, this); } @Override public void onSuccess(JSONObject obj) { if (crc32 != new PutRet(obj).crc32) { onInit(-1); return; } putRet.parse(obj); if (extra.notify != null) extra.notify.onSuccessUpload(extra); wrote += writing; if (putRet.offset == writeNeed) { callback.onSuccess(obj); return; } putNext(); } @Override public void onProcess(long current, long total) { writing = current; callback.onProcess(wrote+writing, writeNeed); } @Override public void onFailure(Exception ex) { callback.onFailure(ex); } }; ret.onInit(-1); return canceler; } public ICancel mkblk(InputStreamAt input, long offset, int blockSize, int writeSize, CallRet ret) { String url = Conf.UP_HOST + "/mkblk/" + blockSize; ClientExecutor client = makeClientExecutor(); call(client, url, input.toHttpEntity(offset, writeSize, client), ret); return client; } public ICancel bput(String host, InputStreamAt input, String ctx, long blockOffset, long offset, int writeLength, CallRet ret) { String url = host + "/bput/" + ctx + "/" + offset; ClientExecutor client = makeClientExecutor(); call(client, url, input.toHttpEntity(blockOffset+offset, writeLength, client), ret); return client; } public ICancel mkfile(String key, long fsize, String mimeType, Map<String, String> params, String ctxs, CallRet ret) { String url = Conf.UP_HOST + "/mkfile/" + fsize; if (mimeType != null && mimeType.length() > 0) { url += "/mimeType/" + encode(mimeType); } if (key != null && key.length() > 0) { url += "/key/" + encode(key); } if (params != null && params.size() > 0) { for (Map.Entry<String, String> a: params.entrySet()) { url += "/" + a.getKey() + "/" + encode(a.getValue()); } } try { return call(makeClientExecutor(), url, new StringEntity(ctxs), ret); } catch (UnsupportedEncodingException e) { e.printStackTrace(); ret.onFailure(e); return null; } } public String encode(String data) { return Base64.encodeToString(data.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP); } }
false
false
null
null
diff --git a/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderMountains.java b/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderMountains.java index c6ef43a..11878ff 100644 --- a/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderMountains.java +++ b/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderMountains.java @@ -1,162 +1,162 @@ /** * */ package net.nexisonline.spade.chunkproviders; import java.util.Random; import libnoiseforjava.NoiseGen.NoiseQuality; import libnoiseforjava.module.Perlin; import libnoiseforjava.module.RidgedMulti; import org.bukkit.ChunkProvider; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Biome; /** * @author Rob * */ public class ChunkProviderMountains extends ChunkProvider { private RidgedMulti terrainNoise; private Perlin continentNoise; private int continentNoiseOctaves = 16; private NoiseQuality noiseQuality = NoiseQuality.QUALITY_STD; private double ContinentNoiseFrequency; /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#onLoad(org.bukkit.World, long) */ @Override public void onLoad(World world, long seed) { double Frequency = 0.1; double Lacunarity = 0.05; double Persistance = 0.25; int OctaveCount = continentNoiseOctaves = 4; try { terrainNoise = new RidgedMulti(); continentNoise = new Perlin(); terrainNoise.setSeed((int) seed); continentNoise.setSeed((int) seed + 2); new Random((int) seed); terrainNoise.setFrequency(Frequency); terrainNoise.setNoiseQuality(noiseQuality); terrainNoise.setOctaveCount(OctaveCount); terrainNoise.setLacunarity(Lacunarity); continentNoise.setFrequency(ContinentNoiseFrequency); continentNoise.setNoiseQuality(noiseQuality); continentNoise.setOctaveCount(continentNoiseOctaves); continentNoise.setLacunarity(Lacunarity); continentNoise.setPersistence(Persistance); } catch (Exception e) { } } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#generateChunk(int, int, byte[], * org.bukkit.block.Biome[], double[]) */ @Override public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { int minHeight = 128; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { double heightoffset = (continentNoise.getValue( (double) (x + (X * 16)) / 10d, (double) (z + (Z * 16)) / 10d, 0) + 1d);// *5d; // 2.0 double height = 30 + heightoffset; height += (int) ((terrainNoise.getValue(x + (X * 16), z - + (Z * 16), 0) + heightoffset)); + + (Z * 16), 0) + heightoffset)*0.33); if (height < minHeight) minHeight = (int) height; for (int y = 0; y < 128; y++) { // If below height, set rock. Otherwise, set air. byte block = (y <= height) ? (byte) 1 : (byte) 0; // Fill block = (y <= 63 && block == 0) ? (byte) 9 : block; // Water // double _do = ((CaveNoise.GetValue(x + (X * chunksize.X), // z + (Z * chunksize.Z), y * CaveDivisor) + 1) / 2.0); // bool d3 = _do > CaveThreshold; // if(d3) // { // if (y <= 63) // block = 3; // else // block = 0; // } // else // block = (d3) ? b[x, y, z] : (byte)1; abyte[getBlockIndex(x,y,z)]=(byte) ((y<2) ? Material.BEDROCK.getId() : block); } } } } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#populateChunk(int, int, byte[], * org.bukkit.block.Biome[]) */ @Override public void populateChunk(World world, int x, int z, byte[] abyte, Biome[] biomes) { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#hasCustomTerrainGenerator() */ @Override public boolean hasCustomTerrainGenerator() { // TODO Auto-generated method stub return true; } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#hasCustomPopulator() */ @Override public boolean hasCustomPopulator() { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#hasCustomCaves() */ @Override public boolean hasCustomCaves() { // TODO Auto-generated method stub return false; } /* * (non-Javadoc) * * @see org.bukkit.ChunkProvider#generateCaves(java.lang.Object, int, int, * byte[]) */ @Override public void generateCaves(World world, int x, int z, byte[] abyte) { // TODO Auto-generated method stub } }
true
true
public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { int minHeight = 128; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { double heightoffset = (continentNoise.getValue( (double) (x + (X * 16)) / 10d, (double) (z + (Z * 16)) / 10d, 0) + 1d);// *5d; // 2.0 double height = 30 + heightoffset; height += (int) ((terrainNoise.getValue(x + (X * 16), z + (Z * 16), 0) + heightoffset)); if (height < minHeight) minHeight = (int) height; for (int y = 0; y < 128; y++) { // If below height, set rock. Otherwise, set air. byte block = (y <= height) ? (byte) 1 : (byte) 0; // Fill block = (y <= 63 && block == 0) ? (byte) 9 : block; // Water // double _do = ((CaveNoise.GetValue(x + (X * chunksize.X), // z + (Z * chunksize.Z), y * CaveDivisor) + 1) / 2.0); // bool d3 = _do > CaveThreshold; // if(d3) // { // if (y <= 63) // block = 3; // else // block = 0; // } // else // block = (d3) ? b[x, y, z] : (byte)1; abyte[getBlockIndex(x,y,z)]=(byte) ((y<2) ? Material.BEDROCK.getId() : block); } } } }
public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature) { int minHeight = 128; for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { double heightoffset = (continentNoise.getValue( (double) (x + (X * 16)) / 10d, (double) (z + (Z * 16)) / 10d, 0) + 1d);// *5d; // 2.0 double height = 30 + heightoffset; height += (int) ((terrainNoise.getValue(x + (X * 16), z + (Z * 16), 0) + heightoffset)*0.33); if (height < minHeight) minHeight = (int) height; for (int y = 0; y < 128; y++) { // If below height, set rock. Otherwise, set air. byte block = (y <= height) ? (byte) 1 : (byte) 0; // Fill block = (y <= 63 && block == 0) ? (byte) 9 : block; // Water // double _do = ((CaveNoise.GetValue(x + (X * chunksize.X), // z + (Z * chunksize.Z), y * CaveDivisor) + 1) / 2.0); // bool d3 = _do > CaveThreshold; // if(d3) // { // if (y <= 63) // block = 3; // else // block = 0; // } // else // block = (d3) ? b[x, y, z] : (byte)1; abyte[getBlockIndex(x,y,z)]=(byte) ((y<2) ? Material.BEDROCK.getId() : block); } } } }
diff --git a/src/biz/bokhorst/xprivacy/ActivityMain.java b/src/biz/bokhorst/xprivacy/ActivityMain.java index 0f655407..d72ac307 100644 --- a/src/biz/bokhorst/xprivacy/ActivityMain.java +++ b/src/biz/bokhorst/xprivacy/ActivityMain.java @@ -1,1393 +1,1391 @@ package biz.bokhorst.xprivacy; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageInfo; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.support.v4.content.LocalBroadcastManager; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; 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.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Filter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class ActivityMain extends Activity implements OnItemSelectedListener, CompoundButton.OnCheckedChangeListener { private int mThemeId; private Spinner spRestriction = null; private AppListAdapter mAppAdapter = null; private boolean mFiltersHidden = true; private boolean mCategoriesHidden = true; private Bitmap[] mCheck; private int mProgressWidth = 0; private int mProgress = 0; private boolean mSharing = false; private String mSharingState = null; private static final int ACTIVITY_LICENSE = 0; private static final int ACTIVITY_EXPORT = 1; private static final int ACTIVITY_IMPORT = 2; private static final int ACTIVITY_IMPORT_SELECT = 3; private static final int ACTIVITY_FETCH = 4; private static final int LICENSED = 0x0100; private static final int NOT_LICENSED = 0x0231; private static final int RETRY = 0x0123; private static final int ERROR_CONTACTING_SERVER = 0x101; private static final int ERROR_INVALID_PACKAGE_NAME = 0x102; private static final int ERROR_NON_MATCHING_UID = 0x103; public static final Uri cProUri = Uri.parse("http://www.faircode.eu/xprivacy/"); private static ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new PriorityThreadFactory()); private static class PriorityThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.NORM_PRIORITY); return t; } } private BroadcastReceiver mPackageChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ActivityMain.this.recreate(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Salt should be the same when exporting/importing String salt = PrivacyManager.getSetting(null, this, 0, PrivacyManager.cSettingSalt, null, false); if (salt == null) { salt = Build.SERIAL; if (salt == null) salt = ""; PrivacyManager.setSetting(null, this, 0, PrivacyManager.cSettingSalt, salt); } // Set theme String themeName = PrivacyManager.getSetting(null, this, 0, PrivacyManager.cSettingTheme, "", false); mThemeId = (themeName.equals("Dark") ? R.style.CustomTheme : R.style.CustomTheme_Light); setTheme(mThemeId); // Set layout setContentView(R.layout.mainlist); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // Get localized restriction name List<String> listRestriction = PrivacyManager.getRestrictions(); List<String> listLocalizedRestriction = new ArrayList<String>(); for (String restrictionName : listRestriction) listLocalizedRestriction.add(PrivacyManager.getLocalizedName(this, restrictionName)); listLocalizedRestriction.add(0, getString(R.string.menu_all)); // Build spinner adapter SpinnerAdapter spAdapter = new SpinnerAdapter(this, android.R.layout.simple_spinner_item); spAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spAdapter.addAll(listLocalizedRestriction); // Handle info ImageView imgInfo = (ImageView) findViewById(R.id.imgInfo); imgInfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int position = spRestriction.getSelectedItemPosition(); if (position != AdapterView.INVALID_POSITION) { String title = (position == 0 ? "XPrivacy" : PrivacyManager.getRestrictions().get(position - 1)); String url = String.format("http://wiki.faircode.eu/index.php?title=%s", title); Intent infoIntent = new Intent(Intent.ACTION_VIEW); infoIntent.setData(Uri.parse(url)); startActivity(infoIntent); } } }); // Setup spinner spRestriction = (Spinner) findViewById(R.id.spRestriction); spRestriction.setAdapter(spAdapter); spRestriction.setOnItemSelectedListener(this); // Setup name filter final EditText etFilter = (EditText) findViewById(R.id.etFilter); etFilter.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String text = etFilter.getText().toString(); ImageView imgClear = (ImageView) findViewById(R.id.imgClear); imgClear.setImageDrawable(getResources().getDrawable( Util.getThemed(ActivityMain.this, text.equals("") ? R.attr.icon_clear_grayed : R.attr.icon_clear))); applyFilter(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); ImageView imgClear = (ImageView) findViewById(R.id.imgClear); imgClear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { etFilter.setText(""); } }); // Setup used filter boolean fUsed = PrivacyManager.getSettingBool(null, ActivityMain.this, 0, PrivacyManager.cSettingFUsed, false, false); CheckBox cFbUsed = (CheckBox) findViewById(R.id.cbFUsed); cFbUsed.setChecked(fUsed); cFbUsed.setOnCheckedChangeListener(this); // Setup internet filter boolean fInternet = PrivacyManager.getSettingBool(null, ActivityMain.this, 0, PrivacyManager.cSettingFInternet, false, false); CheckBox cbFInternet = (CheckBox) findViewById(R.id.cbFInternet); cbFInternet.setChecked(fInternet); cbFInternet.setOnCheckedChangeListener(this); // Setup restriction filter boolean fRestriction = PrivacyManager.getSettingBool(null, ActivityMain.this, 0, PrivacyManager.cSettingFRestriction, false, false); CheckBox cbFRestriction = (CheckBox) findViewById(R.id.cbFRestriction); cbFRestriction.setChecked(fRestriction); cbFRestriction.setOnCheckedChangeListener(this); boolean fRestrictionNot = PrivacyManager.getSettingBool(null, ActivityMain.this, 0, PrivacyManager.cSettingFRestrictionNot, false, false); CheckBox cbFRestrictionNot = (CheckBox) findViewById(R.id.cbFRestrictionNot); cbFRestrictionNot.setChecked(fRestrictionNot); cbFRestrictionNot.setOnCheckedChangeListener(this); // Setup permission filter boolean fPermission = PrivacyManager.getSettingBool(null, ActivityMain.this, 0, PrivacyManager.cSettingFPermission, true, false); CheckBox cbFPermission = (CheckBox) findViewById(R.id.cbFPermission); cbFPermission.setChecked(fPermission); cbFPermission.setOnCheckedChangeListener(this); // Setup user filter boolean fUser = PrivacyManager.getSettingBool(null, ActivityMain.this, 0, PrivacyManager.cSettingFUser, true, false); final CheckBox cbFUser = (CheckBox) findViewById(R.id.cbFUser); cbFUser.setChecked(fUser); cbFUser.setOnCheckedChangeListener(this); // Setup system filter boolean fSystem = PrivacyManager.getSettingBool(null, ActivityMain.this, 0, PrivacyManager.cSettingFSystem, false, false); final CheckBox cbFSystem = (CheckBox) findViewById(R.id.cbFSystem); cbFSystem.setChecked(fSystem); cbFSystem.setOnCheckedChangeListener(this); // Hide filters if (savedInstanceState != null && savedInstanceState.containsKey("Filters")) mFiltersHidden = !savedInstanceState.getBoolean("Filters"); toggleFiltersVisibility(); // Hide categories if (savedInstanceState != null && savedInstanceState.containsKey("Categories")) mCategoriesHidden = !savedInstanceState.getBoolean("Categories"); toggleCategoriesVisibility(); // Handle toggle filters visibility TextView tvFilterDetail = (TextView) findViewById(R.id.tvFilterDetail); tvFilterDetail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toggleFiltersVisibility(); } }); // Handle toggle categories visibility TextView tvCategoryDetail = (TextView) findViewById(R.id.tvCategoryDetail); tvCategoryDetail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toggleCategoriesVisibility(); } }); // Handle post share operation done message if (mSharingState != null) { TextView tvState = (TextView) findViewById(R.id.tvState); tvState.setText(mSharingState); mSharingState = null; } // Start task to get app list AppListTask appListTask = new AppListTask(); appListTask.executeOnExecutor(mExecutor, (Object) null); // Check environment Requirements.check(this); // Licensing checkLicense(); // Listen for package add/remove IntentFilter iff = new IntentFilter(); iff.addAction(Intent.ACTION_PACKAGE_ADDED); iff.addAction(Intent.ACTION_PACKAGE_REMOVED); iff.addDataScheme("package"); registerReceiver(mPackageChangeReceiver, iff); // Listen for progress reports IntentFilter filter = new IntentFilter(); filter.addAction(ActivityShare.cProgressReport); LocalBroadcastManager.getInstance(this).registerReceiver(progressListener, filter); // First run if (PrivacyManager.getSettingBool(null, this, 0, PrivacyManager.cSettingFirstRun, true, false)) { optionAbout(); PrivacyManager.setSetting(null, this, 0, PrivacyManager.cSettingFirstRun, Boolean.FALSE.toString()); } mCheck = Util.getTriStateCheckBox(this); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putBoolean("Filters", mFiltersHidden); outState.putBoolean("Categories", mCategoriesHidden); super.onSaveInstanceState(outState); } @Override protected void onResume() { super.onResume(); if (mAppAdapter != null) mAppAdapter.notifyDataSetChanged(); } @Override protected void onDestroy() { super.onDestroy(); if (mPackageChangeReceiver != null) unregisterReceiver(mPackageChangeReceiver); // Stop listening for progress reports LocalBroadcastManager.getInstance(this).unregisterReceiver(progressListener); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ACTIVITY_LICENSE) { // Result for license check if (data != null) { int code = data.getIntExtra("Code", -1); int reason = data.getIntExtra("Reason", -1); String sReason; if (reason == LICENSED) sReason = "LICENSED"; else if (reason == NOT_LICENSED) sReason = "NOT_LICENSED"; else if (reason == RETRY) sReason = "RETRY"; else if (reason == ERROR_CONTACTING_SERVER) sReason = "ERROR_CONTACTING_SERVER"; else if (reason == ERROR_INVALID_PACKAGE_NAME) sReason = "ERROR_INVALID_PACKAGE_NAME"; else if (reason == ERROR_NON_MATCHING_UID) sReason = "ERROR_NON_MATCHING_UID"; else sReason = Integer.toString(reason); Util.log(null, Log.WARN, "Licensing: code=" + code + " reason=" + sReason); if (code > 0) { Util.setPro(true); invalidateOptionsMenu(); Toast toast = Toast.makeText(this, getString(R.string.menu_pro), Toast.LENGTH_LONG); toast.show(); } else if (reason == RETRY) { Util.setPro(false); new Handler().postDelayed(new Runnable() { @Override public void run() { checkLicense(); } }, 30 * 1000); } } } else if (requestCode == ACTIVITY_EXPORT) { // Exported: clean-up UI sharingDone(); // send share intent if (data != null && data.hasExtra(ActivityShare.cFileName)) { Intent intent = new Intent(android.content.Intent.ACTION_SEND); intent.setType("text/xml"); intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + data.getStringExtra(ActivityShare.cFileName))); startActivity(Intent.createChooser(intent, String.format(getString(R.string.msg_saved_to), data.getStringExtra(ActivityShare.cFileName)))); } } else if (requestCode == ACTIVITY_IMPORT) { // Imported: clean-up UI sharingDone(); ActivityMain.this.recreate(); } else if (requestCode == ACTIVITY_IMPORT_SELECT) { // Result for import file choice if (resultCode == RESULT_CANCELED) sharingDone(); else if (data != null) try { String fileName = data.getData().getPath(); Intent intent = new Intent("biz.bokhorst.xprivacy.action.IMPORT"); intent.putExtra(ActivityShare.cFileName, fileName); startActivityForResult(intent, ACTIVITY_IMPORT); } catch (Throwable ex) { Util.bug(null, ex); } } else if (requestCode == ACTIVITY_FETCH) { // Fetched: clean-up UI sharingDone(); ActivityMain.this.recreate(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean pro = (Util.hasProLicense(this) != null); boolean mounted = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); menu.findItem(R.id.menu_export).setEnabled(pro && mounted && !mSharing); menu.findItem(R.id.menu_import).setEnabled(pro && mounted && !mSharing); menu.findItem(R.id.menu_fetch).setEnabled(!mSharing); menu.findItem(R.id.menu_pro).setVisible(!pro); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { try { switch (item.getItemId()) { case R.id.menu_help: optionHelp(); return true; case R.id.menu_all: optionAll(); return true; case R.id.menu_usage: optionUsage(); return true; case R.id.menu_settings: SettingsDialog.edit(ActivityMain.this, null); return true; case R.id.menu_template: optionTemplate(); return true; case R.id.menu_report: optionReportIssue(); return true; case R.id.menu_export: optionExport(); return true; case R.id.menu_import: optionImport(); return true; case R.id.menu_fetch: optionFetch(); return true; case R.id.menu_theme: optionSwitchTheme(); return true; case R.id.menu_pro: optionPro(); return true; case R.id.menu_about: optionAbout(); return true; default: return super.onOptionsItemSelected(item); } } catch (Throwable ex) { Util.bug(null, ex); return true; } } // Filtering @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { selectRestriction(pos); } @Override public void onNothingSelected(AdapterView<?> parent) { selectRestriction(0); } private void selectRestriction(int pos) { if (mAppAdapter != null) { String restrictionName = (pos == 0 ? null : PrivacyManager.getRestrictions().get(pos - 1)); mAppAdapter.setRestrictionName(restrictionName); applyFilter(); } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { CheckBox cbFUsed = (CheckBox) findViewById(R.id.cbFUsed); CheckBox cbFInternet = (CheckBox) findViewById(R.id.cbFInternet); CheckBox cbFRestriction = (CheckBox) findViewById(R.id.cbFRestriction); CheckBox cbFRestrictionNot = (CheckBox) findViewById(R.id.cbFRestrictionNot); CheckBox cbFPermission = (CheckBox) findViewById(R.id.cbFPermission); CheckBox cbFUser = (CheckBox) findViewById(R.id.cbFUser); CheckBox cbFSystem = (CheckBox) findViewById(R.id.cbFSystem); if (buttonView == cbFUsed) PrivacyManager.setSetting(null, ActivityMain.this, 0, PrivacyManager.cSettingFUsed, Boolean.toString(isChecked)); else if (buttonView == cbFInternet) PrivacyManager.setSetting(null, ActivityMain.this, 0, PrivacyManager.cSettingFInternet, Boolean.toString(isChecked)); else if (buttonView == cbFRestriction) PrivacyManager.setSetting(null, ActivityMain.this, 0, PrivacyManager.cSettingFRestriction, Boolean.toString(isChecked)); else if (buttonView == cbFRestrictionNot) PrivacyManager.setSetting(null, ActivityMain.this, 0, PrivacyManager.cSettingFRestrictionNot, Boolean.toString(isChecked)); else if (buttonView == cbFPermission) PrivacyManager.setSetting(null, ActivityMain.this, 0, PrivacyManager.cSettingFPermission, Boolean.toString(isChecked)); else if (buttonView == cbFUser) { if (isChecked) cbFSystem.setChecked(false); PrivacyManager.setSetting(null, ActivityMain.this, 0, PrivacyManager.cSettingFUser, Boolean.toString(isChecked)); } else if (buttonView == cbFSystem) { if (isChecked) cbFUser.setChecked(false); PrivacyManager.setSetting(null, ActivityMain.this, 0, PrivacyManager.cSettingFSystem, Boolean.toString(isChecked)); } applyFilter(); } private void applyFilter() { if (mAppAdapter != null) { EditText etFilter = (EditText) findViewById(R.id.etFilter); CheckBox cFbUsed = (CheckBox) findViewById(R.id.cbFUsed); CheckBox cbFInternet = (CheckBox) findViewById(R.id.cbFInternet); CheckBox cbFRestriction = (CheckBox) findViewById(R.id.cbFRestriction); CheckBox cbFRestrictionNot = (CheckBox) findViewById(R.id.cbFRestrictionNot); CheckBox cbFPermission = (CheckBox) findViewById(R.id.cbFPermission); CheckBox cbFUser = (CheckBox) findViewById(R.id.cbFUser); CheckBox cbFSystem = (CheckBox) findViewById(R.id.cbFSystem); ProgressBar pbFilter = (ProgressBar) findViewById(R.id.pbFilter); TextView tvStats = (TextView) findViewById(R.id.tvStats); TextView tvState = (TextView) findViewById(R.id.tvState); String filter = String.format("%s\n%b\n%b\n%b\n%b\n%b\n%b\n%b", etFilter.getText().toString(), cFbUsed.isChecked(), cbFInternet.isChecked(), cbFRestriction.isChecked(), cbFRestrictionNot.isChecked(), cbFPermission.isChecked(), cbFUser.isChecked(), cbFSystem.isChecked()); pbFilter.setVisibility(ProgressBar.VISIBLE); tvStats.setVisibility(TextView.GONE); // Adjust progress state width RelativeLayout.LayoutParams tvStateLayout = (RelativeLayout.LayoutParams) tvState.getLayoutParams(); tvStateLayout.addRule(RelativeLayout.LEFT_OF, R.id.pbFilter); mAppAdapter.getFilter().filter(filter); } } // Options private void optionAll() { // Check if some restricted boolean some = false; for (int pos = 0; pos < mAppAdapter.getCount(); pos++) { ApplicationInfoEx xAppInfo = mAppAdapter.getItem(pos); for (boolean restricted : PrivacyManager.getRestricted(ActivityMain.this, xAppInfo.getUid(), mAppAdapter.getRestrictionName())) if (restricted) { some = true; break; } if (some) break; } final boolean someRestricted = some; // Are you sure? AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle(getString(someRestricted ? R.string.menu_clear_all : R.string.menu_restrict_all)); alertDialogBuilder.setMessage(getString(R.string.msg_sure)); alertDialogBuilder.setIcon(Util.getThemed(this, R.attr.icon_launcher)); alertDialogBuilder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mAppAdapter != null) { // Apply action for (int pos = 0; pos < mAppAdapter.getCount(); pos++) { ApplicationInfoEx xAppInfo = mAppAdapter.getItem(pos); if (mAppAdapter.getRestrictionName() == null) { for (String restrictionName : PrivacyManager.getRestrictions()) PrivacyManager.setRestricted(null, ActivityMain.this, xAppInfo.getUid(), restrictionName, null, !someRestricted); } else PrivacyManager.setRestricted(null, ActivityMain.this, xAppInfo.getUid(), mAppAdapter.getRestrictionName(), null, !someRestricted); } // Refresh mAppAdapter.notifyDataSetChanged(); } } }); alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } private void optionUsage() { Intent intent = new Intent(this, ActivityUsage.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void optionTemplate() { // Get restriction categories final List<String> listRestriction = PrivacyManager.getRestrictions(); CharSequence[] options = new CharSequence[listRestriction.size()]; boolean[] selection = new boolean[listRestriction.size()]; for (int i = 0; i < listRestriction.size(); i++) { options[i] = PrivacyManager.getLocalizedName(this, listRestriction.get(i)); selection[i] = PrivacyManager.getSettingBool(null, this, 0, String.format("Template.%s", listRestriction.get(i)), true, false); } // Build dialog AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle(getString(R.string.menu_template)); alertDialogBuilder.setIcon(Util.getThemed(this, R.attr.icon_launcher)); alertDialogBuilder.setMultiChoiceItems(options, selection, new DialogInterface.OnMultiChoiceClickListener() { public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) { PrivacyManager.setSetting(null, ActivityMain.this, 0, String.format("Template.%s", listRestriction.get(whichButton)), Boolean.toString(isChecked)); } }); alertDialogBuilder.setPositiveButton(getString(R.string.msg_done), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Do nothing } }); // Show dialog AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } private void optionReportIssue() { // Report issue Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/M66B/XPrivacy/issues")); startActivity(browserIntent); } private void optionExport() { sharingStart(); Intent file = new Intent(Intent.ACTION_GET_CONTENT); file.setType("file/*"); boolean multiple = Util.isIntentAvailable(ActivityMain.this, file); Intent intent = new Intent("biz.bokhorst.xprivacy.action.EXPORT"); intent.putExtra(ActivityShare.cFileName, ActivityShare.getFileName(multiple)); startActivityForResult(intent, ACTIVITY_EXPORT); } private void optionImport() { sharingStart(); Intent file = new Intent(Intent.ACTION_GET_CONTENT); file.setType("file/*"); if (Util.isIntentAvailable(ActivityMain.this, file)) { Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT); Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/.xprivacy/"); chooseFile.setDataAndType(uri, "text/xml"); Intent intent = Intent.createChooser(chooseFile, getString(R.string.app_name)); startActivityForResult(intent, ACTIVITY_IMPORT_SELECT); } else { Intent intent = new Intent("biz.bokhorst.xprivacy.action.IMPORT"); intent.putExtra(ActivityShare.cFileName, ActivityShare.getFileName(false)); startActivityForResult(intent, ACTIVITY_IMPORT); } } private void optionFetch() { - sharingStart(); - if (Util.getProLicense() == null) { // Redirect to pro page Intent browserIntent = new Intent(Intent.ACTION_VIEW, cProUri); startActivity(browserIntent); } else { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle(getString(R.string.app_name)); alertDialogBuilder.setMessage(getString(R.string.msg_sure)); alertDialogBuilder.setIcon(Util.getThemed(this, R.attr.icon_launcher)); alertDialogBuilder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { + sharingStart(); Intent intent = new Intent("biz.bokhorst.xprivacy.action.FETCH"); startActivityForResult(intent, ACTIVITY_FETCH); } }); alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } } private void optionSwitchTheme() { String themeName = PrivacyManager.getSetting(null, this, 0, PrivacyManager.cSettingTheme, "", false); themeName = (themeName.equals("Dark") ? "Light" : "Dark"); PrivacyManager.setSetting(null, this, 0, PrivacyManager.cSettingTheme, themeName); this.recreate(); } private void optionPro() { // Redirect to pro page Intent browserIntent = new Intent(Intent.ACTION_VIEW, cProUri); startActivity(browserIntent); } private void optionAbout() { // About Dialog dlgAbout = new Dialog(this); dlgAbout.requestWindowFeature(Window.FEATURE_LEFT_ICON); dlgAbout.setTitle(getString(R.string.app_name)); dlgAbout.setContentView(R.layout.about); dlgAbout.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, Util.getThemed(this, R.attr.icon_launcher)); // Show version try { PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); TextView tvVersion = (TextView) dlgAbout.findViewById(R.id.tvVersion); tvVersion.setText(String.format(getString(R.string.app_version), pInfo.versionName, pInfo.versionCode)); } catch (Throwable ex) { Util.bug(null, ex); } // Show Xposed version int xVersion = Util.getXposedAppProcessVersion(); TextView tvXVersion = (TextView) dlgAbout.findViewById(R.id.tvXVersion); tvXVersion.setText(String.format(getString(R.string.app_xversion), xVersion)); // Show license String licensed = Util.hasProLicense(this); TextView tvLicensed = (TextView) dlgAbout.findViewById(R.id.tvLicensed); if (licensed == null) tvLicensed.setText(String.format(getString(R.string.msg_licensed), Environment .getExternalStorageDirectory().getAbsolutePath())); else tvLicensed.setText(String.format(getString(R.string.msg_licensed), licensed)); dlgAbout.setCancelable(true); dlgAbout.show(); } private void optionHelp() { // Show help Dialog dialog = new Dialog(ActivityMain.this); dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON); dialog.setTitle(getString(R.string.help_application)); dialog.setContentView(R.layout.help); dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, Util.getThemed(this, R.attr.icon_launcher)); TextView tvHelpHalf = (TextView) dialog.findViewById(R.id.help_half); Drawable dHalf = new BitmapDrawable(getResources(), mCheck[1]); dHalf.setBounds(0, 0, 48, 48); tvHelpHalf.setCompoundDrawables(dHalf, null, null, null); dialog.setCancelable(true); dialog.show(); } private void toggleFiltersVisibility() { TextView tvFilterDetail = (TextView) findViewById(R.id.tvFilterDetail); View vFilterHighlight = findViewById(R.id.vFilterHighlight); EditText etFilter = (EditText) findViewById(R.id.etFilter); LinearLayout llFilters = (LinearLayout) findViewById(R.id.llFilters); LinearLayout llCategories = (LinearLayout) findViewById(R.id.llCategories); CheckBox cbFUsed = (CheckBox) findViewById(R.id.cbFUsed); CheckBox cbFInternet = (CheckBox) findViewById(R.id.cbFInternet); CheckBox cbFRestriction = (CheckBox) findViewById(R.id.cbFRestriction); CheckBox cbFPermission = (CheckBox) findViewById(R.id.cbFPermission); CheckBox cbFUser = (CheckBox) findViewById(R.id.cbFUser); CheckBox cbFSystem = (CheckBox) findViewById(R.id.cbFSystem); if (mFiltersHidden) { // Change visibility llFilters.setVisibility(LinearLayout.VISIBLE); llCategories.setVisibility(LinearLayout.GONE); tvFilterDetail.setText(R.string.title_filters); if (!mCategoriesHidden) toggleCategoriesVisibility(); } else { int numberOfFilters = 0; // Count number of activate filters if (etFilter.getText().length() > 0) numberOfFilters++; if (cbFUsed.isChecked()) numberOfFilters++; if (cbFInternet.isChecked()) numberOfFilters++; if (cbFRestriction.isChecked()) numberOfFilters++; if (cbFPermission.isChecked()) numberOfFilters++; if (cbFUser.isChecked()) numberOfFilters++; if (cbFSystem.isChecked()) numberOfFilters++; // Change text tvFilterDetail.setText(getResources().getQuantityString(R.plurals.title_active_filters, numberOfFilters, numberOfFilters)); // Change visibility llFilters.setVisibility(LinearLayout.GONE); } mFiltersHidden = !mFiltersHidden; vFilterHighlight.setBackgroundResource(mFiltersHidden ? android.R.color.transparent : Util.getThemed(this, android.R.attr.colorActivatedHighlight)); } private void toggleCategoriesVisibility() { TextView tvCategories = (TextView) findViewById(R.id.tvCategoryDetail); View vCategoryHighlight = findViewById(R.id.vCategoryHighlight); LinearLayout llFilters = (LinearLayout) findViewById(R.id.llFilters); LinearLayout llCategories = (LinearLayout) findViewById(R.id.llCategories); if (mCategoriesHidden) { // Change visibility llFilters.setVisibility(LinearLayout.GONE); llCategories.setVisibility(LinearLayout.VISIBLE); tvCategories.setText(R.string.title_categories); if (!mFiltersHidden) toggleFiltersVisibility(); } else { // Change visibility llCategories.setVisibility(LinearLayout.GONE); tvCategories.setText((String) spRestriction.getSelectedItem()); } mCategoriesHidden = !mCategoriesHidden; vCategoryHighlight.setBackgroundResource(mCategoriesHidden ? android.R.color.transparent : Util.getThemed(this, android.R.attr.colorActivatedHighlight)); } // Tasks private class AppListTask extends AsyncTask<Object, Integer, List<ApplicationInfoEx>> { private String mRestrictionName; private ProgressDialog mProgressDialog; @Override protected List<ApplicationInfoEx> doInBackground(Object... params) { mRestrictionName = null; // Delegate return ApplicationInfoEx.getXApplicationList(ActivityMain.this, mProgressDialog); } @Override protected void onPreExecute() { super.onPreExecute(); // Show progress dialog ListView lvApp = (ListView) findViewById(R.id.lvApp); mProgressDialog = new ProgressDialog(lvApp.getContext()); mProgressDialog.setMessage(getString(R.string.msg_loading)); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setProgressNumberFormat(null); mProgressDialog.setCancelable(false); mProgressDialog.show(); } @Override protected void onPostExecute(List<ApplicationInfoEx> listApp) { super.onPostExecute(listApp); // Display app list mAppAdapter = new AppListAdapter(ActivityMain.this, R.layout.mainentry, listApp, mRestrictionName); ListView lvApp = (ListView) findViewById(R.id.lvApp); lvApp.setAdapter(mAppAdapter); // Dismiss progress dialog try { mProgressDialog.dismiss(); } catch (Throwable ex) { Util.bug(null, ex); } // Restore state ActivityMain.this.selectRestriction(spRestriction.getSelectedItemPosition()); } } // Adapters private class SpinnerAdapter extends ArrayAdapter<String> { public SpinnerAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } } @SuppressLint("DefaultLocale") private class AppListAdapter extends ArrayAdapter<ApplicationInfoEx> { private Context mContext; private List<ApplicationInfoEx> mListApp; private String mRestrictionName; private LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); public AppListAdapter(Context context, int resource, List<ApplicationInfoEx> objects, String initialRestrictionName) { super(context, resource, objects); mContext = context; mListApp = new ArrayList<ApplicationInfoEx>(); mListApp.addAll(objects); mRestrictionName = initialRestrictionName; } public void setRestrictionName(String restrictionName) { mRestrictionName = restrictionName; } public String getRestrictionName() { return mRestrictionName; } @Override public Filter getFilter() { return new AppFilter(); } private class AppFilter extends Filter { public AppFilter() { } @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults results = new FilterResults(); // Get arguments String[] components = ((String) constraint).split("\\n"); String fName = components[0]; boolean fUsed = Boolean.parseBoolean(components[1]); boolean fInternet = Boolean.parseBoolean(components[2]); boolean fRestricted = Boolean.parseBoolean(components[3]); boolean fRestrictedNot = Boolean.parseBoolean(components[4]); boolean fPermission = Boolean.parseBoolean(components[5]); boolean fUser = Boolean.parseBoolean(components[6]); boolean fSystem = Boolean.parseBoolean(components[7]); // Match applications int current = 0; int max = AppListAdapter.this.mListApp.size(); List<ApplicationInfoEx> lstApp = new ArrayList<ApplicationInfoEx>(); for (ApplicationInfoEx xAppInfo : AppListAdapter.this.mListApp) { current++; if (!mSharing && current % 5 == 0) { // Send progress info to main activity Intent progressIntent = new Intent(ActivityShare.cProgressReport); progressIntent.putExtra(ActivityShare.cProgressMessage, getString(R.string.msg_filtering)); progressIntent.putExtra(ActivityShare.cProgressMax, max); progressIntent.putExtra(ActivityShare.cProgressValue, current); LocalBroadcastManager.getInstance(ActivityMain.this).sendBroadcast(progressIntent); } // Get if name contains boolean contains = false; if (!fName.equals("")) contains = (xAppInfo.toString().toLowerCase().contains(((String) fName).toLowerCase())); // Get if used boolean used = false; if (fUsed) used = (PrivacyManager.getUsed(mContext, xAppInfo.getUid(), mRestrictionName, null) != 0); // Get if internet boolean internet = false; if (fInternet) internet = xAppInfo.hasInternet(mContext); // Get some restricted boolean someRestricted = false; if (fRestricted) for (boolean restricted : PrivacyManager.getRestricted(mContext, xAppInfo.getUid(), mRestrictionName)) if (restricted) { someRestricted = true; break; } // Get Android permission boolean permission = false; if (fPermission) if (mRestrictionName == null) permission = true; else if (PrivacyManager.hasPermission(mContext, xAppInfo.getPackageName(), mRestrictionName) || PrivacyManager.getUsed(mContext, xAppInfo.getUid(), mRestrictionName, null) > 0) permission = true; // Get if user boolean user = false; if (fUser) user = !xAppInfo.isSystem(); // Get if system boolean system = false; if (fSystem) system = xAppInfo.isSystem(); // Apply filters if ((fName.equals("") ? true : contains) && (fUsed ? used : true) && (fInternet ? internet : true) && (fRestricted ? (fRestrictedNot ? !someRestricted : someRestricted) : true) && (fPermission ? permission : true) && (fUser ? user : true) && (fSystem ? system : true)) lstApp.add(xAppInfo); } synchronized (this) { results.values = lstApp; results.count = lstApp.size(); } return results; } @Override @SuppressWarnings("unchecked") protected void publishResults(CharSequence constraint, FilterResults results) { clear(); TextView tvStats = (TextView) findViewById(R.id.tvStats); TextView tvState = (TextView) findViewById(R.id.tvState); ProgressBar pbFilter = (ProgressBar) findViewById(R.id.pbFilter); pbFilter.setVisibility(ProgressBar.GONE); tvStats.setVisibility(TextView.VISIBLE); tvStats.setText(results.count + "/" + AppListAdapter.this.mListApp.size()); Intent progressIntent = new Intent(ActivityShare.cProgressReport); progressIntent.putExtra(ActivityShare.cProgressMessage, getString(R.string.title_restrict)); progressIntent.putExtra(ActivityShare.cProgressMax, 1); progressIntent.putExtra(ActivityShare.cProgressValue, 0); LocalBroadcastManager.getInstance(ActivityMain.this).sendBroadcast(progressIntent); // Adjust progress state width RelativeLayout.LayoutParams tvStateLayout = (RelativeLayout.LayoutParams) tvState.getLayoutParams(); tvStateLayout.addRule(RelativeLayout.LEFT_OF, R.id.tvStats); if (results.values == null) notifyDataSetInvalidated(); else { addAll((ArrayList<ApplicationInfoEx>) results.values); notifyDataSetChanged(); } } } private class ViewHolder { private View row; private int position; public ImageView imgIcon; public ImageView imgUsed; public ImageView imgGranted; public ImageView imgInternet; public ImageView imgFrozen; public TextView tvName; public ImageView imgCBName; public RelativeLayout rlName; public ViewHolder(View theRow, int thePosition) { row = theRow; position = thePosition; imgIcon = (ImageView) row.findViewById(R.id.imgIcon); imgUsed = (ImageView) row.findViewById(R.id.imgUsed); imgGranted = (ImageView) row.findViewById(R.id.imgGranted); imgInternet = (ImageView) row.findViewById(R.id.imgInternet); imgFrozen = (ImageView) row.findViewById(R.id.imgFrozen); tvName = (TextView) row.findViewById(R.id.tvName); imgCBName = (ImageView) row.findViewById(R.id.imgCBName); rlName = (RelativeLayout) row.findViewById(R.id.rlName); } } private class HolderTask extends AsyncTask<Object, Object, Object> { private int position; private ViewHolder holder; private ApplicationInfoEx xAppInfo = null; private boolean used; private boolean granted = true; private List<String> listRestriction; private boolean allRestricted = true; private boolean someRestricted = false; public HolderTask(int thePosition, ViewHolder theHolder, ApplicationInfoEx theAppInfo) { position = thePosition; holder = theHolder; xAppInfo = theAppInfo; } @Override protected Object doInBackground(Object... params) { if (holder.position == position && xAppInfo != null) { // Get if used used = (PrivacyManager.getUsed(holder.row.getContext(), xAppInfo.getUid(), mRestrictionName, null) != 0); // Get if granted if (mRestrictionName != null) if (!PrivacyManager.hasPermission(holder.row.getContext(), xAppInfo.getPackageName(), mRestrictionName)) granted = false; // Get restrictions if (mRestrictionName == null) listRestriction = PrivacyManager.getRestrictions(); else { listRestriction = new ArrayList<String>(); listRestriction.add(mRestrictionName); } // Get all/some restricted for (boolean restricted : PrivacyManager.getRestricted(holder.row.getContext(), xAppInfo.getUid(), mRestrictionName)) { allRestricted = (allRestricted && restricted); someRestricted = (someRestricted || restricted); } } return null; } @Override protected void onPostExecute(Object result) { if (holder.position == position && xAppInfo != null) { // Draw border around icon if (xAppInfo.getIcon(ActivityMain.this) instanceof BitmapDrawable) { // Get icon bitmap Bitmap icon = ((BitmapDrawable) xAppInfo.getIcon(ActivityMain.this)).getBitmap(); // Get list item height TypedArray arrayHeight = getTheme().obtainStyledAttributes( new int[] { android.R.attr.listPreferredItemHeightSmall }); int height = (int) Math.round(arrayHeight.getDimension(0, 32) * getResources().getDisplayMetrics().density + 0.5f); arrayHeight.recycle(); // Scale icon to list item height icon = Bitmap.createScaledBitmap(icon, height, height, true); // Create bitmap with borders int borderSize = (int) Math.round(getResources().getDisplayMetrics().density + 0.5f); Bitmap bitmap = Bitmap.createBitmap(icon.getWidth() + 2 * borderSize, icon.getHeight() + 2 * borderSize, icon.getConfig()); // Get highlight color TypedArray arrayColor = getTheme().obtainStyledAttributes( new int[] { android.R.attr.colorActivatedHighlight }); int textColor = arrayColor.getColor(0, 0xFF00FF); arrayColor.recycle(); // Draw bitmap with borders Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); paint.setColor(textColor); paint.setStyle(Style.STROKE); paint.setStrokeWidth(borderSize); canvas.drawRect(0, 0, bitmap.getWidth(), bitmap.getHeight(), paint); paint = new Paint(Paint.FILTER_BITMAP_FLAG); canvas.drawBitmap(icon, borderSize, borderSize, paint); // Show bitmap holder.imgIcon.setImageBitmap(bitmap); } holder.imgIcon.setVisibility(View.VISIBLE); // Check if used holder.tvName.setTypeface(null, used ? Typeface.BOLD_ITALIC : Typeface.NORMAL); holder.imgUsed.setVisibility(used ? View.VISIBLE : View.INVISIBLE); // Check if permission holder.imgGranted.setVisibility(granted ? View.VISIBLE : View.INVISIBLE); // Check if internet access holder.imgInternet.setVisibility(xAppInfo.hasInternet(ActivityMain.this) ? View.VISIBLE : View.INVISIBLE); // Check if frozen holder.imgFrozen .setVisibility(xAppInfo.isFrozen(ActivityMain.this) ? View.VISIBLE : View.INVISIBLE); // Display restriction if (allRestricted) holder.imgCBName.setImageBitmap(mCheck[2]); // Full else if (someRestricted) holder.imgCBName.setImageBitmap(mCheck[1]); // Half else holder.imgCBName.setImageBitmap(mCheck[0]); // Off holder.imgCBName.setVisibility(View.VISIBLE); // Listen for restriction changes holder.rlName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { // Get all/some restricted boolean allRestricted = true; boolean someRestricted = false; for (boolean restricted : PrivacyManager.getRestricted(view.getContext(), xAppInfo.getUid(), mRestrictionName)) { allRestricted = (allRestricted && restricted); someRestricted = (someRestricted || restricted); } // Process click if (mRestrictionName == null && someRestricted) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityMain.this); alertDialogBuilder.setTitle(getString(R.string.app_name)); alertDialogBuilder.setMessage(getString(R.string.msg_sure)); alertDialogBuilder.setIcon(Util.getThemed(ActivityMain.this, R.attr.icon_launcher)); alertDialogBuilder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Update restriction PrivacyManager.deleteRestrictions(view.getContext(), xAppInfo.getUid()); // Update visible state holder.imgCBName.setImageBitmap(mCheck[0]); // Off } }); alertDialogBuilder.setNegativeButton(getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } else { // Update restriction for (String restrictionName : listRestriction) PrivacyManager.setRestricted(null, view.getContext(), xAppInfo.getUid(), restrictionName, null, !someRestricted); // Update all/some restricted allRestricted = true; someRestricted = false; for (boolean restricted : PrivacyManager.getRestricted(view.getContext(), xAppInfo.getUid(), mRestrictionName)) { allRestricted = (allRestricted && restricted); someRestricted = (someRestricted || restricted); } // Update visible state if (allRestricted) holder.imgCBName.setImageBitmap(mCheck[2]); // Full else if (someRestricted) holder.imgCBName.setImageBitmap(mCheck[1]); // Half else holder.imgCBName.setImageBitmap(mCheck[0]); // Off } } }); } } } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.mainentry, null); holder = new ViewHolder(convertView, position); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); holder.position = position; } // Get info final ApplicationInfoEx xAppInfo = getItem(holder.position); // Set background color if (xAppInfo.isSystem()) holder.row.setBackgroundColor(getResources().getColor( Util.getThemed(ActivityMain.this, R.attr.color_dangerous))); else holder.row.setBackgroundColor(Color.TRANSPARENT); // Handle details click holder.imgIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intentSettings = new Intent(view.getContext(), ActivityApp.class); intentSettings.putExtra(ActivityApp.cPackageName, xAppInfo.getPackageName()); intentSettings.putExtra(ActivityApp.cRestrictionName, mRestrictionName); intentSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); view.getContext().startActivity(intentSettings); } }); // Set data holder.imgIcon.setVisibility(View.INVISIBLE); holder.tvName.setText(xAppInfo.toString()); holder.tvName.setTypeface(null, Typeface.NORMAL); holder.imgUsed.setVisibility(View.INVISIBLE); holder.imgGranted.setVisibility(View.INVISIBLE); holder.imgInternet.setVisibility(View.INVISIBLE); holder.imgFrozen.setVisibility(View.INVISIBLE); holder.imgCBName.setVisibility(View.INVISIBLE); // Async update new HolderTask(position, holder, xAppInfo).executeOnExecutor(mExecutor, (Object) null); return convertView; } } // Share operations progress listener private void sharingStart() { - mSharing = true; invalidateOptionsMenu(); } private void sharingDone() { // Re-enable menu items mSharing = false; invalidateOptionsMenu(); // Keep done message for after UI recreation TextView tvState = (TextView) findViewById(R.id.tvState); mSharingState = (String) tvState.getText(); } private BroadcastReceiver progressListener = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // String action = intent.getAction(); String message = intent.getStringExtra(ActivityShare.cProgressMessage); int progress = intent.getIntExtra(ActivityShare.cProgressValue, 0); int max = intent.getIntExtra(ActivityShare.cProgressMax, 1); setProgress(message, progress, max); } }; private void setProgress(String text, int progress, int max) { // Set up the progress bar if (mProgressWidth == 0) { final View vProgressEmpty = (View) findViewById(R.id.vProgressEmpty); mProgressWidth = vProgressEmpty.getMeasuredWidth(); } // Display stuff TextView tvState = (TextView) findViewById(R.id.tvState); if (text != null) tvState.setText(text); if (max == 0) max = 1; mProgress = (int) ((float) mProgressWidth) * progress / max; updateProgress(); } private void updateProgress() { View vProgressFull = (View) findViewById(R.id.vProgressFull); vProgressFull.getLayoutParams().width = mProgress; } // Helper methods private void checkLicense() { if (Util.hasProLicense(this) == null) { if (Util.isProEnablerInstalled(this)) try { Util.log(null, Log.INFO, "Licensing: check"); startActivityForResult(new Intent("biz.bokhorst.xprivacy.pro.CHECK"), ACTIVITY_LICENSE); } catch (Throwable ex) { Util.bug(null, ex); } } } }
false
false
null
null
diff --git a/src/main/java/org/apache/juddi/function/SetPublisherAssertionsFunction.java b/src/main/java/org/apache/juddi/function/SetPublisherAssertionsFunction.java index 8ac49cdef..0efda1fa4 100755 --- a/src/main/java/org/apache/juddi/function/SetPublisherAssertionsFunction.java +++ b/src/main/java/org/apache/juddi/function/SetPublisherAssertionsFunction.java @@ -1,131 +1,158 @@ /* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.juddi.function; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.juddi.datastore.DataStore; import org.apache.juddi.datastore.DataStoreFactory; import org.apache.juddi.datatype.RegistryObject; import org.apache.juddi.datatype.publisher.Publisher; import org.apache.juddi.datatype.request.AuthInfo; import org.apache.juddi.datatype.request.SetPublisherAssertions; import org.apache.juddi.datatype.response.PublisherAssertions; +import org.apache.juddi.datatype.assertion.PublisherAssertion; +import org.apache.juddi.datatype.KeyedReference; import org.apache.juddi.error.RegistryException; import org.apache.juddi.registry.RegistryEngine; +import org.apache.juddi.error.InvalidKeyPassedException; import org.apache.juddi.util.Config; /** * @author Steve Viens (sviens@apache.org) */ public class SetPublisherAssertionsFunction extends AbstractFunction { // private reference to jUDDI Logger private static Log log = LogFactory.getLog(SetPublisherAssertionsFunction.class); /** * */ public SetPublisherAssertionsFunction(RegistryEngine registry) { super(registry); } /** * */ public RegistryObject execute(RegistryObject regObject) throws RegistryException { SetPublisherAssertions request = (SetPublisherAssertions)regObject; String generic = request.getGeneric(); AuthInfo authInfo = request.getAuthInfo(); Vector assertionVector = request.getPublisherAssertionVector(); // aquire a jUDDI datastore instance DataStore dataStore = DataStoreFactory.getDataStore(); try { dataStore.beginTrans(); // validate authentication parameters Publisher publisher = getPublisher(authInfo,dataStore); String publisherID = publisher.getPublisherID(); // validate request parameters & execute + // Per UDDI v2.0 specification, the tModelKey in a passed publisherAssertion CANNOT be null or blank. An invalidKeyPassed error must be thrown. + if (assertionVector != null) { + for (int i = 0; i < assertionVector.size(); i++) { + PublisherAssertion publisherAssertion = (PublisherAssertion)assertionVector.elementAt(i); + if (publisherAssertion != null) { + KeyedReference kr = publisherAssertion.getKeyedReference(); + if (kr != null) { + if (kr.getTModelKey() == null || kr.getTModelKey().length() == 0) { + //throw new InvalidKeyPassedException("tModelKey must be provided in KeyedReference for publisherAssertion: fromKey=" + + // publisherAssertion.getFromKey() + "; toKey=" + publisherAssertion.getToKey()); + throw new InvalidKeyPassedException("tModelKey must be provided in KeyedReference for publisherAssertion: fromKey="); + + } + } + } + + } + } // nothing that requires validation has been identified // set the PublisherAssertions Vector savedAssertionsVector = dataStore.setAssertions(publisherID,assertionVector); dataStore.commit(); PublisherAssertions assertions = new PublisherAssertions(); assertions.setGeneric(generic); assertions.setOperator(Config.getOperator()); assertions.setPublisherAssertionVector(savedAssertionsVector); return assertions; } + catch(InvalidKeyPassedException ivkex) + { + try { dataStore.rollback(); } catch(Exception e) { } + log.error(ivkex); + throw (RegistryException)ivkex; + } catch(RegistryException regex) { try { dataStore.rollback(); } catch(Exception e) { } log.error(regex); throw (RegistryException)regex; } catch(Exception ex) { try { dataStore.rollback(); } catch(Exception e) { } log.error(ex); throw new RegistryException(ex); } finally { if (dataStore != null) dataStore.release(); } } /***************************************************************************/ /***************************** TEST DRIVER *********************************/ /***************************************************************************/ public static void main(String[] args) { // initialize the registry RegistryEngine reg = new RegistryEngine(); reg.init(); try { } catch (Exception ex) { // write execption to the console ex.printStackTrace(); } finally { // destroy the registry reg.dispose(); } } }
false
false
null
null
diff --git a/src/main/java/org/apache/maven/plugin/nar/Java.java b/src/main/java/org/apache/maven/plugin/nar/Java.java index ad35bd68..386dfea7 100644 --- a/src/main/java/org/apache/maven/plugin/nar/Java.java +++ b/src/main/java/org/apache/maven/plugin/nar/Java.java @@ -1,165 +1,165 @@ package org.apache.maven.plugin.nar; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import java.util.Iterator; import java.util.List; import net.sf.antcontrib.cpptasks.CCTask; import net.sf.antcontrib.cpptasks.CUtil; import net.sf.antcontrib.cpptasks.types.CommandLineArgument; import net.sf.antcontrib.cpptasks.types.LibrarySet; import net.sf.antcontrib.cpptasks.types.LinkerArgument; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.tools.ant.BuildException; /** * Java specifications for NAR * * @author Mark Donszelmann */ public class Java { /** * Add Java includes to includepath * * @parameter expression="" default-value="false" * @required */ private boolean include = false; /** * Java Include Paths, relative to a derived ${java.home}. Defaults to: "${java.home}/include" and * "${java.home}/include/<i>os-specific</i>". * * @parameter expression="" */ private List includePaths; /** * Add Java Runtime to linker * * @parameter expression="" default-value="false" * @required */ private boolean link = false; /** * Relative path from derived ${java.home} to the java runtime to link with Defaults to Architecture-OS-Linker * specific value. FIXME table missing * * @parameter expression="" */ private String runtimeDirectory; /** * Name of the runtime * * @parameter expression="" default-value="jvm" */ private String runtime = "jvm"; private AbstractCompileMojo mojo; public Java() { } public void setAbstractCompileMojo( AbstractCompileMojo mojo ) { this.mojo = mojo; } public void addIncludePaths( CCTask task, String outType ) throws MojoFailureException, BuildException, MojoExecutionException { if ( include || mojo.getJavah().getJniDirectory().exists() ) { if ( includePaths != null ) { for ( Iterator i = includePaths.iterator(); i.hasNext(); ) { String path = (String) i.next(); task.createIncludePath().setPath( new File( mojo.getJavaHome( mojo.getAOL() ), path ).getPath() ); } } else { String prefix = mojo.getAOL().getKey() + ".java."; String includes = NarUtil.getDefaults().getProperty( prefix + "include" ); if ( includes != null ) { String[] path = includes.split( ";" ); for ( int i = 0; i < path.length; i++ ) { task.createIncludePath().setPath( new File( mojo.getJavaHome( mojo.getAOL() ), path[i] ).getPath() ); } } } } } public void addRuntime( CCTask task, File javaHome, String os, String prefix ) throws MojoFailureException { if ( link ) { if ( os.equals( OS.MACOSX ) ) { CommandLineArgument.LocationEnum end = new CommandLineArgument.LocationEnum(); end.setValue( "end" ); // add as argument rather than library to avoid argument quoting LinkerArgument framework = new LinkerArgument(); framework.setValue( "-framework" ); framework.setLocation( end ); task.addConfiguredLinkerArg( framework ); LinkerArgument javavm = new LinkerArgument(); javavm.setValue( "JavaVM" ); javavm.setLocation( end ); task.addConfiguredLinkerArg( javavm ); } else { if ( runtimeDirectory == null ) { runtimeDirectory = NarUtil.getDefaults().getProperty( prefix + "runtimeDirectory" ); if ( runtimeDirectory == null ) { throw new MojoFailureException( "NAR: Please specify a <RuntimeDirectory> as part of <Java>" ); } } - mojo.getLog().debug( "Using Java Rumtime Directory: " + runtimeDirectory ); + mojo.getLog().debug( "Using Java Runtime Directory: " + runtimeDirectory ); LibrarySet libset = new LibrarySet(); libset.setProject( mojo.getAntProject() ); libset.setLibs( new CUtil.StringArrayBuilder( runtime ) ); libset.setDir( new File( javaHome, runtimeDirectory ) ); task.addLibset( libset ); } } } } diff --git a/src/main/java/org/apache/maven/plugin/nar/NarCompileMojo.java b/src/main/java/org/apache/maven/plugin/nar/NarCompileMojo.java index 6b55e607..4b2d1f50 100644 --- a/src/main/java/org/apache/maven/plugin/nar/NarCompileMojo.java +++ b/src/main/java/org/apache/maven/plugin/nar/NarCompileMojo.java @@ -1,352 +1,352 @@ package org.apache.maven.plugin.nar; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.sf.antcontrib.cpptasks.CCTask; import net.sf.antcontrib.cpptasks.CUtil; import net.sf.antcontrib.cpptasks.LinkerDef; import net.sf.antcontrib.cpptasks.OutputTypeEnum; import net.sf.antcontrib.cpptasks.RuntimeType; import net.sf.antcontrib.cpptasks.types.LibrarySet; import net.sf.antcontrib.cpptasks.types.LinkerArgument; import net.sf.antcontrib.cpptasks.types.SystemLibrarySet; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.StringUtils; /** * Compiles native source files. * * @goal nar-compile * @phase compile * @requiresDependencyResolution compile * @author Mark Donszelmann */ public class NarCompileMojo extends AbstractCompileMojo { public void execute() throws MojoExecutionException, MojoFailureException { if ( shouldSkip() ) return; // make sure destination is there getTargetDirectory().mkdirs(); // check for source files int noOfSources = 0; noOfSources += getSourcesFor( getCpp() ).size(); noOfSources += getSourcesFor( getC() ).size(); noOfSources += getSourcesFor( getFortran() ).size(); if ( noOfSources > 0 ) { getLog().info( "Compiling " + noOfSources + " native files" ); for ( Iterator i = getLibraries().iterator(); i.hasNext(); ) { createLibrary( getAntProject(), (Library) i.next() ); } } else { getLog().info( "Nothing to compile" ); } try { // FIXME, should the include paths be defined at a higher level ? getCpp().copyIncludeFiles( getMavenProject(), new File( getTargetDirectory(), "include" ) ); } catch ( IOException e ) { throw new MojoExecutionException( "NAR: could not copy include files", e ); } } private List getSourcesFor( Compiler compiler ) throws MojoFailureException { try { List files = new ArrayList(); List srcDirs = compiler.getSourceDirectories(); for ( Iterator i = srcDirs.iterator(); i.hasNext(); ) { File dir = (File) i.next(); if ( dir.exists() ) files.addAll( FileUtils.getFiles( dir, StringUtils.join( compiler.getIncludes().iterator(), "," ), null ) ); } return files; } catch ( IOException e ) { return Collections.EMPTY_LIST; } } private void createLibrary( Project antProject, Library library ) throws MojoExecutionException, MojoFailureException { getLog().debug( "Creating Library " + library ); // configure task CCTask task = new CCTask(); task.setProject( antProject ); // set max cores task.setMaxCores( getMaxCores( getAOL() ) ); // outtype OutputTypeEnum outTypeEnum = new OutputTypeEnum(); String type = library.getType(); outTypeEnum.setValue( type ); task.setOuttype( outTypeEnum ); // stdc++ task.setLinkCPP( library.linkCPP() ); // fortran task.setLinkFortran( library.linkFortran() ); // outDir File outDir = new File( getTargetDirectory(), type.equals( Library.EXECUTABLE ) ? "bin" : "lib" ); outDir = new File( outDir, getAOL().toString() ); if ( !type.equals( Library.EXECUTABLE ) ) outDir = new File( outDir, type ); outDir.mkdirs(); // outFile File outFile; if ( type.equals( Library.EXECUTABLE ) ) { // executable has no version number outFile = new File( outDir, getMavenProject().getArtifactId() ); } else { outFile = new File( outDir, getOutput( getAOL() ) ); } getLog().debug( "NAR - output: '" + outFile + "'" ); task.setOutfile( outFile ); // object directory File objDir = new File( getTargetDirectory(), "obj" ); objDir = new File( objDir, getAOL().toString() ); objDir.mkdirs(); task.setObjdir( objDir ); // failOnError, libtool task.setFailonerror( failOnError( getAOL() ) ); task.setLibtool( useLibtool( getAOL() ) ); // runtime RuntimeType runtimeType = new RuntimeType(); runtimeType.setValue( getRuntime( getAOL() ) ); task.setRuntime( runtimeType ); // add C++ compiler task.addConfiguredCompiler( getCpp().getCompiler( type, getOutput( getAOL() ) ) ); // add C compiler task.addConfiguredCompiler( getC().getCompiler( type, getOutput( getAOL() ) ) ); // add Fortran compiler task.addConfiguredCompiler( getFortran().getCompiler( type, getOutput( getAOL() ) ) ); // add javah include path File jniDirectory = getJavah().getJniDirectory(); if ( jniDirectory.exists() ) task.createIncludePath().setPath( jniDirectory.getPath() ); // add java include paths getJava().addIncludePaths( task, type ); // add dependency include paths for ( Iterator i = getNarManager().getNarDependencies( "compile" ).iterator(); i.hasNext(); ) { // FIXME, handle multiple includes from one NAR NarArtifact narDependency = (NarArtifact) i.next(); String binding = narDependency.getNarInfo().getBinding( getAOL(), Library.STATIC ); getLog().debug( "Looking for " + narDependency + " found binding " + binding ); if ( !binding.equals( Library.JNI ) ) { File include = new File( getNarManager().getNarFile( narDependency ).getParentFile(), "nar/include" ); getLog().debug( "Looking for for directory: " + include ); if ( include.exists() ) { task.createIncludePath().setPath( include.getPath() ); } } } // add linker LinkerDef linkerDefinition = getLinker().getLinker( this, antProject, getOS(), getAOL().getKey() + ".linker.", type ); task.addConfiguredLinker( linkerDefinition ); // add dependency libraries // FIXME: what about PLUGIN and STATIC, depending on STATIC, should we // not add all libraries, see NARPLUGIN-96 if ( type.equals( Library.SHARED ) || type.equals( Library.JNI ) || type.equals( Library.EXECUTABLE ) ) { List depLibOrder = getDependencyLibOrder(); List depLibs = getNarManager().getNarDependencies( "compile" ); // reorder the libraries that come from the nar dependencies // to comply with the order specified by the user if ( ( depLibOrder != null ) && !depLibOrder.isEmpty() ) { List tmp = new LinkedList(); for ( Iterator i = depLibOrder.iterator(); i.hasNext(); ) { String depToOrderName = (String) i.next(); for ( Iterator j = depLibs.iterator(); j.hasNext(); ) { NarArtifact dep = (NarArtifact) j.next(); String depName = dep.getGroupId() + ":" + dep.getArtifactId(); if ( depName.equals( depToOrderName ) ) { tmp.add( dep ); j.remove(); } } } tmp.addAll( depLibs ); depLibs = tmp; } for ( Iterator i = depLibs.iterator(); i.hasNext(); ) { NarArtifact dependency = (NarArtifact) i.next(); // FIXME no handling of "local" // FIXME, no way to override this at this stage String binding = dependency.getNarInfo().getBinding( getAOL(), Library.STATIC ); getLog().debug( "Using Binding: " + binding ); AOL aol = getAOL(); aol = dependency.getNarInfo().getAOL( getAOL() ); getLog().debug( "Using Library AOL: " + aol.toString() ); if ( !binding.equals( Library.JNI ) ) { File dir = new File( getNarManager().getNarFile( dependency ).getParentFile(), "nar/lib/" + aol.toString() + "/" + binding ); getLog().debug( "Looking for Library Directory: " + dir ); if ( dir.exists() ) { LibrarySet libSet = new LibrarySet(); libSet.setProject( antProject ); // FIXME, no way to override String libs = dependency.getNarInfo().getLibs( getAOL() ); if ( ( libs != null ) && !libs.equals( "" ) ) { getLog().debug( "Using LIBS = " + libs ); libSet.setLibs( new CUtil.StringArrayBuilder( libs ) ); libSet.setDir( dir ); task.addLibset( libSet ); } } else { getLog().debug( "Library Directory " + dir + " does NOT exist." ); } // FIXME, look again at this, for multiple dependencies we may need to remove duplicates String options = dependency.getNarInfo().getOptions( getAOL() ); if ( ( options != null ) && !options.equals( "" ) ) { getLog().debug( "Using OPTIONS = " + options ); LinkerArgument arg = new LinkerArgument(); arg.setValue( options ); linkerDefinition.addConfiguredLinkerArg( arg ); } String sysLibs = dependency.getNarInfo().getSysLibs( getAOL() ); if ( ( sysLibs != null ) && !sysLibs.equals( "" ) ) { getLog().debug( "Using SYSLIBS = " + sysLibs ); SystemLibrarySet sysLibSet = new SystemLibrarySet(); sysLibSet.setProject( antProject ); sysLibSet.setLibs( new CUtil.StringArrayBuilder( sysLibs ) ); task.addSyslibset( sysLibSet ); } } } } // Add JVM to linker - getJava().addRuntime( task, getJavaHome( getAOL() ), getOS(), getAOL().getKey() + "java." ); + getJava().addRuntime( task, getJavaHome( getAOL() ), getOS(), getAOL().getKey() + ".java." ); // execute try { task.execute(); } catch ( BuildException e ) { throw new MojoExecutionException( "NAR: Compile failed", e ); } // FIXME, this should be done in CPPTasks at some point if ( getRuntime( getAOL() ).equals( "dynamic" ) && getOS().equals( OS.WINDOWS ) && getLinker().getName( null, null ).equals( "msvc" ) && NarUtil.getEnv( "MSVCVer", "MSVCVer", "6.0" ).startsWith( "8." ) ) { String libType = library.getType(); if ( libType.equals( Library.JNI ) || libType.equals( Library.SHARED ) ) { String dll = outFile.getPath() + ".dll"; String manifest = dll + ".manifest"; int result = NarUtil.runCommand( "mt.exe", new String[] { "/manifest", manifest, "/outputresource:" + dll + ";#2" }, null, null, getLog() ); if ( result != 0 ) throw new MojoFailureException( "MT.EXE failed with exit code: " + result ); } } } }
false
false
null
null
diff --git a/edu/cmu/sphinx/linguist/dflat/DynamicFlatLinguist.java b/edu/cmu/sphinx/linguist/dflat/DynamicFlatLinguist.java index 9ca66532..3f53ab25 100644 --- a/edu/cmu/sphinx/linguist/dflat/DynamicFlatLinguist.java +++ b/edu/cmu/sphinx/linguist/dflat/DynamicFlatLinguist.java @@ -1,1560 +1,1560 @@ /* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electric Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.linguist.dflat; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Logger; import java.util.Set; import edu.cmu.sphinx.linguist.Linguist; import edu.cmu.sphinx.linguist.SearchGraph; import edu.cmu.sphinx.linguist.WordSequence; import edu.cmu.sphinx.linguist.SearchState; import edu.cmu.sphinx.linguist.UnitSearchState; import edu.cmu.sphinx.linguist.WordSearchState; import edu.cmu.sphinx.linguist.HMMSearchState; import edu.cmu.sphinx.linguist.SearchStateArc; import edu.cmu.sphinx.linguist.util.HMMPool; import edu.cmu.sphinx.linguist.acoustic.AcousticModel; import edu.cmu.sphinx.linguist.acoustic.HMM; import edu.cmu.sphinx.linguist.acoustic.HMMPosition; import edu.cmu.sphinx.linguist.acoustic.HMMState; import edu.cmu.sphinx.linguist.acoustic.HMMStateArc; import edu.cmu.sphinx.linguist.acoustic.LeftRightContext; import edu.cmu.sphinx.linguist.acoustic.Unit; import edu.cmu.sphinx.linguist.acoustic.UnitManager; import edu.cmu.sphinx.linguist.dictionary.Dictionary; import edu.cmu.sphinx.linguist.dictionary.Pronunciation; import edu.cmu.sphinx.linguist.dictionary.Word; import edu.cmu.sphinx.linguist.language.grammar.Grammar; import edu.cmu.sphinx.linguist.language.grammar.GrammarArc; import edu.cmu.sphinx.linguist.language.grammar.GrammarNode; import edu.cmu.sphinx.util.LogMath; import edu.cmu.sphinx.util.StatisticsVariable; import edu.cmu.sphinx.util.Timer; import edu.cmu.sphinx.util.props.Configurable; import edu.cmu.sphinx.util.props.PropertyException; import edu.cmu.sphinx.util.props.PropertySheet; import edu.cmu.sphinx.util.props.PropertyType; import edu.cmu.sphinx.util.props.Registry; /** * A simple form of the linguist. It makes the following simplifying * assumptions: 1) Zero or one word per grammar node 2) No fan-in allowed ever 3) * No composites (yet) 4) Only Unit, HMMState, and pronunciation states (and * the initial/final grammar state are in the graph (no word, alternative or * grammar states attached). 5) Only valid tranisitions (matching contexts) are * allowed 6) No tree organization of units 7) Branching grammar states are * allowed * * This is a dynamic version of the flat linguist that is more efficient in * terms of startup time and overall footprint * * Note that all probabilties are maintained in the log math domain */ public class DynamicFlatLinguist implements Linguist, Configurable { /** * A sphinx property used to define the grammar to use when building the * search graph */ public final static String PROP_GRAMMAR = "grammar"; /** * A sphinx property used to define the unit manager to use * when building the search graph */ public final static String PROP_UNIT_MANAGER = "unitManager"; /** * A sphinx property used to define the acoustic model to use when building * the search graph */ public final static String PROP_ACOUSTIC_MODEL = "acousticModel"; /** * Sphinx property that specifies whether to add a branch for detecting * out-of-grammar utterances. */ public final static String PROP_ADD_OUT_OF_GRAMMAR_BRANCH = "addOutOfGrammarBranch"; /** * Default value of PROP_ADD_OUT_OF_GRAMMAR_BRANCH. */ public final static boolean PROP_ADD_OUT_OF_GRAMMAR_BRANCH_DEFAULT = false; /** * Sphinx property for the probability of entering the out-of-grammar * branch. */ public final static String PROP_OUT_OF_GRAMMAR_PROBABILITY = "outOfGrammarProbability"; /** * The default value for PROP_OUT_OF_GRAMMAR_PROBABILITY. */ public final static double PROP_OUT_OF_GRAMMAR_PROBABILITY_DEFAULT = 1.0; /** * Sphinx property for the probability of inserting a CI phone in * the out-of-grammar ci phone loop */ public static final String PROP_PHONE_INSERTION_PROBABILITY = "phoneInsertionProbability"; /** * Default value for PROP_PHONE_INSERTION_PROBABILITY */ public static final double PROP_PHONE_INSERTION_PROBABILITY_DEFAULT = 1.0; /** * Sphinx property for the acoustic model to use to build the phone loop * that detects out of grammar utterances. */ public final static String PROP_PHONE_LOOP_ACOUSTIC_MODEL = "phoneLoopAcousticModel"; /** * Sphinx property that defines the name of the logmath to be used by this * search manager. */ public final static String PROP_LOG_MATH = "logMath"; private final static float logOne = LogMath.getLogOne(); // ---------------------------------- // Subcomponents that are configured // by the property sheet // ----------------------------------- private Grammar grammar; private AcousticModel acousticModel; private AcousticModel phoneLoopAcousticModel; private LogMath logMath; private UnitManager unitManager; // ------------------------------------ // Data that is configured by the // property sheet // ------------------------------------ private float logWordInsertionProbability; private float logSilenceInsertionProbability; private float logUnitInsertionProbability; private float logFillerInsertionProbability; private float languageWeight; private float logOutOfGrammarBranchProbability; private float logPhoneInsertionProbability; private boolean addOutOfGrammarBranch; // ------------------------------------ // Data used for building and maintaining // the search graph // ------------------------------------- private SearchGraph searchGraph; private String name; private Logger logger; private HMMPool hmmPool; SearchStateArc outOfGrammarGraph; // this map is used to manage the set of follow on units for a // particular grammar node. It is used to select the set of // possible right contexts as we leave a node private Map nodeToNextUnitArrayMap; // this map is used to manage the set of possible entry units for // a grammar node. It is used to filter paths so that we only // branch to grammar nodes that match the current right context. private Map nodeToUnitSetMap; // an empty arc (just waiting for Noah, I guess) private final SearchStateArc[] EMPTY_ARCS = new SearchStateArc[0]; /* * (non-Javadoc) * * @see edu.cmu.sphinx.util.props.Configurable#register(java.lang.String, * edu.cmu.sphinx.util.props.Registry) */ public void register(String name, Registry registry) throws PropertyException { this.name = name; registry.register(PROP_GRAMMAR, PropertyType.COMPONENT); registry.register(PROP_ACOUSTIC_MODEL, PropertyType.COMPONENT); registry.register(PROP_LOG_MATH, PropertyType.COMPONENT); registry.register(PROP_WORD_INSERTION_PROBABILITY, PropertyType.DOUBLE); registry.register(PROP_SILENCE_INSERTION_PROBABILITY, PropertyType.DOUBLE); registry.register(PROP_UNIT_INSERTION_PROBABILITY, PropertyType.DOUBLE); registry.register(PROP_LANGUAGE_WEIGHT, PropertyType.FLOAT); registry.register(PROP_UNIT_MANAGER, PropertyType.COMPONENT); registry.register(PROP_FILLER_INSERTION_PROBABILITY, PropertyType.DOUBLE); registry.register(PROP_ADD_OUT_OF_GRAMMAR_BRANCH, PropertyType.BOOLEAN); registry.register(PROP_OUT_OF_GRAMMAR_PROBABILITY, PropertyType.DOUBLE); registry.register(PROP_PHONE_INSERTION_PROBABILITY, PropertyType.DOUBLE); registry.register(PROP_PHONE_LOOP_ACOUSTIC_MODEL, PropertyType.COMPONENT); } /* * (non-Javadoc) * * @see edu.cmu.sphinx.util.props.Configurable#newProperties(edu.cmu.sphinx.util.props.PropertySheet) */ public void newProperties(PropertySheet ps) throws PropertyException { // hookup to all of the components logger = ps.getLogger(); setupAcousticModel(ps); logMath = (LogMath) ps.getComponent(PROP_LOG_MATH, LogMath.class); grammar = (Grammar) ps.getComponent(PROP_GRAMMAR, Grammar.class); unitManager = (UnitManager) ps.getComponent(PROP_UNIT_MANAGER, UnitManager.class); // get the rest of the configuration data logWordInsertionProbability = logMath.linearToLog(ps.getDouble( PROP_WORD_INSERTION_PROBABILITY, PROP_WORD_INSERTION_PROBABILITY_DEFAULT)); logSilenceInsertionProbability = logMath.linearToLog(ps.getDouble( PROP_SILENCE_INSERTION_PROBABILITY, PROP_SILENCE_INSERTION_PROBABILITY_DEFAULT)); logUnitInsertionProbability = logMath.linearToLog(ps.getDouble( PROP_UNIT_INSERTION_PROBABILITY, PROP_UNIT_INSERTION_PROBABILITY_DEFAULT)); logFillerInsertionProbability = logMath.linearToLog(ps.getDouble( PROP_FILLER_INSERTION_PROBABILITY, PROP_FILLER_INSERTION_PROBABILITY_DEFAULT)); languageWeight = ps.getFloat(Linguist.PROP_LANGUAGE_WEIGHT, PROP_LANGUAGE_WEIGHT_DEFAULT); addOutOfGrammarBranch = ps.getBoolean (PROP_ADD_OUT_OF_GRAMMAR_BRANCH, PROP_ADD_OUT_OF_GRAMMAR_BRANCH_DEFAULT); logOutOfGrammarBranchProbability = logMath.linearToLog (ps.getDouble(PROP_OUT_OF_GRAMMAR_PROBABILITY, PROP_OUT_OF_GRAMMAR_PROBABILITY_DEFAULT)); logPhoneInsertionProbability = logMath.linearToLog (ps.getDouble(PROP_PHONE_INSERTION_PROBABILITY, PROP_PHONE_INSERTION_PROBABILITY_DEFAULT)); if (addOutOfGrammarBranch) { phoneLoopAcousticModel = (AcousticModel) ps.getComponent(PROP_PHONE_LOOP_ACOUSTIC_MODEL, AcousticModel.class); } } /** * Returns the search graph * * @return the search graph */ public SearchGraph getSearchGraph() { return searchGraph; } /** * Sets up the acoustic model. * * @param ps the PropertySheet from which to obtain the acoustic model */ protected void setupAcousticModel(PropertySheet ps) throws PropertyException { acousticModel = (AcousticModel) ps.getComponent(PROP_ACOUSTIC_MODEL, AcousticModel.class); } /* * (non-Javadoc) * * @see edu.cmu.sphinx.util.props.Configurable#getName() */ public String getName() { return name; } /* * (non-Javadoc) * * @see edu.cmu.sphinx.linguist.Linguist#allocate() */ public void allocate() throws IOException { logger.info("Allocating DFLAT"); allocateAcousticModel(); grammar.allocate(); hmmPool = new HMMPool(acousticModel, logger, unitManager); nodeToNextUnitArrayMap = new HashMap(); nodeToUnitSetMap = new HashMap(); Timer timer = Timer.getTimer("compileGrammar"); timer.start(); compileGrammar(); timer.stop(); logger.info("Done allocating DFLAT"); } /** * Allocates the acoustic model. */ protected void allocateAcousticModel() throws IOException { acousticModel.allocate(); if (addOutOfGrammarBranch) { phoneLoopAcousticModel.allocate(); } } /* * (non-Javadoc) * * @see edu.cmu.sphinx.linguist.Linguist#deallocate() */ public void deallocate() { if (acousticModel != null) { acousticModel.deallocate(); } grammar.deallocate(); } /** * * Called before a recognition */ public void startRecognition() { } /** * Called after a recognition */ public void stopRecognition() { } /** * Returns the LogMath used. * * @return the logMath used */ public LogMath getLogMath() { return logMath; } /** * Returns the log silence insertion probability. * * @return the log silence insertion probability. */ public float getLogSilenceInsertionProbability() { return logSilenceInsertionProbability; } /** * Compiles the grammar */ private void compileGrammar() { // iterate through the grammar nodes Set nodeSet = grammar.getGrammarNodes(); for (Iterator i = nodeSet.iterator(); i.hasNext(); ) { GrammarNode node = (GrammarNode) i.next(); initUnitMaps(node); } searchGraph = new DynamicFlatSearchGraph(); } /** * Initializes the unit maps for this linguist. There are two unit maps: * (a) nodeToNextUnitArrayMap contains an array of unit ids for all possible * units that immediately follow the given grammar node. This is used to * determine the set of exit contexts for words within a grammar node. * (b) nodeToUnitSetMap contains the set of possible entry units for a * given grammar node. This is typically used to determine if a path with * a given right context should branch into a particular grammar node * * @param node the units maps will be created for this node. */ private void initUnitMaps(GrammarNode node) { // collect the set of next units for this node if (nodeToNextUnitArrayMap.get(node) == null) { Set vistedNodes = new HashSet(); Set unitSet = new HashSet(); GrammarArc[] arcs = node.getSuccessors(); for (int i = 0; i < arcs.length; i++) { GrammarNode nextNode = arcs[i].getGrammarNode(); collectNextUnits(nextNode, vistedNodes, unitSet); } int[] nextUnits = new int[unitSet.size()]; int index = 0; for (Iterator i = unitSet.iterator(); i.hasNext(); ) { Unit unit = (Unit) i.next(); nextUnits[index++] = unit.getBaseID(); } nodeToNextUnitArrayMap.put(node, nextUnits); } // collect the set of entry units for this node if (nodeToUnitSetMap.get(node) == null) { Set vistedNodes = new HashSet(); Set unitSet = new HashSet(); collectNextUnits(node, vistedNodes, unitSet); nodeToUnitSetMap.put(node, unitSet); } } /** * For the given grammar node, collect the set of possible next units. * * @param thisNode the grammar node * @param vistedNodes the set of visited grammar nodes, used to ensure * that we don't attempt to expand a particular grammar node more than * once (which could lead to a death spiral) * @param unitSet the entry units are collected here. */ private void collectNextUnits(GrammarNode thisNode, Set vistedNodes, Set unitSet) { if (vistedNodes.contains(thisNode)) { return; } vistedNodes.add(thisNode); if (thisNode.isFinalNode()) { unitSet.add(UnitManager.SILENCE); } else if (!thisNode.isEmpty()) { Word word = thisNode.getWord(); Pronunciation[] pronunciations = word.getPronunciations(); for (int j = 0; j < pronunciations.length; j++) { unitSet.add(pronunciations[j].getUnits()[0]); } } else { GrammarArc[] arcs = thisNode.getSuccessors(); for (int i = 0; i < arcs.length; i++) { GrammarNode nextNode = arcs[i].getGrammarNode(); collectNextUnits(nextNode, vistedNodes, unitSet); } } } Map successorCache = new HashMap(); /** * The base search state for this dynamic flat linguist. */ abstract class FlatSearchState implements SearchState , SearchStateArc { final static int ANY = 0; /** * Gets the set of successors for this state * * @return the set of successors */ public abstract SearchStateArc[] getSuccessors(); /** * Returns a unique string representation of the state. This string is * suitable (and typically used) for a label for a GDL node * * @return the signature */ public abstract String getSignature(); /** * Returns the order of this state type among all of the search states * * @return the order */ public abstract int getOrder(); /** * Determines if this state is an emitting state * * @return true if this is an emitting state */ public boolean isEmitting() { return false; } /** * Determines if this is a final state * * @return true if this is a final state */ public boolean isFinal() { return false; } /** * Returns a lex state associated with the searc state (not applicable * to this linguist) * * @return the lex state (null for this linguist) */ public Object getLexState() { return null; } /** * Returns a well formatted string representation of this state * * @return the formatted string */ public String toPrettyString() { return toString(); } /** * Returns a string representation of this object * * @return a string representation */ public String toString() { return getSignature(); } /** * Returns the word history for this state (not applicable to this * linguist) * @return the word history (null for this linguist) */ public WordSequence getWordHistory() { return null; } /** * Gets a successor to this search state * * @return the successor state */ public SearchState getState() { return this; } /** * Gets the composite probability of entering this state * * @return the log probability */ public float getProbability() { return getLanguageProbability() + getAcousticProbability() + getInsertionProbability(); } /** * Gets the language probability of entering this state * * @return the log probability */ public float getLanguageProbability() { return logOne; } /** * Gets the acoustic probability of entering this state * * @return the log probability */ public float getAcousticProbability() { return logOne; } /** * Gets the insertion probability of entering this state * * @return the log probability */ public float getInsertionProbability() { return logOne; } /** * Simple debugging output * * @param msg the debug message */ void debug(String msg) { if (false) { System.out.println(msg); } } /** * Get the arcs from the cache if the exist * * @return the cached arcs or null */ SearchStateArc[] getCachedSuccessors() { return (SearchStateArc[]) successorCache.get(this); } /** * Places the set of successor arcs in the cache * - * @param the set of arcs to be cached for this state + * @param successors the set of arcs to be cached for this state */ void cacheSuccessors(SearchStateArc[] successors) { successorCache.put(this, successors); } } /** * Represents a grammar node in the search graph. A grammar state needs to * keep track of the associated grammar node as well as the left context * and next base unit. */ class GrammarState extends FlatSearchState { private GrammarNode node; private int lc; private int nextBaseID; private float languageProbability; /** * Creates a grammar state for the given node with a silence Lc * * @param node the grammar node */ GrammarState(GrammarNode node) { this(node, logOne, UnitManager.SILENCE.getBaseID()); } /** * Creates a grammar state for the given node and left context. The * path will connect to any possible next base * * @param node the grammar node * @param languageProbability the probability of transistioning to * this word * @param lc the left context for this path */ GrammarState(GrammarNode node, float languageProbability, int lc) { this(node, languageProbability, lc, ANY); } /** * Creates a grammar state for the given node and left context and * next base ID. * * @param node the grammar node * @param languageProbability the probability of transistioning to * this word * @param lc the left context for this path * @param nextBaseID the next base ID */ GrammarState(GrammarNode node, float languageProbability, int lc, int nextBaseID) { this.lc = lc; this.nextBaseID = nextBaseID; this.node = node; this.languageProbability = languageProbability; } /** * Gets the language probability of entering this state * * @return the log probability */ public float getLanguageProbability() { return languageProbability * languageWeight; } /** * Generate a hashcode for an object. Equality for a grammar state * includes the grammar node, the lc and the next base ID * * @return the hashcode */ public int hashCode() { return node.hashCode() * 17 + lc * 7 + nextBaseID; } /** * Determines if the given object is equal to this object * * @param o * the object to test * @return <code>true</code> if the object is equal to this */ public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof GrammarState) { GrammarState other = (GrammarState) o; return other.node == node && lc == other.lc && nextBaseID == other.nextBaseID; } else { return false; } } /** * Determines if this is a final state in the search graph * * @return true if this is a final state in the search graph */ public boolean isFinal() { return node.isFinalNode(); } /** * Gets the set of successors for this state * * @return the set of successors */ public SearchStateArc[] getSuccessors() { SearchStateArc[] arcs = getCachedSuccessors(); if (arcs == null) { if (isFinal()) { arcs = EMPTY_ARCS; } else if (node.isEmpty()) { arcs = getNextGrammarStates(lc, nextBaseID); } else { Word word = node.getWord(); Pronunciation[] pronunciations = word.getPronunciations(); pronunciations = filter(pronunciations, nextBaseID); SearchStateArc[] nextArcs = new SearchStateArc[pronunciations.length]; for (int i = 0; i < pronunciations.length; i++) { nextArcs[i] = new PronunciationState(this, pronunciations[i]); } arcs = nextArcs; } cacheSuccessors(arcs); } return arcs; } /** * Gets the set of arcs to the next set of grammar states that match * the given nextBaseID * * @param lc the current left context * @param nextBaseID the desired next base ID */ SearchStateArc[] getNextGrammarStates(int lc, int nextBaseID) { GrammarArc[] nextNodes = node.getSuccessors(); nextNodes = filter(nextNodes, nextBaseID); SearchStateArc[] nextArcs = new SearchStateArc[nextNodes.length]; for (int i = 0; i < nextNodes.length; i++) { GrammarArc arc = nextNodes[i]; nextArcs[i] = new GrammarState(arc.getGrammarNode(), arc.getProbability(), lc, nextBaseID); } return nextArcs; } /** * Returns a unique string representation of the state. This string is * suitable (and typically used) for a label for a GDL node * * @return the signature */ public String getSignature() { return "GS " + node + "-lc-" + hmmPool.getUnit(lc) + "-rc-" + hmmPool.getUnit(nextBaseID); } /** * Returns the order of this state type among all of the search states * * @return the order */ public int getOrder() { return 1; } /** * Given a set of arcs and the ID of the desired next unit, return the * set of arcs containing only those that transition to the next unit * * @param arcs the set of arcs to filter * @param nextBase the ID of the desired next unit */ GrammarArc[] filter(GrammarArc[] arcs, int nextBase) { if (nextBase != ANY) { List list = new ArrayList(); for (int i = 0; i < arcs.length; i++) { GrammarNode node = arcs[i].getGrammarNode(); if (hasEntryContext(node, nextBase)) { list.add(arcs[i]); } } arcs = (GrammarArc[]) list.toArray(new GrammarArc[list.size()]); } return arcs; } /** * Determines if the given node starts with the specified unit * * @param node the grammar node * @param unitID the id of the unit */ private boolean hasEntryContext(GrammarNode node, int unitID) { Set unitSet = (Set) nodeToUnitSetMap.get(node); return unitSet.contains(hmmPool.getUnit(unitID)); } /** * Retain only the pronunciations that start with the unit indicated * by nextBase * * @param p the set of pronunciations to filter * @param nextBase the ID of the desired initial unit */ Pronunciation[] filter(Pronunciation[] p, int nextBase) { if (true) { return p; } if (nextBase == ANY) { return p; } else { int count = 0; for (int i = 0; i < p.length; i++) { Unit[] units = p[i].getUnits(); if (units[0].getBaseID() == nextBase) { count++; } } if (count == p.length) { return p; } else { Pronunciation[] filteredP = new Pronunciation[count]; int index = 0; for (int i = 0; i < p.length; i++) { Unit[] units = p[i].getUnits(); if (units[0].getBaseID() == nextBase) { filteredP[index++] = p[i]; } } return filteredP; } } } /** * Gets the ID of the left context unit for this path * * @return the left context ID */ int getLC() { return lc; } /** * Gets the ID of the desired next unit * * @return the ID of the next unit */ int getNextBaseID() { return nextBaseID; } /** * Returns the set of IDs for all possible next units for this grammar * node * * @return the set of IDs of all possible next units */ int[] getNextUnits() { return (int[]) nodeToNextUnitArrayMap.get(node); } /** * Returns a string representation of this object * * @return a string representation */ public String toString() { return node + "[" + hmmPool.getUnit(lc) + "," + hmmPool.getUnit(nextBaseID) + "]"; } /** * Returns the grammar node associated with this grammar state * * @return the grammar node */ GrammarNode getGrammarNode() { return node; } } class InitialState extends FlatSearchState { private List nextArcs = new ArrayList(); /** * Gets the set of successors for this state * * @return the set of successors */ public SearchStateArc[] getSuccessors() { return (SearchStateArc[]) nextArcs .toArray(new SearchStateArc[nextArcs .size()]); } public void addArc(SearchStateArc arc) { nextArcs.add(arc); } /** * Returns a unique string representation of the state. This string is * suitable (and typically used) for a label for a GDL node * * @return the signature */ public String getSignature() { return "initialState"; } /** * Returns the order of this state type among all of the search states * * @return the order */ public int getOrder() { return 1; } /** * Returns a string representation of this object * * @return a string representation */ public String toString() { return getSignature(); } } /** * This class representations a word punctuation in the search graph */ class PronunciationState extends FlatSearchState implements WordSearchState{ private GrammarState gs; private Pronunciation pronunciation; /** * Creates a PronunciationState * * @param gs the associated grammar state * @param p the pronunciation */ PronunciationState(GrammarState gs, Pronunciation p) { this.gs = gs; this.pronunciation = p; } /** * Gets the insertion probability of entering this state * * @return the log probability */ public float getInsertionProbability() { if (pronunciation.getWord().isFiller()) { return logOne; } else { return logWordInsertionProbability; } } /** * Generate a hashcode for an object * * @return the hashcode */ public int hashCode() { return 13 * gs.hashCode() + pronunciation.hashCode(); } /** * Determines if the given object is equal to this object * * @param o * the object to test * @return <code>true</code> if the object is equal to this */ public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof PronunciationState) { PronunciationState other = (PronunciationState) o; return other.gs.equals(gs) && other.pronunciation.equals(pronunciation); } else { return false; } } /** * Gets the successor states for this search graph * * @return the successor states */ public SearchStateArc[] getSuccessors() { SearchStateArc[] arcs = getCachedSuccessors(); if (arcs == null) { arcs = getSuccessors(gs.getLC(), 0); cacheSuccessors(arcs); } return arcs; } /** * Gets the successor states for the unit and the given position and * left context * * @param lc the ID of the left context * @param index the position of the unit within the pronunciation * * @return the set of sucessor arcs */ SearchStateArc[] getSuccessors(int lc, int index) { SearchStateArc[] arcs = null; if (index == pronunciation.getUnits().length -1) { if (isContextIndependentUnit( pronunciation.getUnits()[index])) { arcs = new SearchStateArc[1]; arcs[0] = new FullHMMSearchState(this, index, lc, ANY); } else { int[] nextUnits = gs.getNextUnits(); arcs = new SearchStateArc[nextUnits.length]; for (int i = 0; i < arcs.length; i++) { arcs[i] = new FullHMMSearchState(this,index,lc,nextUnits[i]); } } } else { arcs = new SearchStateArc[1]; arcs[0] = new FullHMMSearchState(this, index, lc); } return arcs; } /** * Gets the pronunciation assocated with this state * * @return the pronunciation */ public Pronunciation getPronunciation() { return pronunciation; } /** * Determines if the given unit is a CI unit * * @param unit the unit to test * * @return true if the unit is a context independent unit */ private boolean isContextIndependentUnit(Unit unit) { return unit.isFiller(); } /** * Returns a unique string representation of the state. This string is * suitable (and typically used) for a label for a GDL node * * @return the signature */ public String getSignature() { return "PS " + gs.getSignature() + "-" + pronunciation; } /** * Returns a string representation of this object * * @return a string representation */ public String toString() { return pronunciation.getWord().getSpelling(); } /** * Returns the order of this state type among all of the search states * * @return the order */ public int getOrder() { return 2; } /** * Returns the grammar state associated with this state * * @return the grammar state */ GrammarState getGrammarState() { return gs; } /** * Returns true if this WordSearchState indicates the start of a word. * Returns false if this WordSearchState indicates the end of a word. * * @return true if this WordSearchState indicates the start of a word, * false if this WordSearchState indicates the end of a word */ public boolean isWordStart() { return true; } } /** * Represents a unit (as an HMM) in the search graph */ class FullHMMSearchState extends FlatSearchState implements UnitSearchState { private PronunciationState pState; private int index; private int lc; private int rc; private HMM hmm; private boolean isLastUnitOfWord; /** * Creates a FullHMMSearchState * * @param p the parent PronunciationState * @param which the index of the unit within the pronunciation * @param lc the ID of the left context */ FullHMMSearchState(PronunciationState p, int which, int lc) { this(p, which, lc, p.getPronunciation().getUnits()[which + 1].getBaseID()); } /** * Creates a FullHMMSearchState * * @param p the parent PronunciationState * @param which the index of the unit within the pronunciation * @param lc the ID of the left context * @param rc the ID of the right context */ FullHMMSearchState(PronunciationState p, int which, int lc, int rc) { this.pState = p; this.index = which; this.lc = lc; this.rc = rc; int base = p.getPronunciation().getUnits()[which].getBaseID(); int id = hmmPool.buildID(base, lc, rc); hmm = hmmPool.getHMM(id, getPosition()); isLastUnitOfWord = which == p.getPronunciation().getUnits().length - 1; } /** * Determines the insertion probability based upon the type of unit * * @return the insertion probability */ public float getInsertionProbability() { Unit unit = hmm.getBaseUnit(); if (unit.isSilence()) { return logSilenceInsertionProbability; } else if (unit.isFiller()) { return logFillerInsertionProbability; } else { return logUnitInsertionProbability; } } /** * Returns a string representation of this object * * @return a string representation */ public String toString() { return hmm.getUnit().toString(); } /** * Generate a hashcode for an object * * @return the hashcode */ public int hashCode() { return pState.getGrammarState().getGrammarNode().hashCode() * 29 + pState.getPronunciation().hashCode() * 19 + index * 7 + 43 * lc + rc; } /** * Determines if the given object is equal to this object * * @param o * the object to test * @return <code>true</code> if the object is equal to this */ public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof FullHMMSearchState) { FullHMMSearchState other = (FullHMMSearchState) o; // the definition for equal for a FullHMMState: // Grammar Node equal // Pronunciation equal // index equal // rc equal return pState.getGrammarState().getGrammarNode() == other.pState.getGrammarState().getGrammarNode() && pState.getPronunciation() == other.pState.getPronunciation() && index == other.index && lc == other.lc && rc == other.rc; } else { return false; } } /** * Returns the unit assoicated with this state * * @return the unit */ public Unit getUnit() { return hmm.getBaseUnit(); } /** * Gets the set of successors for this state * * @return the set of successors */ public SearchStateArc[] getSuccessors() { SearchStateArc[] arcs = getCachedSuccessors(); if (arcs == null) { arcs = new SearchStateArc[1]; arcs[0] = new HMMStateSearchState(this, hmm.getInitialState()); cacheSuccessors(arcs); } return arcs; } /** * Determines if this unit is the last unit of a word * * @return true if this unit is the last unit of a word */ boolean isLastUnitOfWord() { return isLastUnitOfWord; } /** * Determines the position of the unit within the word * * @return the position of the unit within the word */ HMMPosition getPosition() { int len = pState.getPronunciation().getUnits().length; if (len == 1) { return HMMPosition.SINGLE; } else if (index == 0) { return HMMPosition.BEGIN; } else if (index == len -1) { return HMMPosition.END; } else { return HMMPosition.INTERNAL; } } /** * Returns the HMM for this state * * @return the HMM */ HMM getHMM() { return hmm; } /** * Returns the order of this state type among all of the search states * * @return the order */ public int getOrder() { return 3; } /** * Determines the insertion probability based upon the type of unit * * @return the insertion probability */ private float calcInsertionProbability() { Unit unit = hmm.getBaseUnit(); if (unit.isSilence()) { return logSilenceInsertionProbability; } else if (unit.isFiller()) { return logFillerInsertionProbability; } else { return logUnitInsertionProbability; } } /** * Returns a unique string representation of the state. This string is * suitable (and typically used) for a label for a GDL node * * @return the signature */ public String getSignature() { return "HSS " + pState.getGrammarState().getGrammarNode() + pState.getPronunciation() + index + "-" + rc + "-" + lc; } /** * Returns the ID of the right context for this state * * @return the right context unit ID */ int getRC() { return rc; } /** * Returns the next set of arcs after this state and all * substates have been processed * * @return the next set of arcs */ SearchStateArc[] getNextArcs() { SearchStateArc[] arcs; // this is the last state of the hmm // so check to see if we are at the end // of a word, if not get the next full hmm in the word // otherwise generate arcs to the next set of words Pronunciation pronunciation = pState.getPronunciation(); int nextLC = getHMM().getBaseUnit().getBaseID(); if (!isLastUnitOfWord()) { arcs = pState.getSuccessors(nextLC, index + 1); } else { // we are at the end of the word, so we transit to the // next grammar nodes GrammarState gs = pState.getGrammarState(); arcs = gs.getNextGrammarStates(nextLC, getRC()); } return arcs; } } /** * Represents a single hmm state in the search graph */ class HMMStateSearchState extends FlatSearchState implements HMMSearchState { private FullHMMSearchState fullHMMSearchState; private HMMState hmmState; private float probability; /** * Creates an HMMStateSearchState * * @param hss the parent hmm state * @param hmmState which hmm state */ HMMStateSearchState(FullHMMSearchState hss, HMMState hmmState) { this(hss, hmmState, logOne); } /** * Creates an HMMStateSearchState * * @param hss the parent hmm state * @param hmmState which hmm state * @param prob the transition probability */ HMMStateSearchState(FullHMMSearchState hss, HMMState hmmState, float prob) { this.probability = prob; fullHMMSearchState = hss; this.hmmState = hmmState; } /** * Returns the acoustic probability for this state * * @return the probability */ public float getAcousticProbability() { return probability; } /** * Generate a hashcode for an object * * @return the hashcode */ public int hashCode() { return 7 * fullHMMSearchState.hashCode() + hmmState.hashCode(); } /** * Determines if the given object is equal to this object * * @param o * the object to test * @return <code>true</code> if the object is equal to this */ public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof HMMStateSearchState) { HMMStateSearchState other = (HMMStateSearchState) o; return other.fullHMMSearchState.equals(fullHMMSearchState) && other.hmmState.equals(hmmState); } else { return false; } } /** * Determines if this state is an emitting state * * @return true if this is an emitting state */ public boolean isEmitting() { return hmmState.isEmitting(); } /** * Gets the set of successors for this state * * @return the set of successors */ public SearchStateArc[] getSuccessors() { SearchStateArc[] arcs = getCachedSuccessors(); if (arcs == null) { if (hmmState.isExitState()) { arcs = fullHMMSearchState.getNextArcs(); } else { HMMStateArc[] next = hmmState.getSuccessors(); arcs = new SearchStateArc[next.length]; for (int i = 0; i < arcs.length; i++) { arcs[i] = new HMMStateSearchState(fullHMMSearchState, next[i].getHMMState(), next[i].getLogProbability()); } } cacheSuccessors(arcs); } return arcs; } /** * Returns the order of this state type among all of the search states * * @return the order */ public int getOrder() { return isEmitting() ? 4 : 0; } /** * Returns a unique string representation of the state. This string is * suitable (and typically used) for a label for a GDL node * * @return the signature */ public String getSignature() { return "HSSS " + fullHMMSearchState.getSignature() + "-" + hmmState; } /** * Returns the hmm state for this search state * * @return the hmm state */ public HMMState getHMMState() { return hmmState; } } /** * The search graph that is produced by the flat linguist. */ class DynamicFlatSearchGraph implements SearchGraph { /* * (non-Javadoc) * * @see edu.cmu.sphinx.linguist.SearchGraph#getInitialState() */ public SearchState getInitialState() { InitialState initialState = new InitialState(); initialState.addArc(new GrammarState(grammar.getInitialNode())); // add an out-of-grammar branch if configured to do so if (addOutOfGrammarBranch) { OutOfGrammarGraph oogg = new OutOfGrammarGraph (phoneLoopAcousticModel, logOutOfGrammarBranchProbability, logPhoneInsertionProbability); initialState.addArc(oogg.getOutOfGrammarGraph()); } return initialState; } /* * (non-Javadoc) * * @see edu.cmu.sphinx.linguist.SearchGraph#getNumStateOrder() */ public int getNumStateOrder() { return 5; } } }
true
false
null
null
diff --git a/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/PactCompiler.java b/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/PactCompiler.java index 60e546cb8..7845aa910 100644 --- a/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/PactCompiler.java +++ b/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/PactCompiler.java @@ -1,1702 +1,1706 @@ /*********************************************************************************************************************** * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.compiler; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import eu.stratosphere.api.common.Plan; import eu.stratosphere.api.common.operators.BulkIteration; import eu.stratosphere.api.common.operators.BulkIteration.PartialSolutionPlaceHolder; import eu.stratosphere.api.common.operators.DeltaIteration; import eu.stratosphere.api.common.operators.DeltaIteration.SolutionSetPlaceHolder; import eu.stratosphere.api.common.operators.DeltaIteration.WorksetPlaceHolder; import eu.stratosphere.api.common.operators.GenericDataSink; import eu.stratosphere.api.common.operators.GenericDataSource; import eu.stratosphere.api.common.operators.Operator; import eu.stratosphere.api.common.operators.base.CoGroupOperatorBase; import eu.stratosphere.api.common.operators.base.CrossOperatorBase; import eu.stratosphere.api.common.operators.base.FlatMapOperatorBase; import eu.stratosphere.api.common.operators.base.JoinOperatorBase; import eu.stratosphere.api.common.operators.base.MapOperatorBase; import eu.stratosphere.api.common.operators.base.GroupReduceOperatorBase; import eu.stratosphere.api.common.operators.base.PlainMapOperatorBase; import eu.stratosphere.api.common.operators.base.ReduceOperatorBase; import eu.stratosphere.compiler.costs.CostEstimator; import eu.stratosphere.compiler.costs.DefaultCostEstimator; import eu.stratosphere.compiler.dag.BulkIterationNode; import eu.stratosphere.compiler.dag.BulkPartialSolutionNode; import eu.stratosphere.compiler.dag.CoGroupNode; import eu.stratosphere.compiler.dag.CollectorMapNode; import eu.stratosphere.compiler.dag.CrossNode; import eu.stratosphere.compiler.dag.DataSinkNode; import eu.stratosphere.compiler.dag.DataSourceNode; import eu.stratosphere.compiler.dag.FlatMapNode; import eu.stratosphere.compiler.dag.IterationNode; import eu.stratosphere.compiler.dag.MapNode; import eu.stratosphere.compiler.dag.MatchNode; import eu.stratosphere.compiler.dag.OptimizerNode; import eu.stratosphere.compiler.dag.PactConnection; import eu.stratosphere.compiler.dag.GroupReduceNode; import eu.stratosphere.compiler.dag.ReduceNode; import eu.stratosphere.compiler.dag.SinkJoiner; import eu.stratosphere.compiler.dag.SolutionSetNode; import eu.stratosphere.compiler.dag.TempMode; import eu.stratosphere.compiler.dag.WorksetIterationNode; import eu.stratosphere.compiler.dag.WorksetNode; import eu.stratosphere.compiler.deadlockdetect.DeadlockPreventer; import eu.stratosphere.compiler.plan.BinaryUnionPlanNode; import eu.stratosphere.compiler.plan.BulkIterationPlanNode; import eu.stratosphere.compiler.plan.BulkPartialSolutionPlanNode; import eu.stratosphere.compiler.plan.Channel; import eu.stratosphere.compiler.plan.IterationPlanNode; import eu.stratosphere.compiler.plan.NAryUnionPlanNode; import eu.stratosphere.compiler.plan.OptimizedPlan; import eu.stratosphere.compiler.plan.PlanNode; import eu.stratosphere.compiler.plan.SinkJoinerPlanNode; import eu.stratosphere.compiler.plan.SinkPlanNode; import eu.stratosphere.compiler.plan.SolutionSetPlanNode; import eu.stratosphere.compiler.plan.SourcePlanNode; import eu.stratosphere.compiler.plan.WorksetIterationPlanNode; import eu.stratosphere.compiler.plan.WorksetPlanNode; import eu.stratosphere.compiler.postpass.OptimizerPostPass; import eu.stratosphere.configuration.ConfigConstants; import eu.stratosphere.configuration.Configuration; import eu.stratosphere.configuration.GlobalConfiguration; import eu.stratosphere.nephele.instance.InstanceType; import eu.stratosphere.nephele.instance.InstanceTypeDescription; import eu.stratosphere.nephele.ipc.RPC; import eu.stratosphere.nephele.net.NetUtils; import eu.stratosphere.nephele.protocols.ExtendedManagementProtocol; import eu.stratosphere.pact.runtime.shipping.ShipStrategyType; import eu.stratosphere.pact.runtime.task.DriverStrategy; import eu.stratosphere.pact.runtime.task.util.LocalStrategy; import eu.stratosphere.util.InstantiationUtil; import eu.stratosphere.util.Visitor; /** * The optimizer that takes the user specified program plan and creates an optimized plan that contains * exact descriptions about how the physical execution will take place. It first translates the user * program into an internal optimizer representation and then chooses between different alternatives * for shipping strategies and local strategies. * <p> * The basic principle is taken from optimizer works in systems such as Volcano/Cascades and Selinger/System-R/DB2. The * optimizer walks from the sinks down, generating interesting properties, and ascends from the sources generating * alternative plans, pruning against the interesting properties. * <p> * The optimizer also assigns the memory to the individual tasks. This is currently done in a very simple fashion: All * sub-tasks that need memory (e.g. reduce or match) are given an equal share of memory. */ public class PactCompiler { // ------------------------------------------------------------------------ // Constants // ------------------------------------------------------------------------ /** * Compiler hint key for the input channel's shipping strategy. This String is a key to the operator's stub * parameters. The corresponding value tells the compiler which shipping strategy to use for the input channel. * If the operator has two input channels, the shipping strategy is applied to both input channels. */ public static final String HINT_SHIP_STRATEGY = "INPUT_SHIP_STRATEGY"; /** * Compiler hint key for the <b>first</b> input channel's shipping strategy. This String is a key to * the operator's stub parameters. The corresponding value tells the compiler which shipping strategy * to use for the <b>first</b> input channel. Only applicable to operators with two inputs. */ public static final String HINT_SHIP_STRATEGY_FIRST_INPUT = "INPUT_LEFT_SHIP_STRATEGY"; /** * Compiler hint key for the <b>second</b> input channel's shipping strategy. This String is a key to * the operator's stub parameters. The corresponding value tells the compiler which shipping strategy * to use for the <b>second</b> input channel. Only applicable to operators with two inputs. */ public static final String HINT_SHIP_STRATEGY_SECOND_INPUT = "INPUT_RIGHT_SHIP_STRATEGY"; /** * Value for the shipping strategy compiler hint that enforces a <b>Forward</b> strategy on the * input channel, i.e. no redistribution of any kind. * * @see #HINT_SHIP_STRATEGY * @see #HINT_SHIP_STRATEGY_FIRST_INPUT * @see #HINT_SHIP_STRATEGY_SECOND_INPUT */ public static final String HINT_SHIP_STRATEGY_FORWARD = "SHIP_FORWARD"; /** * Value for the shipping strategy compiler hint that enforces a random repartition strategy. * * @see #HINT_SHIP_STRATEGY * @see #HINT_SHIP_STRATEGY_FIRST_INPUT * @see #HINT_SHIP_STRATEGY_SECOND_INPUT */ public static final String HINT_SHIP_STRATEGY_REPARTITION= "SHIP_REPARTITION"; /** * Value for the shipping strategy compiler hint that enforces a hash-partition strategy. * * @see #HINT_SHIP_STRATEGY * @see #HINT_SHIP_STRATEGY_FIRST_INPUT * @see #HINT_SHIP_STRATEGY_SECOND_INPUT */ public static final String HINT_SHIP_STRATEGY_REPARTITION_HASH = "SHIP_REPARTITION_HASH"; /** * Value for the shipping strategy compiler hint that enforces a range-partition strategy. * * @see #HINT_SHIP_STRATEGY * @see #HINT_SHIP_STRATEGY_FIRST_INPUT * @see #HINT_SHIP_STRATEGY_SECOND_INPUT */ public static final String HINT_SHIP_STRATEGY_REPARTITION_RANGE = "SHIP_REPARTITION_RANGE"; /** * Value for the shipping strategy compiler hint that enforces a <b>broadcast</b> strategy on the * input channel. * * @see #HINT_SHIP_STRATEGY * @see #HINT_SHIP_STRATEGY_FIRST_INPUT * @see #HINT_SHIP_STRATEGY_SECOND_INPUT */ public static final String HINT_SHIP_STRATEGY_BROADCAST = "SHIP_BROADCAST"; /** * Compiler hint key for the operator's local strategy. This String is a key to the operator's stub * parameters. The corresponding value tells the compiler which local strategy to use to process the * data inside one partition. * <p> * This hint is ignored by operators that do not have a local strategy (such as <i>Map</i>), or by operators that * have no choice in their local strategy (such as <i>Cross</i>). */ public static final String HINT_LOCAL_STRATEGY = "LOCAL_STRATEGY"; /** * Value for the local strategy compiler hint that enforces a <b>sort based</b> local strategy. * For example, a <i>Reduce</i> operator will sort the data to group it. * * @see #HINT_LOCAL_STRATEGY */ public static final String HINT_LOCAL_STRATEGY_SORT = "LOCAL_STRATEGY_SORT"; /** * Value for the local strategy compiler hint that enforces a <b>sort based</b> local strategy. * During sorting a combine method is repeatedly applied to reduce the data volume. * For example, a <i>Reduce</i> operator will sort the data to group it. * * @see #HINT_LOCAL_STRATEGY */ public static final String HINT_LOCAL_STRATEGY_COMBINING_SORT = "LOCAL_STRATEGY_COMBINING_SORT"; /** * Value for the local strategy compiler hint that enforces a <b>sort merge based</b> local strategy on both * inputs with subsequent merging of inputs. * For example, a <i>Match</i> or <i>CoGroup</i> operator will use a sort-merge strategy to find pairs * of matching keys. * * @see #HINT_LOCAL_STRATEGY */ public static final String HINT_LOCAL_STRATEGY_SORT_BOTH_MERGE = "LOCAL_STRATEGY_SORT_BOTH_MERGE"; /** * Value for the local strategy compiler hint that enforces a <b>sort merge based</b> local strategy. * The the first input is sorted, the second input is assumed to be sorted. After sorting both inputs are merged. * For example, a <i>Match</i> or <i>CoGroup</i> operator will use a sort-merge strategy to find pairs * of matching keys. * * @see #HINT_LOCAL_STRATEGY */ public static final String HINT_LOCAL_STRATEGY_SORT_FIRST_MERGE = "LOCAL_STRATEGY_SORT_FIRST_MERGE"; /** * Value for the local strategy compiler hint that enforces a <b>sort merge based</b> local strategy. * The the second input is sorted, the first input is assumed to be sorted. After sorting both inputs are merged. * For example, a <i>Match</i> or <i>CoGroup</i> operator will use a sort-merge strategy to find pairs * of matching keys. * * @see #HINT_LOCAL_STRATEGY */ public static final String HINT_LOCAL_STRATEGY_SORT_SECOND_MERGE = "LOCAL_STRATEGY_SORT_SECOND_MERGE"; /** * Value for the local strategy compiler hint that enforces a <b>merge based</b> local strategy. * Both inputs are assumed to be sorted and are merged. * For example, a <i>Match</i> or <i>CoGroup</i> operator will use a merge strategy to find pairs * of matching keys. * * @see #HINT_LOCAL_STRATEGY */ public static final String HINT_LOCAL_STRATEGY_MERGE = "LOCAL_STRATEGY_MERGE"; /** * Value for the local strategy compiler hint that enforces a <b>hash based</b> local strategy. * For example, a <i>Match</i> operator will use a hybrid-hash-join strategy to find pairs of * matching keys. The <b>first</b> input will be used to build the hash table, the second input will be * used to probe the table. * * @see #HINT_LOCAL_STRATEGY */ public static final String HINT_LOCAL_STRATEGY_HASH_BUILD_FIRST = "LOCAL_STRATEGY_HASH_BUILD_FIRST"; /** * Value for the local strategy compiler hint that enforces a <b>hash based</b> local strategy. * For example, a <i>Match</i> operator will use a hybrid-hash-join strategy to find pairs of * matching keys. The <b>second</b> input will be used to build the hash table, the first input will be * used to probe the table. * * @see #HINT_LOCAL_STRATEGY */ public static final String HINT_LOCAL_STRATEGY_HASH_BUILD_SECOND = "LOCAL_STRATEGY_HASH_BUILD_SECOND"; /** * Value for the local strategy compiler hint that chooses the outer side of the <b>nested-loop</b> local strategy. * A <i>Cross</i> operator will process the data of the <b>first</b> input in the outer-loop of the nested loops. * Hence, the data of the first input will be is streamed though, while the data of the second input is stored on * disk * and repeatedly read. * * @see #HINT_LOCAL_STRATEGY */ public static final String HINT_LOCAL_STRATEGY_NESTEDLOOP_STREAMED_OUTER_FIRST = "LOCAL_STRATEGY_NESTEDLOOP_STREAMED_OUTER_FIRST"; /** * Value for the local strategy compiler hint that chooses the outer side of the <b>nested-loop</b> local strategy. * A <i>Cross</i> operator will process the data of the <b>second</b> input in the outer-loop of the nested loops. * Hence, the data of the second input will be is streamed though, while the data of the first input is stored on * disk * and repeatedly read. * * @see #HINT_LOCAL_STRATEGY */ public static final String HINT_LOCAL_STRATEGY_NESTEDLOOP_STREAMED_OUTER_SECOND = "LOCAL_STRATEGY_NESTEDLOOP_STREAMED_OUTER_SECOND"; /** * Value for the local strategy compiler hint that chooses the outer side of the <b>nested-loop</b> local strategy. * A <i>Cross</i> operator will process the data of the <b>first</b> input in the outer-loop of the nested loops. * Further more, the first input, being the outer side, will be processed in blocks, and for each block, the second * input, * being the inner side, will read repeatedly from disk. * * @see #HINT_LOCAL_STRATEGY */ public static final String HINT_LOCAL_STRATEGY_NESTEDLOOP_BLOCKED_OUTER_FIRST = "LOCAL_STRATEGY_NESTEDLOOP_BLOCKED_OUTER_FIRST"; /** * Value for the local strategy compiler hint that chooses the outer side of the <b>nested-loop</b> local strategy. * A <i>Cross</i> operator will process the data of the <b>second</b> input in the outer-loop of the nested loops. * Further more, the second input, being the outer side, will be processed in blocks, and for each block, the first * input, * being the inner side, will read repeatedly from disk. * * @see #HINT_LOCAL_STRATEGY */ public static final String HINT_LOCAL_STRATEGY_NESTEDLOOP_BLOCKED_OUTER_SECOND = "LOCAL_STRATEGY_NESTEDLOOP_BLOCKED_OUTER_SECOND"; /** * The log handle that is used by the compiler to log messages. */ public static final Log LOG = LogFactory.getLog(PactCompiler.class); // ------------------------------------------------------------------------ // Members // ------------------------------------------------------------------------ /** * The statistics object used to obtain statistics, such as input sizes, * for the cost estimation process. */ private final DataStatistics statistics; /** * The cost estimator used by the compiler. */ private final CostEstimator costEstimator; /** * The connection used to connect to the job-manager. */ private final InetSocketAddress jobManagerAddress; /** * The maximum number of machines (instances) to use, per the configuration. */ private int maxMachines; /** * The default degree of parallelism for jobs compiled by this compiler. */ private int defaultDegreeOfParallelism; /** * The maximum number of subtasks that should share an instance. */ private int maxIntraNodeParallelism; // ------------------------------------------------------------------------ // Constructor & Setup // ------------------------------------------------------------------------ /** * Creates a new compiler instance. The compiler has no access to statistics about the * inputs and can hence not determine any properties. It will perform all optimization with * unknown sizes and default to the most robust execution strategies. The * compiler also uses conservative default estimates for the operator costs, since * it has no access to another cost estimator. * <p> * The address of the job manager (to obtain system characteristics) is determined via the global configuration. */ public PactCompiler() { this(null, new DefaultCostEstimator()); } /** * Creates a new compiler instance that uses the statistics object to determine properties about the input. * Given those statistics, the compiler can make better choices for the execution strategies. * as if no filesystem was given. The compiler uses conservative default estimates for the operator costs, since * it has no access to another cost estimator. * <p> * The address of the job manager (to obtain system characteristics) is determined via the global configuration. * * @param stats * The statistics to be used to determine the input properties. */ public PactCompiler(DataStatistics stats) { this(stats, new DefaultCostEstimator()); } /** * Creates a new compiler instance. The compiler has no access to statistics about the * inputs and can hence not determine any properties. It will perform all optimization with * unknown sizes and default to the most robust execution strategies. It uses * however the given cost estimator to compute the costs of the individual operations. * <p> * The address of the job manager (to obtain system characteristics) is determined via the global configuration. * * @param estimator * The <tt>CostEstimator</tt> to use to cost the individual operations. */ public PactCompiler(CostEstimator estimator) { this(null, estimator); } /** * Creates a new compiler instance that uses the statistics object to determine properties about the input. * Given those statistics, the compiler can make better choices for the execution strategies. * as if no filesystem was given. It uses the given cost estimator to compute the costs of the individual * operations. * <p> * The address of the job manager (to obtain system characteristics) is determined via the global configuration. * * @param stats * The statistics to be used to determine the input properties. * @param estimator * The <tt>CostEstimator</tt> to use to cost the individual operations. */ public PactCompiler(DataStatistics stats, CostEstimator estimator) { this(stats, estimator, null); } /** * Creates a new compiler instance that uses the statistics object to determine properties about the input. * Given those statistics, the compiler can make better choices for the execution strategies. * as if no filesystem was given. It uses the given cost estimator to compute the costs of the individual * operations. * <p> * The given socket-address is used to connect to the job manager to obtain system characteristics, like available * memory. If that parameter is null, then the address is obtained from the global configuration. * * @param stats * The statistics to be used to determine the input properties. * @param estimator * The <tt>CostEstimator</tt> to use to cost the individual operations. * @param jobManagerConnection * The address of the job manager that is queried for system characteristics. */ public PactCompiler(DataStatistics stats, CostEstimator estimator, InetSocketAddress jobManagerConnection) { this.statistics = stats; this.costEstimator = estimator; Configuration config = GlobalConfiguration.getConfiguration(); // determine the maximum number of instances to use this.maxMachines = -1; // determine the default parallelization degree this.defaultDegreeOfParallelism = config.getInteger(ConfigConstants.DEFAULT_PARALLELIZATION_DEGREE_KEY, ConfigConstants.DEFAULT_PARALLELIZATION_DEGREE); // determine the default intra-node parallelism int maxInNodePar = config.getInteger(ConfigConstants.PARALLELIZATION_MAX_INTRA_NODE_DEGREE_KEY, ConfigConstants.DEFAULT_MAX_INTRA_NODE_PARALLELIZATION_DEGREE); if (maxInNodePar == 0 || maxInNodePar < -1) { LOG.error("Invalid maximum degree of intra-node parallelism: " + maxInNodePar + ". Ignoring parameter."); maxInNodePar = ConfigConstants.DEFAULT_MAX_INTRA_NODE_PARALLELIZATION_DEGREE; } this.maxIntraNodeParallelism = maxInNodePar; // assign the connection to the job-manager if (jobManagerConnection != null) { this.jobManagerAddress = jobManagerConnection; } else { final String address = config.getString(ConfigConstants.JOB_MANAGER_IPC_ADDRESS_KEY, null); if (address == null) { throw new CompilerException( "Cannot find address to job manager's RPC service in the global configuration."); } final int port = GlobalConfiguration.getInteger(ConfigConstants.JOB_MANAGER_IPC_PORT_KEY, ConfigConstants.DEFAULT_JOB_MANAGER_IPC_PORT); if (port < 0) { throw new CompilerException( "Cannot find port to job manager's RPC service in the global configuration."); } this.jobManagerAddress = new InetSocketAddress(address, port); } } // ------------------------------------------------------------------------ // Getters / Setters // ------------------------------------------------------------------------ public int getMaxMachines() { return maxMachines; } public void setMaxMachines(int maxMachines) { if (maxMachines == -1 || maxMachines > 0) { this.maxMachines = maxMachines; } else { throw new IllegalArgumentException(); } } public int getDefaultDegreeOfParallelism() { return defaultDegreeOfParallelism; } public void setDefaultDegreeOfParallelism(int defaultDegreeOfParallelism) { if (defaultDegreeOfParallelism == -1 || defaultDegreeOfParallelism > 0) { this.defaultDegreeOfParallelism = defaultDegreeOfParallelism; } else { throw new IllegalArgumentException(); } } public int getMaxIntraNodeParallelism() { return maxIntraNodeParallelism; } public void setMaxIntraNodeParallelism(int maxIntraNodeParallelism) { if (maxIntraNodeParallelism == -1 || maxIntraNodeParallelism > 0) { this.maxIntraNodeParallelism = maxIntraNodeParallelism; } else { throw new IllegalArgumentException(); } } // ------------------------------------------------------------------------ // Compilation // ------------------------------------------------------------------------ /** * Translates the given plan in to an OptimizedPlan, where all nodes have their local strategy assigned * and all channels have a shipping strategy assigned. The compiler connects to the job manager to obtain information * about the available instances and their memory and then chooses an instance type to schedule the execution on. * <p> * The compilation process itself goes through several phases: * <ol> * <li>Create an optimizer data flow representation of the program, assign parallelism and compute size estimates.</li> * <li>Compute interesting properties and auxiliary structures.</li> * <li>Enumerate plan alternatives. This cannot be done in the same step as the interesting property computation (as * opposed to the Database approaches), because we support plans that are not trees.</li> * </ol> * * @param program The program to be translated. * @return The optimized plan. * @throws CompilerException * Thrown, if the plan is invalid or the optimizer encountered an inconsistent * situation during the compilation process. */ public OptimizedPlan compile(Plan program) throws CompilerException { // -------------------- try to get the connection to the job manager ---------------------- // --------------------------to obtain instance information -------------------------------- final OptimizerPostPass postPasser = getPostPassFromPlan(program); return compile(program, getInstanceTypeInfo(), postPasser); } public OptimizedPlan compile(Plan program, InstanceTypeDescription type) throws CompilerException { final OptimizerPostPass postPasser = getPostPassFromPlan(program); return compile(program, type, postPasser); } /** * Translates the given pact plan in to an OptimizedPlan, where all nodes have their local strategy assigned * and all channels have a shipping strategy assigned. The process goes through several phases: * <ol> * <li>Create <tt>OptimizerNode</tt> representations of the PACTs, assign parallelism and compute size estimates.</li> * <li>Compute interesting properties and auxiliary structures.</li> * <li>Enumerate plan alternatives. This cannot be done in the same step as the interesting property computation (as * opposed to the Database approaches), because we support plans that are not trees.</li> * </ol> * * @param program The program to be translated. * @param type The instance type to schedule the execution on. Used also to determine the amount of memory * available to the tasks. * @param postPasser The function to be used for post passing the optimizer's plan and setting the * data type specific serialization routines. * @return The optimized plan. * * @throws CompilerException * Thrown, if the plan is invalid or the optimizer encountered an inconsistent * situation during the compilation process. */ private OptimizedPlan compile(Plan program, InstanceTypeDescription type, OptimizerPostPass postPasser) throws CompilerException { if (program == null || type == null || postPasser == null) throw new NullPointerException(); if (LOG.isDebugEnabled()) { LOG.debug("Beginning compilation of program '" + program.getJobName() + '\''); } final String instanceName = type.getInstanceType().getIdentifier(); // we subtract some percentage of the memory to accommodate for rounding errors final long memoryPerInstance = (long) (type.getHardwareDescription().getSizeOfFreeMemory() * 0.96f); final int numInstances = type.getMaximumNumberOfAvailableInstances(); // determine the maximum number of machines to use int maxMachinesJob = program.getMaxNumberMachines(); if (maxMachinesJob < 1) { maxMachinesJob = this.maxMachines; } else if (this.maxMachines >= 1) { // check if the program requested more than the global config allowed if (maxMachinesJob > this.maxMachines && LOG.isWarnEnabled()) { LOG.warn("Maximal number of machines specified in program (" + maxMachinesJob + ") exceeds the maximum number in the global configuration (" + this.maxMachines + "). Using the global configuration value."); } maxMachinesJob = Math.min(maxMachinesJob, this.maxMachines); } // adjust the maximum number of machines the the number of available instances if (maxMachinesJob < 1) { maxMachinesJob = numInstances; } else if (maxMachinesJob > numInstances) { maxMachinesJob = numInstances; if (LOG.isInfoEnabled()) { LOG.info("Maximal number of machines decreased to " + maxMachinesJob + " because no more instances are available."); } } // set the default degree of parallelism int defaultParallelism = program.getDefaultParallelism() > 0 ? program.getDefaultParallelism() : this.defaultDegreeOfParallelism; if (this.maxIntraNodeParallelism > 0) { if (defaultParallelism < 1) { defaultParallelism = maxMachinesJob * this.maxIntraNodeParallelism; } else if (defaultParallelism > maxMachinesJob * this.maxIntraNodeParallelism) { int oldParallelism = defaultParallelism; defaultParallelism = maxMachinesJob * this.maxIntraNodeParallelism; if (LOG.isInfoEnabled()) { LOG.info("Decreasing default degree of parallelism from " + oldParallelism + " to " + defaultParallelism + " to fit a maximum number of " + maxMachinesJob + " instances with a intra-parallelism of " + this.maxIntraNodeParallelism); } } } else if (defaultParallelism < 1) { defaultParallelism = maxMachinesJob; if (LOG.isInfoEnabled()) { LOG.info("No default parallelism specified. Using default parallelism of " + defaultParallelism + " (One task per instance)"); } } // log the output if (LOG.isDebugEnabled()) { LOG.debug("Using a default degree of parallelism of " + defaultParallelism + ", a maximum intra-node parallelism of " + this.maxIntraNodeParallelism + '.'); if (this.maxMachines > 0) { LOG.debug("The execution is limited to a maximum number of " + maxMachinesJob + " machines."); } } // the first step in the compilation is to create the optimizer plan representation // this step does the following: // 1) It creates an optimizer plan node for each operator // 2) It connects them via channels // 3) It looks for hints about local strategies and channel types and // sets the types and strategies accordingly // 4) It makes estimates about the data volume of the data sources and // propagates those estimates through the plan GraphCreatingVisitor graphCreator = new GraphCreatingVisitor(maxMachinesJob, defaultParallelism); program.accept(graphCreator); // if we have a plan with multiple data sinks, add logical optimizer nodes that have two data-sinks as children // each until we have only a single root node. This allows to transparently deal with the nodes with // multiple outputs OptimizerNode rootNode; if (graphCreator.sinks.size() == 1) { rootNode = graphCreator.sinks.get(0); } else if (graphCreator.sinks.size() > 1) { Iterator<DataSinkNode> iter = graphCreator.sinks.iterator(); rootNode = iter.next(); while (iter.hasNext()) { rootNode = new SinkJoiner(rootNode, iter.next()); } } else { throw new CompilerException("Bug: The optimizer plan representation has no sinks."); } // now that we have all nodes created and recorded which ones consume memory, tell the nodes their minimal // guaranteed memory, for further cost estimations. we assume an equal distribution of memory among consumer tasks rootNode.accept(new IdAndMemoryAndEstimatesVisitor(this.statistics, graphCreator.getMemoryConsumerCount() == 0 ? 0 : memoryPerInstance / graphCreator.getMemoryConsumerCount())); // Now that the previous step is done, the next step is to traverse the graph again for the two // steps that cannot directly be performed during the plan enumeration, because we are dealing with DAGs // rather than a trees. That requires us to deviate at some points from the classical DB optimizer algorithms. // // 1) propagate the interesting properties top-down through the graph // 2) Track information about nodes with multiple outputs that are later on reconnected in a node with // multiple inputs. InterestingPropertyVisitor propsVisitor = new InterestingPropertyVisitor(this.costEstimator); rootNode.accept(propsVisitor); BranchesVisitor branchingVisitor = new BranchesVisitor(); rootNode.accept(branchingVisitor); // perform a sanity check: the root may not have any unclosed branches if (rootNode.getOpenBranches() != null && rootNode.getOpenBranches().size() > 0) { throw new CompilerException("Bug: Logic for branching plans (non-tree plans) has an error, and does not " + "track the re-joining of branches correctly."); } // the final step is now to generate the actual plan alternatives List<PlanNode> bestPlan = rootNode.getAlternativePlans(this.costEstimator); if (bestPlan.size() != 1) { throw new CompilerException("Error in compiler: more than one best plan was created!"); } // check if the best plan's root is a data sink (single sink plan) // if so, directly take it. if it is a sink joiner node, get its contained sinks PlanNode bestPlanRoot = bestPlan.get(0); List<SinkPlanNode> bestPlanSinks = new ArrayList<SinkPlanNode>(4); if (bestPlanRoot instanceof SinkPlanNode) { bestPlanSinks.add((SinkPlanNode) bestPlanRoot); } else if (bestPlanRoot instanceof SinkJoinerPlanNode) { ((SinkJoinerPlanNode) bestPlanRoot).getDataSinks(bestPlanSinks); } DeadlockPreventer dp = new DeadlockPreventer(); dp.resolveDeadlocks(bestPlanSinks); // finalize the plan OptimizedPlan plan = new PlanFinalizer().createFinalPlan(bestPlanSinks, program.getJobName(), program, memoryPerInstance); plan.setInstanceTypeName(instanceName); // swap the binary unions for n-ary unions. this changes no strategies or memory consumers whatsoever, so // we can do this after the plan finalization plan.accept(new BinaryUnionReplacer()); // post pass the plan. this is the phase where the serialization and comparator code is set postPasser.postPass(plan); return plan; } /** * This function performs only the first step to the compilation process - the creation of the optimizer * representation of the plan. No estimations or enumerations of alternatives are done here. * * @param program The plan to generate the optimizer representation for. * @return The optimizer representation of the plan, as a collection of all data sinks * from the plan can be traversed. */ public static List<DataSinkNode> createPreOptimizedPlan(Plan program) { GraphCreatingVisitor graphCreator = new GraphCreatingVisitor(-1, 1); program.accept(graphCreator); return graphCreator.sinks; } // ------------------------------------------------------------------------ // Visitors for Compilation Traversals // ------------------------------------------------------------------------ /** * This utility class performs the translation from the user specified program to the optimizer plan. * It works as a visitor that walks the user's job in a depth-first fashion. During the descend, it creates * an optimizer node for each operator, respectively data source or -sink. During the ascend, it connects * the nodes to the full graph. * <p> * This translator relies on the <code>setInputs</code> method in the nodes. As that method implements the size * estimation and the awareness for optimizer hints, the sizes will be properly estimated and the translated plan * already respects all optimizer hints. */ private static final class GraphCreatingVisitor implements Visitor<Operator> { private final Map<Operator, OptimizerNode> con2node; // map from the operator objects to their // corresponding optimizer nodes private final List<DataSourceNode> sources; // all data source nodes in the optimizer plan private final List<DataSinkNode> sinks; // all data sink nodes in the optimizer plan private final int maxMachines; // the maximum number of machines to use private final int defaultParallelism; // the default degree of parallelism private int numMemoryConsumers; private final GraphCreatingVisitor parent; // reference to enclosing creator, in case of a recursive translation private final boolean forceDOP; private GraphCreatingVisitor(int maxMachines, int defaultParallelism) { this(null, false, maxMachines, defaultParallelism, null); } private GraphCreatingVisitor(GraphCreatingVisitor parent, boolean forceDOP, int maxMachines, int defaultParallelism, HashMap<Operator, OptimizerNode> closure) { if(closure == null){ con2node = new HashMap<Operator, OptimizerNode>(); }else{ con2node = closure; } this.sources = new ArrayList<DataSourceNode>(4); this.sinks = new ArrayList<DataSinkNode>(2); this.maxMachines = maxMachines; this.defaultParallelism = defaultParallelism; this.parent = parent; this.forceDOP = forceDOP; } @Override public boolean preVisit(Operator c) { // check if we have been here before if (this.con2node.containsKey(c)) { return false; } final OptimizerNode n; // create a node for the operator (or sink or source) if we have not been here before if (c instanceof GenericDataSink) { DataSinkNode dsn = new DataSinkNode((GenericDataSink) c); this.sinks.add(dsn); n = dsn; } else if (c instanceof GenericDataSource) { DataSourceNode dsn = new DataSourceNode((GenericDataSource<?>) c); this.sources.add(dsn); n = dsn; } else if (c instanceof MapOperatorBase) { n = new CollectorMapNode((MapOperatorBase<?>) c); } else if (c instanceof PlainMapOperatorBase) { n = new MapNode((PlainMapOperatorBase<?>) c); } else if (c instanceof FlatMapOperatorBase) { n = new FlatMapNode((FlatMapOperatorBase<?>) c); } else if (c instanceof ReduceOperatorBase) { n = new ReduceNode((ReduceOperatorBase<?>) c); } else if (c instanceof GroupReduceOperatorBase) { n = new GroupReduceNode((GroupReduceOperatorBase<?>) c); } else if (c instanceof JoinOperatorBase) { n = new MatchNode((JoinOperatorBase<?>) c); } else if (c instanceof CoGroupOperatorBase) { n = new CoGroupNode((CoGroupOperatorBase<?>) c); } else if (c instanceof CrossOperatorBase) { n = new CrossNode((CrossOperatorBase<?>) c); } else if (c instanceof BulkIteration) { n = new BulkIterationNode((BulkIteration) c); } else if (c instanceof DeltaIteration) { n = new WorksetIterationNode((DeltaIteration) c); } else if (c instanceof PartialSolutionPlaceHolder) { final PartialSolutionPlaceHolder holder = (PartialSolutionPlaceHolder) c; final BulkIteration enclosingIteration = holder.getContainingBulkIteration(); final BulkIterationNode containingIterationNode = (BulkIterationNode) this.parent.con2node.get(enclosingIteration); // catch this for the recursive translation of step functions BulkPartialSolutionNode p = new BulkPartialSolutionNode(holder, containingIterationNode); p.setDegreeOfParallelism(containingIterationNode.getDegreeOfParallelism()); p.setSubtasksPerInstance(containingIterationNode.getSubtasksPerInstance()); n = p; } else if (c instanceof WorksetPlaceHolder) { final WorksetPlaceHolder holder = (WorksetPlaceHolder) c; final DeltaIteration enclosingIteration = holder.getContainingWorksetIteration(); final WorksetIterationNode containingIterationNode = (WorksetIterationNode) this.parent.con2node.get(enclosingIteration); // catch this for the recursive translation of step functions WorksetNode p = new WorksetNode(holder, containingIterationNode); p.setDegreeOfParallelism(containingIterationNode.getDegreeOfParallelism()); p.setSubtasksPerInstance(containingIterationNode.getSubtasksPerInstance()); n = p; } else if (c instanceof SolutionSetPlaceHolder) { final SolutionSetPlaceHolder holder = (SolutionSetPlaceHolder) c; final DeltaIteration enclosingIteration = holder.getContainingWorksetIteration(); final WorksetIterationNode containingIterationNode = (WorksetIterationNode) this.parent.con2node.get(enclosingIteration); // catch this for the recursive translation of step functions SolutionSetNode p = new SolutionSetNode(holder, containingIterationNode); p.setDegreeOfParallelism(containingIterationNode.getDegreeOfParallelism()); p.setSubtasksPerInstance(containingIterationNode.getSubtasksPerInstance()); n = p; } else { throw new IllegalArgumentException("Unknown operator type."); } this.con2node.put(c, n); // record the potential memory consumption this.numMemoryConsumers += n.isMemoryConsumer() ? 1 : 0; // set the parallelism only if it has not been set before. some nodes have a fixed DOP, such as the // key-less reducer (all-reduce) if (n.getDegreeOfParallelism() < 1) { // set the degree of parallelism int par = c.getDegreeOfParallelism(); if (par > 0) { if (this.forceDOP && par != this.defaultParallelism) { par = this.defaultParallelism; LOG.warn("The degree-of-parallelism of nested Dataflows (such as step functions in iterations) is " + "currently fixed to the degree-of-parallelism of the surrounding operator (the iteration)."); } } else { par = this.defaultParallelism; } n.setDegreeOfParallelism(par); } // check if we need to set the instance sharing accordingly such that // the maximum number of machines is not exceeded if (n.getSubtasksPerInstance() < 1) { int tasksPerInstance = 1; if (this.maxMachines > 0) { int p = n.getDegreeOfParallelism(); tasksPerInstance = (p / this.maxMachines) + (p % this.maxMachines == 0 ? 0 : 1); } // we group together n tasks per machine, depending on config and the above computed // value required to obey the maximum number of machines n.setSubtasksPerInstance(tasksPerInstance); } return true; } @Override public void postVisit(Operator c) { OptimizerNode n = this.con2node.get(c); // first connect to the predecessors n.setInputs(this.con2node); n.setBroadcastInputs(this.con2node); // if the node represents a bulk iteration, we recursively translate the data flow now if (n instanceof BulkIterationNode) { final BulkIterationNode iterNode = (BulkIterationNode) n; final BulkIteration iter = iterNode.getIterationContract(); // calculate closure of the anonymous function HashMap<Operator, OptimizerNode> closure = new HashMap<Operator, OptimizerNode>(con2node); // first, recursively build the data flow for the step function final GraphCreatingVisitor recursiveCreator = new GraphCreatingVisitor(this, true, this.maxMachines, iterNode.getDegreeOfParallelism(), closure); BulkPartialSolutionNode partialSolution = null; iter.getNextPartialSolution().accept(recursiveCreator); partialSolution = (BulkPartialSolutionNode) recursiveCreator.con2node.get(iter.getPartialSolution()); OptimizerNode rootOfStepFunction = recursiveCreator.con2node.get(iter.getNextPartialSolution()); if (partialSolution == null) { throw new CompilerException("Error: The step functions result does not depend on the partial solution."); } OptimizerNode terminationCriterion = null; if (iter.getTerminationCriterion() != null) { terminationCriterion = recursiveCreator.con2node.get(iter.getTerminationCriterion()); // no intermediate node yet, traverse from the termination criterion to build the missing parts if (terminationCriterion == null) { iter.getTerminationCriterion().accept(recursiveCreator); terminationCriterion = recursiveCreator.con2node.get(iter.getTerminationCriterion()); // this does unfortunately not work, as the partial solution node is known to exist at // this point (otherwise the check for the next partial solution would have failed already) // partialSolution = (BulkPartialSolutionNode) recursiveCreator.con2node.get(iter.getPartialSolution()); // // if (partialSolution == null) { // throw new CompilerException("Error: The termination criterion result does not depend on the partial solution."); // } } } iterNode.setNextPartialSolution(rootOfStepFunction, terminationCriterion); iterNode.setPartialSolution(partialSolution); // account for the nested memory consumers this.numMemoryConsumers += recursiveCreator.numMemoryConsumers; // go over the contained data flow and mark the dynamic path nodes - rootOfStepFunction.accept(new StaticDynamicPathIdentifier(iterNode.getCostWeight())); + StaticDynamicPathIdentifier identifier = new StaticDynamicPathIdentifier(iterNode.getCostWeight()); + rootOfStepFunction.accept(identifier); + if(terminationCriterion != null){ + terminationCriterion.accept(identifier); + } } else if (n instanceof WorksetIterationNode) { final WorksetIterationNode iterNode = (WorksetIterationNode) n; final DeltaIteration iter = iterNode.getIterationContract(); // calculate the closure of the anonymous function HashMap<Operator, OptimizerNode> closure = new HashMap<Operator, OptimizerNode>(con2node); // first, recursively build the data flow for the step function final GraphCreatingVisitor recursiveCreator = new GraphCreatingVisitor(this, true, this.maxMachines, iterNode.getDegreeOfParallelism(), closure); // descend from the solution set delta. check that it depends on both the workset // and the solution set. If it does depend on both, this descend should create both nodes iter.getSolutionSetDelta().accept(recursiveCreator); final SolutionSetNode solutionSetNode = (SolutionSetNode) recursiveCreator.con2node.get(iter.getSolutionSet()); final WorksetNode worksetNode = (WorksetNode) recursiveCreator.con2node.get(iter.getWorkset()); if (worksetNode == null) { throw new CompilerException("In the given plan, the solution set delta does not depend on the workset. This is a prerequisite in workset iterations."); } iter.getNextWorkset().accept(recursiveCreator); // for now, check that the solution set it joined with only once. we want to allow multiple joins // with the solution set later when we can share data structures among operators. also, the join // must be a match which is at the same time the solution set delta if (solutionSetNode == null || solutionSetNode.getOutgoingConnections() == null || solutionSetNode.getOutgoingConnections().isEmpty()) { throw new CompilerException("Error: The step function does not reference the solution set."); } else { if (solutionSetNode.getOutgoingConnections().size() > 1) { throw new CompilerException("Error: The solution set may currently be joined with only once."); } else { OptimizerNode successor = solutionSetNode.getOutgoingConnections().get(0).getTarget(); if (successor.getClass() == MatchNode.class) { // find out which input to the match the solution set is MatchNode mn = (MatchNode) successor; if (mn.getFirstPredecessorNode() == solutionSetNode) { mn.fixDriverStrategy(DriverStrategy.HYBRIDHASH_BUILD_FIRST); } else if (mn.getSecondPredecessorNode() == solutionSetNode) { mn.fixDriverStrategy(DriverStrategy.HYBRIDHASH_BUILD_SECOND); } else { throw new CompilerException(); } } else if (successor.getClass() == CoGroupNode.class) { CoGroupNode cg = (CoGroupNode) successor; if (cg.getFirstPredecessorNode() == solutionSetNode) { cg.makeCoGroupWithSolutionSet(0); } else if (cg.getSecondPredecessorNode() == solutionSetNode) { cg.makeCoGroupWithSolutionSet(1); } else { throw new CompilerException(); } } else { throw new CompilerException("Error: The solution set may only be joined with through a Match or a CoGroup."); } } } final OptimizerNode nextWorksetNode = recursiveCreator.con2node.get(iter.getNextWorkset()); final OptimizerNode solutionSetDeltaNode = recursiveCreator.con2node.get(iter.getSolutionSetDelta()); // set the step function nodes to the iteration node iterNode.setPartialSolution(solutionSetNode, worksetNode); iterNode.setNextPartialSolution(solutionSetDeltaNode, nextWorksetNode); // account for the nested memory consumers this.numMemoryConsumers += recursiveCreator.numMemoryConsumers; // go over the contained data flow and mark the dynamic path nodes StaticDynamicPathIdentifier pathIdentifier = new StaticDynamicPathIdentifier(iterNode.getCostWeight()); nextWorksetNode.accept(pathIdentifier); iterNode.getSolutionSetDelta().accept(pathIdentifier); } } int getMemoryConsumerCount() { return this.numMemoryConsumers; } }; private static final class StaticDynamicPathIdentifier implements Visitor<OptimizerNode> { private final Set<OptimizerNode> seenBefore = new HashSet<OptimizerNode>(); private final int costWeight; private StaticDynamicPathIdentifier(int costWeight) { this.costWeight = costWeight; } @Override public boolean preVisit(OptimizerNode visitable) { return this.seenBefore.add(visitable); } @Override public void postVisit(OptimizerNode visitable) { visitable.identifyDynamicPath(this.costWeight); } } /** * Simple visitor that sets the minimal guaranteed memory per task based on the amount of available memory, * the number of memory consumers, and on the task's degree of parallelism. */ private static final class IdAndMemoryAndEstimatesVisitor implements Visitor<OptimizerNode> { private final DataStatistics statistics; private final long memoryPerTaskPerInstance; private int id = 1; private IdAndMemoryAndEstimatesVisitor(DataStatistics statistics, long memoryPerTaskPerInstance) { this.statistics = statistics; this.memoryPerTaskPerInstance = memoryPerTaskPerInstance; } @Override public boolean preVisit(OptimizerNode visitable) { if (visitable.getId() != -1) { // been here before return false; } // assign minimum memory share, for lower bound estimates final long mem = visitable.isMemoryConsumer() ? this.memoryPerTaskPerInstance / visitable.getSubtasksPerInstance() : 0; visitable.setMinimalMemoryPerSubTask(mem); return true; } @Override public void postVisit(OptimizerNode visitable) { // the node ids visitable.initId(this.id++); // connections need to figure out their maximum path depths for (PactConnection conn : visitable.getIncomingConnections()) { conn.initMaxDepth(); } for (PactConnection conn : visitable.getBroadcastConnections()) { conn.initMaxDepth(); } // the estimates visitable.computeOutputEstimates(this.statistics); // if required, recurse into the step function if (visitable instanceof IterationNode) { ((IterationNode) visitable).acceptForStepFunction(this); } } } /** * Visitor that computes the interesting properties for each node in the plan. On its recursive * depth-first descend, it propagates all interesting properties top-down. */ public static final class InterestingPropertyVisitor implements Visitor<OptimizerNode> { private CostEstimator estimator; // the cost estimator for maximal costs of an interesting property /** * Creates a new visitor that computes the interesting properties for all nodes in the plan. * It uses the given cost estimator used to compute the maximal costs for an interesting property. * * @param estimator * The cost estimator to estimate the maximal costs for interesting properties. */ public InterestingPropertyVisitor(CostEstimator estimator) { this.estimator = estimator; } @Override public boolean preVisit(OptimizerNode node) { // The interesting properties must be computed on the descend. In case a node has multiple outputs, // that computation must happen during the last descend. if (node.getInterestingProperties() == null && node.haveAllOutputConnectionInterestingProperties()) { node.computeUnionOfInterestingPropertiesFromSuccessors(); node.computeInterestingPropertiesForInputs(this.estimator); return true; } else { return false; } } @Override public void postVisit(OptimizerNode visitable) {} } /** * Visitor that computes the interesting properties for each node in the plan. On its recursive * depth-first descend, it propagates all interesting properties top-down. On its re-ascend, * it computes auxiliary maps that are needed to support plans that are not a minimally connected * DAG (Such plans are not trees, but at least one node feeds its output into more than one other * node). */ private static final class BranchesVisitor implements Visitor<OptimizerNode> { @Override public boolean preVisit(OptimizerNode node) { return node.getOpenBranches() == null; } @Override public void postVisit(OptimizerNode node) { if (node instanceof IterationNode) { ((IterationNode) node).acceptForStepFunction(this); } node.computeUnclosedBranchStack(); } }; /** * Utility class that traverses a plan to collect all nodes and add them to the OptimizedPlan. * Besides collecting all nodes, this traversal assigns the memory to the nodes. */ private static final class PlanFinalizer implements Visitor<PlanNode> { private final Set<PlanNode> allNodes; // a set of all nodes in the optimizer plan private final List<SourcePlanNode> sources; // all data source nodes in the optimizer plan private final List<SinkPlanNode> sinks; // all data sink nodes in the optimizer plan private final Deque<IterationPlanNode> stackOfIterationNodes; private long memoryPerInstance; // the amount of memory per instance private int memoryConsumerWeights; // a counter of all memory consumers /** * Creates a new plan finalizer. */ private PlanFinalizer() { this.allNodes = new HashSet<PlanNode>(); this.sources = new ArrayList<SourcePlanNode>(); this.sinks = new ArrayList<SinkPlanNode>(); this.stackOfIterationNodes = new ArrayDeque<IterationPlanNode>(); } private OptimizedPlan createFinalPlan(List<SinkPlanNode> sinks, String jobName, Plan originalPlan, long memPerInstance) { if (LOG.isDebugEnabled()) LOG.debug("Available memory per instance: " + memPerInstance); this.memoryPerInstance = memPerInstance; this.memoryConsumerWeights = 0; // traverse the graph for (SinkPlanNode node : sinks) { node.accept(this); } // assign the memory to each node if (this.memoryConsumerWeights > 0) { final long memoryPerInstanceAndWeight = this.memoryPerInstance / this.memoryConsumerWeights; if (LOG.isDebugEnabled()) LOG.debug("Memory per consumer weight: " + memoryPerInstanceAndWeight); for (PlanNode node : this.allNodes) { // assign memory to the driver strategy of the node final int consumerWeight = node.getMemoryConsumerWeight(); if (consumerWeight > 0) { final long mem = memoryPerInstanceAndWeight * consumerWeight / node.getSubtasksPerInstance(); node.setMemoryPerSubTask(mem); if (LOG.isDebugEnabled()) { final long mib = mem >> 20; LOG.debug("Assigned " + mib + " MiBytes memory to each subtask of " + node.getPactContract().getName() + " (" + mib * node.getDegreeOfParallelism() + " MiBytes total.)"); } } // assign memory to the local and global strategies of the channels for (Iterator<Channel> channels = node.getInputs(); channels.hasNext();) { final Channel c = channels.next(); if (c.getLocalStrategy().dams()) { final long mem = memoryPerInstanceAndWeight / node.getSubtasksPerInstance(); c.setMemoryLocalStrategy(mem); if (LOG.isDebugEnabled()) { final long mib = mem >> 20; LOG.debug("Assigned " + mib + " MiBytes memory to each local strategy instance of " + c + " (" + mib * node.getDegreeOfParallelism() + " MiBytes total.)"); } } if (c.getTempMode() != TempMode.NONE) { final long mem = memoryPerInstanceAndWeight / node.getSubtasksPerInstance(); c.setTempMemory(mem); if (LOG.isDebugEnabled()) { final long mib = mem >> 20; LOG.debug("Assigned " + mib + " MiBytes memory to each instance of the temp table for " + c + " (" + mib * node.getDegreeOfParallelism() + " MiBytes total.)"); } } } } } return new OptimizedPlan(this.sources, this.sinks, this.allNodes, jobName, originalPlan); } @Override public boolean preVisit(PlanNode visitable) { // if we come here again, prevent a further descend if (!this.allNodes.add(visitable)) { return false; } if (visitable instanceof SinkPlanNode) { this.sinks.add((SinkPlanNode) visitable); } else if (visitable instanceof SourcePlanNode) { this.sources.add((SourcePlanNode) visitable); } else if (visitable instanceof BulkPartialSolutionPlanNode) { // tell the partial solution about the iteration node that contains it final BulkPartialSolutionPlanNode pspn = (BulkPartialSolutionPlanNode) visitable; final IterationPlanNode iteration = this.stackOfIterationNodes.peekLast(); // sanity check! if (iteration == null || !(iteration instanceof BulkIterationPlanNode)) { throw new CompilerException("Bug: Error finalizing the plan. " + "Cannot associate the node for a partial solutions with its containing iteration."); } pspn.setContainingIterationNode((BulkIterationPlanNode) iteration); } else if (visitable instanceof WorksetPlanNode) { // tell the partial solution about the iteration node that contains it final WorksetPlanNode wspn = (WorksetPlanNode) visitable; final IterationPlanNode iteration = this.stackOfIterationNodes.peekLast(); // sanity check! if (iteration == null || !(iteration instanceof WorksetIterationPlanNode)) { throw new CompilerException("Bug: Error finalizing the plan. " + "Cannot associate the node for a partial solutions with its containing iteration."); } wspn.setContainingIterationNode((WorksetIterationPlanNode) iteration); } else if (visitable instanceof SolutionSetPlanNode) { // tell the partial solution about the iteration node that contains it final SolutionSetPlanNode sspn = (SolutionSetPlanNode) visitable; final IterationPlanNode iteration = this.stackOfIterationNodes.peekLast(); // sanity check! if (iteration == null || !(iteration instanceof WorksetIterationPlanNode)) { throw new CompilerException("Bug: Error finalizing the plan. " + "Cannot associate the node for a partial solutions with its containing iteration."); } sspn.setContainingIterationNode((WorksetIterationPlanNode) iteration); } // double-connect the connections. previously, only parents knew their children, because // one child candidate could have been referenced by multiple parents. for (Iterator<Channel> iter = visitable.getInputs(); iter.hasNext();) { final Channel conn = iter.next(); conn.setTarget(visitable); conn.getSource().addOutgoingChannel(conn); } for (Channel c : visitable.getBroadcastInputs()) { c.setTarget(visitable); c.getSource().addOutgoingChannel(c); } // count the memory consumption this.memoryConsumerWeights += visitable.getMemoryConsumerWeight(); for (Iterator<Channel> channels = visitable.getInputs(); channels.hasNext();) { final Channel c = channels.next(); if (c.getLocalStrategy().dams()) { this.memoryConsumerWeights++; } if (c.getTempMode() != TempMode.NONE) { this.memoryConsumerWeights++; } } for (Channel c : visitable.getBroadcastInputs()) { if (c.getLocalStrategy().dams()) { this.memoryConsumerWeights++; } if (c.getTempMode() != TempMode.NONE) { this.memoryConsumerWeights++; } } // pass the visitor to the iteraton's step function if (visitable instanceof IterationPlanNode) { // push the iteration node onto the stack final IterationPlanNode iterNode = (IterationPlanNode) visitable; this.stackOfIterationNodes.addLast(iterNode); // recurse ((IterationPlanNode) visitable).acceptForStepFunction(this); // pop the iteration node from the stack this.stackOfIterationNodes.removeLast(); } return true; } @Override public void postVisit(PlanNode visitable) {} } /** * A visitor that traverses the graph and collects cascading binary unions into a single n-ary * union operator. The exception is, when on of the union inputs is materialized, such as in the * static-code-path-cache in iterations. */ private static final class BinaryUnionReplacer implements Visitor<PlanNode> { private final Set<PlanNode> seenBefore = new HashSet<PlanNode>(); @Override public boolean preVisit(PlanNode visitable) { if (this.seenBefore.add(visitable)) { if (visitable instanceof IterationPlanNode) { ((IterationPlanNode) visitable).acceptForStepFunction(this); } return true; } else { return false; } } @Override public void postVisit(PlanNode visitable) { if (visitable instanceof BinaryUnionPlanNode) { final BinaryUnionPlanNode unionNode = (BinaryUnionPlanNode) visitable; final Channel in1 = unionNode.getInput1(); final Channel in2 = unionNode.getInput2(); PlanNode newUnionNode; // if any input is cached, we keep this as a binary union and do not collapse it into a // n-ary union // if (in1.getTempMode().isCached() || in2.getTempMode().isCached()) { // // replace this node by an explicit operator // Channel cached, pipelined; // if (in1.getTempMode().isCached()) { // cached = in1; // pipelined = in2; // } else { // cached = in2; // pipelined = in1; // } // // newUnionNode = new DualInputPlanNode(unionNode.getOriginalOptimizerNode(), cached, pipelined, // DriverStrategy.UNION_WITH_CACHED); // newUnionNode.initProperties(unionNode.getGlobalProperties(), new LocalProperties()); // // in1.setTarget(newUnionNode); // in2.setTarget(newUnionNode); // } else { // collect the union inputs to collapse this operator with // its collapsed predecessors. check whether an input is materialized to prevent // collapsing List<Channel> inputs = new ArrayList<Channel>(); collect(in1, inputs); collect(in2, inputs); newUnionNode = new NAryUnionPlanNode(unionNode.getOptimizerNode(), inputs, unionNode.getGlobalProperties()); // adjust the input channels to have their target point to the new union node for (Channel c : inputs) { c.setTarget(newUnionNode); } // } unionNode.getOutgoingChannels().get(0).swapUnionNodes(newUnionNode); } } private void collect(Channel in, List<Channel> inputs) { if (in.getSource() instanceof NAryUnionPlanNode) { // sanity check if (in.getShipStrategy() != ShipStrategyType.FORWARD) { throw new CompilerException("Bug: Plan generation for Unions picked a ship strategy between binary plan operators."); } if (!(in.getLocalStrategy() == null || in.getLocalStrategy() == LocalStrategy.NONE)) { throw new CompilerException("Bug: Plan generation for Unions picked a local strategy between binary plan operators."); } inputs.addAll(((NAryUnionPlanNode) in.getSource()).getListOfInputs()); } else { // is not a union node, so we take the channel directly inputs.add(in); } } } // ------------------------------------------------------------------------ // Miscellaneous // ------------------------------------------------------------------------ private OptimizerPostPass getPostPassFromPlan(Plan program) { final String className = program.getPostPassClassName(); if (className == null) { throw new CompilerException("Optimizer Post Pass class description is null"); } try { Class<? extends OptimizerPostPass> clazz = Class.forName(className).asSubclass(OptimizerPostPass.class); try { return InstantiationUtil.instantiate(clazz, OptimizerPostPass.class); } catch (RuntimeException rtex) { // unwrap the source exception if (rtex.getCause() != null) { throw new CompilerException("Cannot instantiate optimizer post pass: " + rtex.getMessage(), rtex.getCause()); } else { throw rtex; } } } catch (ClassNotFoundException cnfex) { throw new CompilerException("Cannot load Optimizer post-pass class '" + className + "'.", cnfex); } catch (ClassCastException ccex) { throw new CompilerException("Class '" + className + "' is not an optimizer post passer.", ccex); } } private InstanceTypeDescription getInstanceTypeInfo() { if (LOG.isDebugEnabled()) { LOG.debug("Connecting compiler to JobManager to dertermine instance information."); } // create the connection in a separate thread, such that this thread // can abort, if an unsuccessful connection occurs. Map<InstanceType, InstanceTypeDescription> instances = null; JobManagerConnector jmc = new JobManagerConnector(this.jobManagerAddress); Thread connectorThread = new Thread(jmc, "Compiler - JobManager connector."); connectorThread.setDaemon(true); connectorThread.start(); // connect and get the result try { jmc.waitForCompletion(); instances = jmc.instances; if (instances == null) { throw new NullPointerException("Returned instance map is <null>"); } } catch (Throwable t) { throw new CompilerException("Available instances could not be determined from job manager: " + t.getMessage(), t); } // determine which type to run on return getType(instances); } /** * This utility method picks the instance type to be used for executing programs. * <p> * * @param types The available types. * @return The type to be used for scheduling. * * @throws CompilerException * @throws IllegalArgumentException */ private InstanceTypeDescription getType(Map<InstanceType, InstanceTypeDescription> types) throws CompilerException { if (types == null || types.size() < 1) { throw new IllegalArgumentException("No instance type found."); } InstanceTypeDescription retValue = null; long totalMemory = 0; int numInstances = 0; final Iterator<InstanceTypeDescription> it = types.values().iterator(); while(it.hasNext()) { final InstanceTypeDescription descr = it.next(); // skip instances for which no hardware description is available // this means typically that no if (descr.getHardwareDescription() == null || descr.getInstanceType() == null) { continue; } final int curInstances = descr.getMaximumNumberOfAvailableInstances(); final long curMemory = curInstances * descr.getHardwareDescription().getSizeOfFreeMemory(); // get, if first, or if it has more instances and not less memory, or if it has significantly more memory // and the same number of cores still if ( (retValue == null) || (curInstances > numInstances && (int) (curMemory * 1.2f) > totalMemory) || (curInstances * retValue.getInstanceType().getNumberOfCores() >= numInstances && (int) (curMemory * 1.5f) > totalMemory) ) { retValue = descr; numInstances = curInstances; totalMemory = curMemory; } } if (retValue == null) { throw new CompilerException("No instance currently registered at the job-manager. Retry later.\n" + "If the system has recently started, it may take a few seconds until the instances register."); } return retValue; } /** * Utility class for an asynchronous connection to the job manager to determine the available instances. */ private static final class JobManagerConnector implements Runnable { private static final long MAX_MILLIS_TO_WAIT = 10000; private final InetSocketAddress jobManagerAddress; private final Object lock = new Object(); private volatile Map<InstanceType, InstanceTypeDescription> instances; private volatile Throwable error; private JobManagerConnector(InetSocketAddress jobManagerAddress) { this.jobManagerAddress = jobManagerAddress; } public void waitForCompletion() throws Throwable { long start = System.currentTimeMillis(); long remaining = MAX_MILLIS_TO_WAIT; if (this.error != null) { throw this.error; } if (this.instances != null) { return; } do { try { synchronized (this.lock) { this.lock.wait(remaining); } } catch (InterruptedException iex) {} } while (this.error == null && this.instances == null && (remaining = MAX_MILLIS_TO_WAIT + start - System.currentTimeMillis()) > 0); if (this.error != null) { throw this.error; } if (this.instances != null) { return; } // try to forcefully shut this thread down throw new IOException("Connection timed out."); } @Override public void run() { ExtendedManagementProtocol jobManagerConnection = null; try { jobManagerConnection = RPC.getProxy(ExtendedManagementProtocol.class, this.jobManagerAddress, NetUtils.getSocketFactory()); this.instances = jobManagerConnection.getMapOfAvailableInstanceTypes(); if (this.instances == null) { throw new IOException("Returned instance map was <null>"); } } catch (Throwable t) { this.error = t; } finally { // first of all, signal completion synchronized (this.lock) { this.lock.notifyAll(); } if (jobManagerConnection != null) { try { RPC.stopProxy(jobManagerConnection); } catch (Throwable t) { LOG.error("Could not cleanly shut down connection from compiler to job manager,", t); } } jobManagerConnection = null; } } } } diff --git a/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dag/BulkIterationNode.java b/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dag/BulkIterationNode.java index c02794311..f1a3c10b4 100644 --- a/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dag/BulkIterationNode.java +++ b/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dag/BulkIterationNode.java @@ -1,337 +1,337 @@ /*********************************************************************************************************************** * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.compiler.dag; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import eu.stratosphere.api.common.operators.BulkIteration; import eu.stratosphere.compiler.CompilerException; import eu.stratosphere.compiler.DataStatistics; import eu.stratosphere.compiler.PactCompiler.InterestingPropertyVisitor; import eu.stratosphere.compiler.costs.CostEstimator; import eu.stratosphere.compiler.dag.WorksetIterationNode.SingleRootJoiner; import eu.stratosphere.compiler.dataproperties.GlobalProperties; import eu.stratosphere.compiler.dataproperties.InterestingProperties; import eu.stratosphere.compiler.dataproperties.LocalProperties; import eu.stratosphere.compiler.dataproperties.RequestedGlobalProperties; import eu.stratosphere.compiler.dataproperties.RequestedLocalProperties; import eu.stratosphere.compiler.operators.NoOpDescriptor; import eu.stratosphere.compiler.operators.OperatorDescriptorSingle; import eu.stratosphere.compiler.plan.BulkIterationPlanNode; import eu.stratosphere.compiler.plan.BulkPartialSolutionPlanNode; import eu.stratosphere.compiler.plan.Channel; import eu.stratosphere.compiler.plan.NamedChannel; import eu.stratosphere.compiler.plan.PlanNode; import eu.stratosphere.util.Visitor; /** * A node in the optimizer's program representation for a bulk iteration. */ public class BulkIterationNode extends SingleInputNode implements IterationNode { private BulkPartialSolutionNode partialSolution; private OptimizerNode terminationCriterion; private OptimizerNode nextPartialSolution; private PactConnection rootConnection; private PactConnection terminationCriterionRootConnection; private OptimizerNode singleRoot; private final int costWeight; // -------------------------------------------------------------------------------------------- /** * Creates a new node with a single input for the optimizer plan. * * @param pactContract The PACT that the node represents. */ public BulkIterationNode(BulkIteration iteration) { super(iteration); if (iteration.getMaximumNumberOfIterations() <= 0) { throw new CompilerException("BulkIteration must have a maximum number of iterations specified."); } int numIters = iteration.getMaximumNumberOfIterations(); this.costWeight = (numIters > 0 && numIters < OptimizerNode.MAX_DYNAMIC_PATH_COST_WEIGHT) ? numIters : OptimizerNode.MAX_DYNAMIC_PATH_COST_WEIGHT; } // -------------------------------------------------------------------------------------------- public BulkIteration getIterationContract() { return (BulkIteration) getPactContract(); } /** * Gets the partialSolution from this BulkIterationNode. * * @return The partialSolution. */ public BulkPartialSolutionNode getPartialSolution() { return partialSolution; } /** * Sets the partialSolution for this BulkIterationNode. * * @param partialSolution The partialSolution to set. */ public void setPartialSolution(BulkPartialSolutionNode partialSolution) { this.partialSolution = partialSolution; } /** * Gets the nextPartialSolution from this BulkIterationNode. * * @return The nextPartialSolution. */ public OptimizerNode getNextPartialSolution() { return nextPartialSolution; } /** * Sets the nextPartialSolution for this BulkIterationNode. * * @param nextPartialSolution The nextPartialSolution to set. */ public void setNextPartialSolution(OptimizerNode nextPartialSolution, OptimizerNode terminationCriterion) { // check if the root of the step function has the same DOP as the iteration if (nextPartialSolution.getDegreeOfParallelism() != getDegreeOfParallelism() || nextPartialSolution.getSubtasksPerInstance() != getSubtasksPerInstance() ) { // add a no-op to the root to express the re-partitioning NoOpNode noop = new NoOpNode(); noop.setDegreeOfParallelism(getDegreeOfParallelism()); noop.setSubtasksPerInstance(getSubtasksPerInstance()); PactConnection noOpConn = new PactConnection(nextPartialSolution, noop); noop.setIncomingConnection(noOpConn); nextPartialSolution.addOutgoingConnection(noOpConn); nextPartialSolution = noop; } this.nextPartialSolution = nextPartialSolution; this.terminationCriterion = terminationCriterion; if (terminationCriterion == null) { this.singleRoot = nextPartialSolution; this.rootConnection = new PactConnection(nextPartialSolution); } else { // we have a termination criterion SingleRootJoiner singleRootJoiner = new SingleRootJoiner(); this.rootConnection = new PactConnection(nextPartialSolution, singleRootJoiner); this.terminationCriterionRootConnection = new PactConnection(terminationCriterion, singleRootJoiner); singleRootJoiner.setInputs(this.rootConnection, this.terminationCriterionRootConnection); this.singleRoot = singleRootJoiner; // add connection to terminationCriterion for interesting properties visitor terminationCriterion.addOutgoingConnection(terminationCriterionRootConnection); } nextPartialSolution.addOutgoingConnection(rootConnection); } public int getCostWeight() { return this.costWeight; } public OptimizerNode getSingleRootOfStepFunction() { return this.singleRoot; } // -------------------------------------------------------------------------------------------- @Override public String getName() { return "Bulk Iteration"; } @Override public boolean isFieldConstant(int input, int fieldNumber) { return false; } protected void readStubAnnotations() {} @Override protected void computeOperatorSpecificDefaultEstimates(DataStatistics statistics) { this.estimatedOutputSize = getPredecessorNode().getEstimatedOutputSize(); this.estimatedNumRecords = getPredecessorNode().getEstimatedNumRecords(); } // -------------------------------------------------------------------------------------------- // Properties and Optimization // -------------------------------------------------------------------------------------------- protected List<OperatorDescriptorSingle> getPossibleProperties() { return Collections.<OperatorDescriptorSingle>singletonList(new NoOpDescriptor()); } @Override public boolean isMemoryConsumer() { return true; } @Override public void computeInterestingPropertiesForInputs(CostEstimator estimator) { final InterestingProperties intProps = getInterestingProperties().clone(); if (this.terminationCriterion != null) { // first propagate through termination Criterion. since it has no successors, it has no // interesting properties this.terminationCriterionRootConnection.setInterestingProperties(new InterestingProperties()); this.terminationCriterion.accept(new InterestingPropertyVisitor(estimator)); } // we need to make 2 interesting property passes, because the root of the step function needs also // the interesting properties as generated by the partial solution // give our own interesting properties (as generated by the iterations successors) to the step function and // make the first pass this.rootConnection.setInterestingProperties(intProps); this.nextPartialSolution.accept(new InterestingPropertyVisitor(estimator)); // take the interesting properties of the partial solution and add them to the root interesting properties InterestingProperties partialSolutionIntProps = this.partialSolution.getInterestingProperties(); intProps.getGlobalProperties().addAll(partialSolutionIntProps.getGlobalProperties()); intProps.getLocalProperties().addAll(partialSolutionIntProps.getLocalProperties()); // clear all interesting properties to prepare the second traversal // this clears only the path down from the next partial solution. The paths down // from the termination criterion (before they meet the paths down from the next partial solution) // remain unaffected by this step this.rootConnection.clearInterestingProperties(); this.nextPartialSolution.accept(InterestingPropertiesClearer.INSTANCE); // 2nd pass this.rootConnection.setInterestingProperties(intProps); this.nextPartialSolution.accept(new InterestingPropertyVisitor(estimator)); // now add the interesting properties of the partial solution to the input final InterestingProperties inProps = this.partialSolution.getInterestingProperties().clone(); inProps.addGlobalProperties(new RequestedGlobalProperties()); inProps.addLocalProperties(new RequestedLocalProperties()); this.inConn.setInterestingProperties(inProps); } @Override public void computeUnclosedBranchStack() { if (this.openBranches != null) { return; } // handle the data flow branching for the regular inputs addClosedBranches(getPredecessorNode().closedBranchingNodes); addClosedBranches(getNextPartialSolution().closedBranchingNodes); List<UnclosedBranchDescriptor> result1 = getPredecessorNode().getBranchesForParent(this.inConn); List<UnclosedBranchDescriptor> result2 = getSingleRootOfStepFunction().openBranches; ArrayList<UnclosedBranchDescriptor> inputsMerged = new ArrayList<UnclosedBranchDescriptor>(); mergeLists(result1, result2, inputsMerged); // handle the data flow branching for the broadcast inputs List<UnclosedBranchDescriptor> result = computeUnclosedBranchStackForBroadcastInputs(inputsMerged); this.openBranches = (result == null || result.isEmpty()) ? Collections.<UnclosedBranchDescriptor>emptyList() : result; } @Override protected void instantiateCandidate(OperatorDescriptorSingle dps, Channel in, List<Set<? extends NamedChannel>> broadcastPlanChannels, List<PlanNode> target, CostEstimator estimator, RequestedGlobalProperties globPropsReq, RequestedLocalProperties locPropsReq) { // NOTES ON THE ENUMERATION OF THE STEP FUNCTION PLANS: // Whenever we instantiate the iteration, we enumerate new candidates for the step function. // That way, we make sure we have an appropriate plan for each candidate for the initial partial solution, // we have a fitting candidate for the step function (often, work is pushed out of the step function). // Among the candidates of the step function, we keep only those that meet the requested properties of the // current candidate initial partial solution. That makes sure these properties exist at the beginning of // the successive iteration. // 1) Because we enumerate multiple times, we may need to clean the cached plans // before starting another enumeration this.nextPartialSolution.accept(PlanCacheCleaner.INSTANCE); // 2) Give the partial solution the properties of the current candidate for the initial partial solution this.partialSolution.setCandidateProperties(in.getGlobalProperties(), in.getLocalProperties()); final BulkPartialSolutionPlanNode pspn = this.partialSolution.getCurrentPartialSolutionPlanNode(); // 3) Get the alternative plans List<PlanNode> candidates = this.nextPartialSolution.getAlternativePlans(estimator); // 4) Throw away all that are not compatible with the properties currently requested to the // initial partial solution for (Iterator<PlanNode> planDeleter = candidates.iterator(); planDeleter.hasNext(); ) { PlanNode candidate = planDeleter.next(); if (!(globPropsReq.isMetBy(candidate.getGlobalProperties()) && locPropsReq.isMetBy(candidate.getLocalProperties()))) { planDeleter.remove(); } } // 5) Create a candidate for the Iteration Node for every remaining plan of the step function. if (terminationCriterion == null) { for (PlanNode candidate : candidates) { BulkIterationPlanNode node = new BulkIterationPlanNode(this, "BulkIteration ("+this.getPactContract().getName()+")", in, pspn, candidate); GlobalProperties gProps = candidate.getGlobalProperties().clone(); LocalProperties lProps = candidate.getLocalProperties().clone(); node.initProperties(gProps, lProps); target.add(node); } } - else { + else if(candidates.size() > 0) { List<PlanNode> terminationCriterionCandidates = this.terminationCriterion.getAlternativePlans(estimator); for (PlanNode candidate : candidates) { for(PlanNode terminationCandidate : terminationCriterionCandidates) { if (this.singleRoot.areBranchCompatible(candidate, terminationCandidate)) { BulkIterationPlanNode node = new BulkIterationPlanNode(this, "BulkIteration ("+this.getPactContract().getName()+")", in, pspn, candidate, terminationCandidate); GlobalProperties gProps = candidate.getGlobalProperties().clone(); LocalProperties lProps = candidate.getLocalProperties().clone(); node.initProperties(gProps, lProps); target.add(node); } } } } } // -------------------------------------------------------------------------------------------- // Iteration Specific Traversals // -------------------------------------------------------------------------------------------- public void acceptForStepFunction(Visitor<OptimizerNode> visitor) { this.singleRoot.accept(visitor); } } diff --git a/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dag/OptimizerNode.java b/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dag/OptimizerNode.java index 60b0bc408..5dee643b5 100644 --- a/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dag/OptimizerNode.java +++ b/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/dag/OptimizerNode.java @@ -1,1257 +1,1258 @@ /*********************************************************************************************************************** * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.compiler.dag; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import eu.stratosphere.api.common.operators.AbstractUdfOperator; import eu.stratosphere.api.common.operators.CompilerHints; import eu.stratosphere.api.common.operators.Operator; import eu.stratosphere.api.common.operators.util.FieldSet; import eu.stratosphere.compiler.CompilerException; import eu.stratosphere.compiler.DataStatistics; import eu.stratosphere.compiler.costs.CostEstimator; import eu.stratosphere.compiler.dataproperties.InterestingProperties; import eu.stratosphere.compiler.dataproperties.RequestedGlobalProperties; import eu.stratosphere.compiler.dataproperties.RequestedLocalProperties; import eu.stratosphere.compiler.plan.PlanNode; import eu.stratosphere.compiler.plandump.DumpableConnection; import eu.stratosphere.compiler.plandump.DumpableNode; import eu.stratosphere.pact.runtime.shipping.ShipStrategyType; import eu.stratosphere.util.Visitable; import eu.stratosphere.util.Visitor; /** * This class represents a node in the optimizer's internal representation of the PACT plan. It contains * extra information about estimates, hints and data properties. */ public abstract class OptimizerNode implements Visitable<OptimizerNode>, EstimateProvider, DumpableNode<OptimizerNode> { public static final int MAX_DYNAMIC_PATH_COST_WEIGHT = 100; // -------------------------------------------------------------------------------------------- // Members // -------------------------------------------------------------------------------------------- private final Operator pactContract; // The operator (Reduce / Join / DataSource / ...) private List<String> broadcastConnectionNames = new ArrayList<String>(); // the broadcast inputs names of this node private List<PactConnection> broadcastConnections = new ArrayList<PactConnection>(); // the broadcast inputs of this node private List<PactConnection> outgoingConnections; // The links to succeeding nodes private InterestingProperties intProps; // the interesting properties of this node // --------------------------------- Branch Handling ------------------------------------------ protected List<UnclosedBranchDescriptor> openBranches; // stack of branches in the sub-graph that are not joined protected Set<OptimizerNode> closedBranchingNodes; // stack of branching nodes which have already been closed protected List<OptimizerNode> hereJoinedBranchers; // the branching nodes (node with multiple outputs) // that at least two children share and that are at least partially joined // ---------------------------- Estimates and Annotations ------------------------------------- protected long estimatedOutputSize = -1; // the estimated size of the output (bytes) protected long estimatedNumRecords = -1; // the estimated number of key/value pairs in the output protected Set<FieldSet> uniqueFields; // set of attributes that will always be unique after this node // --------------------------------- General Parameters --------------------------------------- private int degreeOfParallelism = -1; // the number of parallel instances of this node private int subtasksPerInstance = -1; // the number of parallel instance that will run on the same machine private long minimalMemoryPerSubTask = -1; protected int id = -1; // the id for this node. protected int costWeight = 1; // factor to weight the costs for dynamic paths protected boolean onDynamicPath; protected List<PlanNode> cachedPlans; // cache candidates, because the may be accessed repeatedly protected int[][] remappedKeys; // ------------------------------------------------------------------------ // Constructor / Setup // ------------------------------------------------------------------------ /** * Creates a new node for the optimizer plan. * * @param op The operator that the node represents. */ public OptimizerNode(Operator op) { this.pactContract = op; readStubAnnotations(); if (this.pactContract instanceof AbstractUdfOperator) { final AbstractUdfOperator<?> pact = (AbstractUdfOperator<?>) this.pactContract; this.remappedKeys = new int[pact.getNumberOfInputs()][]; for (int i = 0; i < this.remappedKeys.length; i++) { final int[] keys = pact.getKeyColumns(i); int[] rk = new int[keys.length]; System.arraycopy(keys, 0, rk, 0, keys.length); this.remappedKeys[i] = rk; } } } protected OptimizerNode(OptimizerNode toCopy) { this.pactContract = toCopy.pactContract; this.intProps = toCopy.intProps; this.remappedKeys = toCopy.remappedKeys; this.openBranches = toCopy.openBranches; this.closedBranchingNodes = toCopy.closedBranchingNodes; this.estimatedOutputSize = toCopy.estimatedOutputSize; this.estimatedNumRecords = toCopy.estimatedNumRecords; this.degreeOfParallelism = toCopy.degreeOfParallelism; this.subtasksPerInstance = toCopy.subtasksPerInstance; this.minimalMemoryPerSubTask = toCopy.minimalMemoryPerSubTask; this.id = toCopy.id; this.costWeight = toCopy.costWeight; this.onDynamicPath = toCopy.onDynamicPath; } // ------------------------------------------------------------------------ // Abstract methods that implement node specific behavior // and the pact type specific optimization methods. // ------------------------------------------------------------------------ /** * Gets the name of this node. This returns either the name of the PACT, or * a string marking the node as a data source or a data sink. * * @return The node name. */ public abstract String getName(); /** * This function is for plan translation purposes. Upon invocation, the implementing subclasses should * examine its contained contract and look at the contracts that feed their data into that contract. * The method should then create a <tt>PactConnection</tt> for each of those inputs. * <p> * In addition, the nodes must set the shipping strategy of the connection, if a suitable optimizer hint is found. * * @param contractToNode * The map to translate the contracts to their corresponding optimizer nodes. */ public abstract void setInputs(Map<Operator, OptimizerNode> contractToNode); /** * This function is for plan translation purposes. Upon invocation, this method creates a {@link PactConnection} * for each one of the broadcast inputs associated with the {@code Operator} referenced by this node. * <p> * The {@code PactConnections} must set its shipping strategy type to BROADCAST. * * @param operatorToNode * The map associating operators with their corresponding optimizer nodes. * @throws CompilerException */ public void setBroadcastInputs(Map<Operator, OptimizerNode> operatorToNode) throws CompilerException { // skip for Operators that don't support broadcast variables if (!(getPactContract() instanceof AbstractUdfOperator<?>)) { return; } // get all broadcast inputs AbstractUdfOperator<?> operator = ((AbstractUdfOperator<?>) getPactContract()); // create connections and add them for (Map.Entry<String, Operator> input: operator.getBroadcastInputs().entrySet()) { OptimizerNode predecessor = operatorToNode.get(input.getValue()); PactConnection connection = new PactConnection(predecessor, this, ShipStrategyType.BROADCAST); addBroadcastConnection(input.getKey(), connection); predecessor.addOutgoingConnection(connection); } } /** * This method needs to be overridden by subclasses to return the children. * * @return The list of incoming links. */ public abstract List<PactConnection> getIncomingConnections(); /** * Tells the node to compute the interesting properties for its inputs. The interesting properties * for the node itself must have been computed before. * The node must then see how many of interesting properties it preserves and add its own. * * @param estimator The {@code CostEstimator} instance to use for plan cost estimation. */ public abstract void computeInterestingPropertiesForInputs(CostEstimator estimator); /** * This method causes the node to compute the description of open branches in its sub-plan. An open branch * describes, that a (transitive) child node had multiple outputs, which have not all been re-joined in the * sub-plan. This method needs to set the <code>openBranches</code> field to a stack of unclosed branches, the * latest one top. A branch is considered closed, if some later node sees all of the branching node's outputs, * no matter if there have been more branches to different paths in the meantime. */ public abstract void computeUnclosedBranchStack(); protected List<UnclosedBranchDescriptor> computeUnclosedBranchStackForBroadcastInputs(List<UnclosedBranchDescriptor> branchesSoFar) { // handle the data flow branching for the broadcast inputs for (PactConnection broadcastInput : getBroadcastConnections()) { OptimizerNode bcSource = broadcastInput.getSource(); addClosedBranches(bcSource.closedBranchingNodes); List<UnclosedBranchDescriptor> bcBranches = bcSource.getBranchesForParent(broadcastInput); ArrayList<UnclosedBranchDescriptor> mergedBranches = new ArrayList<UnclosedBranchDescriptor>(); mergeLists(branchesSoFar, bcBranches, mergedBranches); branchesSoFar = mergedBranches.isEmpty() ? Collections.<UnclosedBranchDescriptor>emptyList() : mergedBranches; } return branchesSoFar; } /** * Computes the plan alternatives for this node, an implicitly for all nodes that are children of * this node. This method must determine for each alternative the global and local properties * and the costs. This method may recursively call <code>getAlternatives()</code> on its children * to get their plan alternatives, and build its own alternatives on top of those. * * @param estimator * The cost estimator used to estimate the costs of each plan alternative. * @return A list containing all plan alternatives. */ public abstract List<PlanNode> getAlternativePlans(CostEstimator estimator); /** * This method implements the visit of a depth-first graph traversing visitor. Implementors must first * call the <code>preVisit()</code> method, then hand the visitor to their children, and finally call * the <code>postVisit()</code> method. * * @param visitor * The graph traversing visitor. * @see eu.stratosphere.util.Visitable#accept(eu.stratosphere.util.Visitor) */ @Override public abstract void accept(Visitor<OptimizerNode> visitor); /** * Checks, whether this node requires memory for its tasks or not. * * @return True, if this node contains logic that requires memory usage, false otherwise. */ public abstract boolean isMemoryConsumer(); /** * Checks whether a field is modified by the user code or whether it is kept unchanged. * * @param input The input number. * @param fieldNumber The position of the field. * * @return True if the field is not changed by the user function, false otherwise. */ public abstract boolean isFieldConstant(int input, int fieldNumber); // ------------------------------------------------------------------------ // Getters / Setters // ------------------------------------------------------------------------ @Override public Iterator<OptimizerNode> getPredecessors() { List<OptimizerNode> allPredecessors = new ArrayList<OptimizerNode>(); for (Iterator<PactConnection> inputs = getIncomingConnections().iterator(); inputs.hasNext(); ){ allPredecessors.add(inputs.next().getSource()); } for (PactConnection conn : getBroadcastConnections()) { allPredecessors.add(conn.getSource()); } return allPredecessors.iterator(); } /** * Gets the ID of this node. If the id has not yet been set, this method returns -1; * * @return This node's id, or -1, if not yet set. */ public int getId() { return this.id; } /** * Sets the ID of this node. * * @param id * The id for this node. */ public void initId(int id) { if (id <= 0) throw new IllegalArgumentException(); if (this.id == -1) { this.id = id; } else { throw new IllegalStateException("Id has already been initialized."); } } /** * Adds the broadcast connection identified by the given {@code name} to this node. * * @param broadcastConnection * The connection to add. */ public void addBroadcastConnection(String name, PactConnection broadcastConnection) { this.broadcastConnectionNames.add(name); this.broadcastConnections.add(broadcastConnection); } /** * Return the list of names associated with broadcast inputs for this node. */ public List<String> getBroadcastConnectionNames() { return this.broadcastConnectionNames; } /** * Return the list of inputs associated with broadcast variables for this node. */ public List<PactConnection> getBroadcastConnections() { return this.broadcastConnections; } /** * Adds a new outgoing connection to this node. * * @param pactConnection * The connection to add. */ public void addOutgoingConnection(PactConnection pactConnection) { if (this.outgoingConnections == null) { this.outgoingConnections = new ArrayList<PactConnection>(); } else { if (this.outgoingConnections.size() == 64) { throw new CompilerException("Cannot currently handle nodes with more than 64 outputs."); } } this.outgoingConnections.add(pactConnection); } /** * The list of outgoing connections from this node to succeeding tasks. * * @return The list of outgoing connections. */ public List<PactConnection> getOutgoingConnections() { return this.outgoingConnections; } /** * Gets the object that specifically describes the contract of this node. * * @return This node's contract. */ public Operator getPactContract() { return this.pactContract; } /** * Gets the degree of parallelism for the contract represented by this optimizer node. * The degree of parallelism denotes how many parallel instances of the user function will be * spawned during the execution. If this value is <code>-1</code>, then the system will take * the default number of parallel instances. * * @return The degree of parallelism. */ public int getDegreeOfParallelism() { return this.degreeOfParallelism; } /** * Sets the degree of parallelism for the contract represented by this optimizer node. * The degree of parallelism denotes how many parallel instances of the user function will be * spawned during the execution. If this value is set to <code>-1</code>, then the system will take * the default number of parallel instances. * * @param degreeOfParallelism * The degree of parallelism to set. * @throws IllegalArgumentException * If the degree of parallelism is smaller than one. */ public void setDegreeOfParallelism(int degreeOfParallelism) { if (degreeOfParallelism < 1) { throw new IllegalArgumentException(); } this.degreeOfParallelism = degreeOfParallelism; } /** * Gets the number of parallel instances of the contract that are * to be executed on the same compute instance (logical machine). * * @return The number of subtask instances per machine. */ public int getSubtasksPerInstance() { return this.subtasksPerInstance; } /** * Sets the number of parallel task instances of the contract that are * to be executed on the same computing instance (logical machine). * * @param instancesPerMachine The instances per machine. * @throws IllegalArgumentException If the number of instances per machine is smaller than one. */ public void setSubtasksPerInstance(int instancesPerMachine) { if (instancesPerMachine < 1) { throw new IllegalArgumentException(); } this.subtasksPerInstance = instancesPerMachine; } /** * Gets the minimal guaranteed memory per subtask for tasks represented by this OptimizerNode. * * @return The minimal guaranteed memory per subtask, in bytes. */ public long getMinimalMemoryPerSubTask() { return this.minimalMemoryPerSubTask; } /** * Sets the minimal guaranteed memory per subtask for tasks represented by this OptimizerNode. * * @param minimalGuaranteedMemory The minimal guaranteed memory per subtask, in bytes. */ public void setMinimalMemoryPerSubTask(long minimalGuaranteedMemory) { this.minimalMemoryPerSubTask = minimalGuaranteedMemory; } /** * Gets the amount of memory that all subtasks of this task have jointly available. * * @return The total amount of memory across all subtasks. */ public long getMinimalMemoryAcrossAllSubTasks() { return this.minimalMemoryPerSubTask == -1 ? -1 : this.minimalMemoryPerSubTask * this.degreeOfParallelism; } public boolean isOnDynamicPath() { return this.onDynamicPath; } public void identifyDynamicPath(int costWeight) { boolean anyDynamic = false; boolean allDynamic = true; for (PactConnection conn : getIncomingConnections()) { boolean dynamicIn = conn.isOnDynamicPath(); anyDynamic |= dynamicIn; allDynamic &= dynamicIn; } for (PactConnection conn : getBroadcastConnections()) { boolean dynamicIn = conn.isOnDynamicPath(); anyDynamic |= dynamicIn; allDynamic &= dynamicIn; } if (anyDynamic) { this.onDynamicPath = true; this.costWeight = costWeight; if (!allDynamic) { // this node joins static and dynamic path. // mark the connections where the source is not dynamic as cached for (PactConnection conn : getIncomingConnections()) { if (!conn.getSource().isOnDynamicPath()) { conn.setMaterializationMode(conn.getMaterializationMode().makeCached()); } } // broadcast variables are always cached, because they stay unchanged available in the // runtime context of the functions } } } public int getCostWeight() { return this.costWeight; } public int getMaxDepth() { int maxDepth = 0; for (PactConnection conn : getIncomingConnections()) { maxDepth = Math.max(maxDepth, conn.getMaxDepth()); } for (PactConnection conn : getBroadcastConnections()) { maxDepth = Math.max(maxDepth, conn.getMaxDepth()); } return maxDepth; } /** * Gets the properties that are interesting for this node to produce. * * @return The interesting properties for this node, or null, if not yet computed. */ public InterestingProperties getInterestingProperties() { return this.intProps; } public long getEstimatedOutputSize() { return this.estimatedOutputSize; } public long getEstimatedNumRecords() { return this.estimatedNumRecords; } public float getEstimatedAvgWidthPerOutputRecord() { if (this.estimatedOutputSize > 0 && this.estimatedNumRecords > 0) { return ((float) this.estimatedOutputSize) / this.estimatedNumRecords; } else { return -1.0f; } } /** * Checks whether this node has branching output. A node's output is branched, if it has more * than one output connection. * * @return True, if the node's output branches. False otherwise. */ public boolean isBranching() { return getOutgoingConnections() != null && getOutgoingConnections().size() > 1; } // ------------------------------------------------------------------------ // Miscellaneous // ------------------------------------------------------------------------ /** * Checks, if all outgoing connections have their interesting properties set from their target nodes. * * @return True, if on all outgoing connections, the interesting properties are set. False otherwise. */ public boolean haveAllOutputConnectionInterestingProperties() { for (PactConnection conn : getOutgoingConnections()) { if (conn.getInterestingProperties() == null) { return false; } } return true; } /** * Computes all the interesting properties that are relevant to this node. The interesting * properties are a union of the interesting properties on each outgoing connection. * However, if two interesting properties on the outgoing connections overlap, * the interesting properties will occur only once in this set. For that, this * method deduplicates and merges the interesting properties. * This method returns copies of the original interesting properties objects and * leaves the original objects, contained by the connections, unchanged. */ public void computeUnionOfInterestingPropertiesFromSuccessors() { List<PactConnection> conns = getOutgoingConnections(); if (conns.size() == 0) { // no incoming, we have none ourselves this.intProps = new InterestingProperties(); } else { this.intProps = conns.get(0).getInterestingProperties().clone(); for (int i = 1; i < conns.size(); i++) { this.intProps.addInterestingProperties(conns.get(i).getInterestingProperties()); } } this.intProps.dropTrivials(); } public void clearInterestingProperties() { this.intProps = null; for (PactConnection conn : getIncomingConnections()) { conn.clearInterestingProperties(); } for (PactConnection conn : getBroadcastConnections()) { conn.clearInterestingProperties(); } } /** * Causes this node to compute its output estimates (such as number of rows, size in bytes) * based on the inputs and the compiler hints. The compiler hints are instantiated with conservative * default values which are used if no other values are provided. Nodes may access the statistics to * determine relevant information. * * @param statistics * The statistics object which may be accessed to get statistical information. * The parameter may be null, if no statistics are available. */ public void computeOutputEstimates(DataStatistics statistics) { // sanity checking for (PactConnection c : getIncomingConnections()) { if (c.getSource() == null) { throw new CompilerException("Bug: Estimate computation called before inputs have been set."); } } // let every operator do its computation computeOperatorSpecificDefaultEstimates(statistics); // overwrite default estimates with hints, if given if (getPactContract() == null || getPactContract().getCompilerHints() == null) { return ; } CompilerHints hints = getPactContract().getCompilerHints(); if (hints.getOutputSize() >= 0) { this.estimatedOutputSize = hints.getOutputSize(); } if (hints.getOutputCardinality() >= 0) { this.estimatedNumRecords = hints.getOutputCardinality(); } if (hints.getFilterFactor() >= 0.0f) { if (this.estimatedNumRecords >= 0) { this.estimatedNumRecords = (long) (this.estimatedNumRecords * hints.getFilterFactor()); if (this.estimatedOutputSize >= 0) { this.estimatedOutputSize = (long) (this.estimatedOutputSize * hints.getFilterFactor()); } } else if (this instanceof SingleInputNode) { OptimizerNode pred = ((SingleInputNode) this).getPredecessorNode(); if (pred != null && pred.getEstimatedNumRecords() >= 0) { this.estimatedNumRecords = (long) (pred.getEstimatedNumRecords() * hints.getFilterFactor()); } } } // use the width to infer the cardinality (given size) and vice versa if (hints.getAvgOutputRecordSize() >= 1) { // the estimated number of rows based on size if (this.estimatedNumRecords == -1 && this.estimatedOutputSize >= 0) { this.estimatedNumRecords = (long) (this.estimatedOutputSize / hints.getAvgOutputRecordSize()); } else if (this.estimatedOutputSize == -1 && this.estimatedNumRecords >= 0) { this.estimatedOutputSize = (long) (this.estimatedNumRecords * hints.getAvgOutputRecordSize()); } } } protected abstract void computeOperatorSpecificDefaultEstimates(DataStatistics statistics); // ------------------------------------------------------------------------ // Reading of stub annotations // ------------------------------------------------------------------------ /** * Reads all stub annotations, i.e. which fields remain constant, what cardinality bounds the * functions have, which fields remain unique. */ protected void readStubAnnotations() { readUniqueFieldsAnnotation(); } protected void readUniqueFieldsAnnotation() { if (this.pactContract.getCompilerHints() != null) { Set<FieldSet> uniqueFieldSets = pactContract.getCompilerHints().getUniqueFields(); if (uniqueFieldSets != null) { if (this.uniqueFields == null) { this.uniqueFields = new HashSet<FieldSet>(); } this.uniqueFields.addAll(uniqueFieldSets); } } } // ------------------------------------------------------------------------ // Access of stub annotations // ------------------------------------------------------------------------ /** * Returns the key columns for the specific input, if all keys are preserved * by this node. Null, otherwise. * * @param input * @return */ protected int[] getConstantKeySet(int input) { Operator contract = getPactContract(); if (contract instanceof AbstractUdfOperator<?>) { AbstractUdfOperator<?> abstractPact = (AbstractUdfOperator<?>) contract; int[] keyColumns = abstractPact.getKeyColumns(input); if (keyColumns != null) { if (keyColumns.length == 0) { return null; } for (int keyColumn : keyColumns) { if (!isFieldConstant(input, keyColumn)) { return null; } } return keyColumns; } } return null; } /** * An optional method where nodes can describe which fields will be unique in their output. * @return */ public List<FieldSet> createUniqueFieldsForNode() { return null; } /** * Gets the FieldSets which are unique in the output of the node. * * @return */ public Set<FieldSet> getUniqueFields() { return this.uniqueFields == null ? Collections.<FieldSet>emptySet() : this.uniqueFields; } // -------------------------------------------------------------------------------------------- // Miscellaneous // -------------------------------------------------------------------------------------------- public BinaryUnionNode createdUnionCascade(List<Operator> children, Map<Operator, OptimizerNode> contractToNode, ShipStrategyType preSet) { if (children.size() < 2) { throw new IllegalArgumentException(); } BinaryUnionNode lastUnion = null; for (int i = 1; i < children.size(); i++) { if (i == 1) { OptimizerNode in1 = contractToNode.get(children.get(0)); OptimizerNode in2 = contractToNode.get(children.get(1)); lastUnion = new BinaryUnionNode(in1, in2, preSet); } else { OptimizerNode nextIn = contractToNode.get(children.get(i)); lastUnion = new BinaryUnionNode(lastUnion, nextIn); lastUnion.getFirstIncomingConnection().setShipStrategy(ShipStrategyType.FORWARD); if (preSet != null) { lastUnion.getSecondIncomingConnection().setShipStrategy(preSet); } } lastUnion.setDegreeOfParallelism(getDegreeOfParallelism()); lastUnion.setSubtasksPerInstance(getSubtasksPerInstance()); } return lastUnion; } // -------------------------------------------------------------------------------------------- // Pruning // -------------------------------------------------------------------------------------------- protected void prunePlanAlternatives(List<PlanNode> plans) { if (plans.isEmpty()) { throw new CompilerException("No plan meeting the requirements could be created @ " + this + ". Most likely reason: Too restrictive plan hints."); } // shortcut for the simple case if (plans.size() == 1) { return; } // we can only compare plan candidates that made equal choices // at the branching points. for each choice at a branching point, // we need to keep the cheapest (wrt. interesting properties). // if we do not keep candidates for each branch choice, we might not // find branch compatible candidates when joining the branches back. // for pruning, we are quasi AFTER the node, so in the presence of // branches, we need form the per-branch-choice groups by the choice // they made at the latest unjoined branching node. Note that this is // different from the check for branch compatibility of candidates, as // this happens on the input sub-plans and hence BEFORE the node (therefore // it is relevant to find the latest (partially) joined branch point. if (this.openBranches == null || this.openBranches.isEmpty()) { prunePlanAlternativesWithCommonBranching(plans); } else { // partition the candidates into groups that made the same sub-plan candidate // choice at the latest unclosed branch point final OptimizerNode[] branchDeterminers = new OptimizerNode[this.openBranches.size()]; for (int i = 0; i < branchDeterminers.length; i++) { branchDeterminers[i] = this.openBranches.get(this.openBranches.size() - 1 - i).getBranchingNode(); } // this sorter sorts by the candidate choice at the branch point Comparator<PlanNode> sorter = new Comparator<PlanNode>() { @Override public int compare(PlanNode o1, PlanNode o2) { for (int i = 0; i < branchDeterminers.length; i++) { PlanNode n1 = o1.getCandidateAtBranchPoint(branchDeterminers[i]); PlanNode n2 = o2.getCandidateAtBranchPoint(branchDeterminers[i]); int hash1 = System.identityHashCode(n1); int hash2 = System.identityHashCode(n2); if (hash1 != hash2) { return hash1 - hash2; } } return 0; } }; Collections.sort(plans, sorter); List<PlanNode> result = new ArrayList<PlanNode>(); List<PlanNode> turn = new ArrayList<PlanNode>(); final PlanNode[] determinerChoice = new PlanNode[branchDeterminers.length]; while (!plans.isEmpty()) { // take one as the determiner turn.clear(); PlanNode determiner = plans.remove(plans.size() - 1); turn.add(determiner); for (int i = 0; i < determinerChoice.length; i++) { determinerChoice[i] = determiner.getCandidateAtBranchPoint(branchDeterminers[i]); } // go backwards through the plans and find all that are equal boolean stillEqual = true; for (int k = plans.size() - 1; k >= 0 && stillEqual; k--) { PlanNode toCheck = plans.get(k); for (int i = 0; i < branchDeterminers.length; i++) { PlanNode checkerChoice = toCheck.getCandidateAtBranchPoint(branchDeterminers[i]); if (checkerChoice != determinerChoice[i]) { // not the same anymore stillEqual = false; break; } } if (stillEqual) { // the same plans.remove(k); turn.add(toCheck); } } // now that we have only plans with the same branch alternatives, prune! if (turn.size() > 1) { prunePlanAlternativesWithCommonBranching(turn); } result.addAll(turn); } // after all turns are complete plans.clear(); plans.addAll(result); } } protected void prunePlanAlternativesWithCommonBranching(List<PlanNode> plans) { // for each interesting property, which plans are cheapest final RequestedGlobalProperties[] gps = (RequestedGlobalProperties[]) this.intProps.getGlobalProperties().toArray(new RequestedGlobalProperties[this.intProps.getGlobalProperties().size()]); final RequestedLocalProperties[] lps = (RequestedLocalProperties[]) this.intProps.getLocalProperties().toArray(new RequestedLocalProperties[this.intProps.getLocalProperties().size()]); final PlanNode[][] toKeep = new PlanNode[gps.length][]; final PlanNode[] cheapestForGlobal = new PlanNode[gps.length]; PlanNode cheapest = null; // the overall cheapest plan // go over all plans from the list for (PlanNode candidate : plans) { // check if that plan is the overall cheapest if (cheapest == null || (cheapest.getCumulativeCosts().compareTo(candidate.getCumulativeCosts()) > 0)) { cheapest = candidate; } // find the interesting global properties that this plan matches for (int i = 0; i < gps.length; i++) { if (gps[i].isMetBy(candidate.getGlobalProperties())) { // the candidate meets the global property requirements. That means // it has a chance that its local properties are re-used (they would be // destroyed if global properties need to be established) if (cheapestForGlobal[i] == null || (cheapestForGlobal[i].getCumulativeCosts().compareTo(candidate.getCumulativeCosts()) > 0)) { cheapestForGlobal[i] = candidate; } final PlanNode[] localMatches; if (toKeep[i] == null) { localMatches = new PlanNode[lps.length]; toKeep[i] = localMatches; } else { localMatches = toKeep[i]; } for (int k = 0; k < lps.length; k++) { if (lps[k].isMetBy(candidate.getLocalProperties())) { final PlanNode previous = localMatches[k]; if (previous == null || previous.getCumulativeCosts().compareTo(candidate.getCumulativeCosts()) > 0) { // this one is cheaper! localMatches[k] = candidate; } } } } } } // all plans are set now plans.clear(); // add the cheapest plan if (cheapest != null) { plans.add(cheapest); cheapest.setPruningMarker(); // remember that that plan is in the set } // skip the top down delta cost check for now (TODO: implement this) // add all others, which are optimal for some interesting properties for (int i = 0; i < gps.length; i++) { if (toKeep[i] != null) { final PlanNode[] localMatches = toKeep[i]; for (int k = 0; k < localMatches.length; k++) { final PlanNode n = localMatches[k]; if (n != null && !n.isPruneMarkerSet()) { n.setPruningMarker(); plans.add(n); } } } if (cheapestForGlobal[i] != null) { final PlanNode n = cheapestForGlobal[i]; if (!n.isPruneMarkerSet()) { n.setPruningMarker(); plans.add(n); } } } } // -------------------------------------------------------------------------------------------- // Handling of branches // -------------------------------------------------------------------------------------------- public boolean hasUnclosedBranches() { return this.openBranches != null && !this.openBranches.isEmpty(); } public List<OptimizerNode> getJoinedBranchers() { return this.hereJoinedBranchers; } public List<UnclosedBranchDescriptor> getOpenBranches() { return this.openBranches; } /** * Checks whether to candidate plans for the sub-plan of this node are comparable. The two * alternative plans are comparable, if * * a) There is no branch in the sub-plan of this node * b) Both candidates have the same candidate as the child at the last open branch. * * @param subPlan1 * @param subPlan2 * @return */ protected boolean areBranchCompatible(PlanNode plan1, PlanNode plan2) { if (plan1 == null || plan2 == null) throw new NullPointerException(); // if there is no open branch, the children are always compatible. // in most plans, that will be the dominant case if (this.hereJoinedBranchers == null || this.hereJoinedBranchers.isEmpty()) { return true; } for (OptimizerNode joinedBrancher : hereJoinedBranchers) { final PlanNode branch1Cand = plan1.getCandidateAtBranchPoint(joinedBrancher); final PlanNode branch2Cand = plan2.getCandidateAtBranchPoint(joinedBrancher); if (branch1Cand != branch2Cand) { return false; } } return true; } /** * @param toParent * @return */ protected List<UnclosedBranchDescriptor> getBranchesForParent(PactConnection toParent) { if (this.outgoingConnections.size() == 1) { // return our own stack of open branches, because nothing is added if (this.openBranches == null || this.openBranches.isEmpty()) return Collections.emptyList(); else return new ArrayList<UnclosedBranchDescriptor>(this.openBranches); } else if (this.outgoingConnections.size() > 1) { // we branch add a branch info to the stack List<UnclosedBranchDescriptor> branches = new ArrayList<UnclosedBranchDescriptor>(4); if (this.openBranches != null) { branches.addAll(this.openBranches); } // find out, which output number the connection to the parent int num; for (num = 0; num < this.outgoingConnections.size(); num++) { if (this.outgoingConnections.get(num) == toParent) { break; } } if (num >= this.outgoingConnections.size()) { throw new CompilerException("Error in compiler: " + "Parent to get branch info for is not contained in the outgoing connections."); } // create the description and add it long bitvector = 0x1L << num; branches.add(new UnclosedBranchDescriptor(this, bitvector)); return branches; } else { throw new CompilerException( "Error in compiler: Cannot get branch info for parent in a node with no parents."); } } protected void removeClosedBranches(List<UnclosedBranchDescriptor> openList) { if (openList == null || openList.isEmpty() || this.closedBranchingNodes == null || this.closedBranchingNodes.isEmpty()) return; Iterator<UnclosedBranchDescriptor> it = openList.iterator(); while (it.hasNext()) { if (this.closedBranchingNodes.contains(it.next().getBranchingNode())) { //this branch was already closed --> remove it from the list it.remove(); } } } protected void addClosedBranches(Set<OptimizerNode> alreadyClosed) { if (alreadyClosed == null || alreadyClosed.isEmpty()) { return; } if (this.closedBranchingNodes == null) { this.closedBranchingNodes = new HashSet<OptimizerNode>(alreadyClosed); } else { this.closedBranchingNodes.addAll(alreadyClosed); } } protected void addClosedBranch(OptimizerNode alreadyClosed) { if (this.closedBranchingNodes == null) { this.closedBranchingNodes = new HashSet<OptimizerNode>(); } this.closedBranchingNodes.add(alreadyClosed); } /** * The node IDs are assigned in graph-traversal order (pre-order), hence, each list is sorted by ID in ascending order and * all consecutive lists start with IDs in ascending order. */ protected final boolean mergeLists(List<UnclosedBranchDescriptor> child1open, List<UnclosedBranchDescriptor> child2open, List<UnclosedBranchDescriptor> result) { //remove branches which have already been closed removeClosedBranches(child1open); removeClosedBranches(child2open); result.clear(); // check how many open branches we have. the cases: // 1) if both are null or empty, the result is null // 2) if one side is null (or empty), the result is the other side. // 3) both are set, then we need to merge. if (child1open == null || child1open.isEmpty()) { - result.addAll(child2open); + if(child2open != null && !child2open.isEmpty()) + result.addAll(child2open); return false; } if (child2open == null || child2open.isEmpty()) { result.addAll(child1open); return false; } int index1 = child1open.size() - 1; int index2 = child2open.size() - 1; boolean didCloseABranch = false; // as both lists (child1open and child2open) are sorted in ascending ID order // we can do a merge-join-like loop which preserved the order in the result list // and eliminates duplicates while (index1 >= 0 || index2 >= 0) { int id1 = -1; int id2 = index2 >= 0 ? child2open.get(index2).getBranchingNode().getId() : -1; while (index1 >= 0 && (id1 = child1open.get(index1).getBranchingNode().getId()) > id2) { result.add(child1open.get(index1)); index1--; } while (index2 >= 0 && (id2 = child2open.get(index2).getBranchingNode().getId()) > id1) { result.add(child2open.get(index2)); index2--; } // match: they share a common branching child if (id1 == id2) { didCloseABranch = true; // if this is the latest common child, remember it OptimizerNode currBanchingNode = child1open.get(index1).getBranchingNode(); long vector1 = child1open.get(index1).getJoinedPathsVector(); long vector2 = child2open.get(index2).getJoinedPathsVector(); // check if this is the same descriptor, (meaning that it contains the same paths) // if it is the same, add it only once, otherwise process the join of the paths if (vector1 == vector2) { result.add(child1open.get(index1)); } else { if (this.hereJoinedBranchers == null) { this.hereJoinedBranchers = new ArrayList<OptimizerNode>(2); } this.hereJoinedBranchers.add(currBanchingNode); // see, if this node closes the branch long joinedInputs = vector1 | vector2; // this is 2^size - 1, which is all bits set at positions 0..size-1 long allInputs = (0x1L << currBanchingNode.getOutgoingConnections().size()) - 1; if (joinedInputs == allInputs) { // closed - we can remove it from the stack addClosedBranch(currBanchingNode); } else { // not quite closed result.add(new UnclosedBranchDescriptor(currBanchingNode, joinedInputs)); } } index1--; index2--; } } // merged. now we need to reverse the list, because we added the elements in reverse order Collections.reverse(result); return didCloseABranch; } /** * */ public static final class UnclosedBranchDescriptor { protected OptimizerNode branchingNode; protected long joinedPathsVector; /** * @param branchingNode * @param joinedPathsVector */ protected UnclosedBranchDescriptor(OptimizerNode branchingNode, long joinedPathsVector) { this.branchingNode = branchingNode; this.joinedPathsVector = joinedPathsVector; } public OptimizerNode getBranchingNode() { return this.branchingNode; } public long getJoinedPathsVector() { return this.joinedPathsVector; } @Override public String toString() { return "(" + this.branchingNode.getPactContract() + ") [" + this.joinedPathsVector + "]"; } } @Override public OptimizerNode getOptimizerNode() { return this; } @Override public PlanNode getPlanNode() { return null; } @Override public Iterator<DumpableConnection<OptimizerNode>> getDumpableInputs() { List<DumpableConnection<OptimizerNode>> allInputs = new ArrayList<DumpableConnection<OptimizerNode>>(); allInputs.addAll(getIncomingConnections()); allInputs.addAll(getBroadcastConnections()); return allInputs.iterator(); } @Override public String toString() { StringBuilder bld = new StringBuilder(); bld.append(getName()); bld.append(" (").append(getPactContract().getName()).append(") "); int i = 1; for (PactConnection conn : getIncomingConnections()) { bld.append('(').append(i++).append(":").append(conn.getShipStrategy() == null ? "null" : conn.getShipStrategy().name()).append(')'); } return bld.toString(); } public int[] getRemappedKeys(int input) { return this.remappedKeys[input]; } } \ No newline at end of file diff --git a/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/plantranslate/NepheleJobGraphGenerator.java b/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/plantranslate/NepheleJobGraphGenerator.java index dd9248a27..5d1e4ee94 100644 --- a/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/plantranslate/NepheleJobGraphGenerator.java +++ b/stratosphere-compiler/src/main/java/eu/stratosphere/compiler/plantranslate/NepheleJobGraphGenerator.java @@ -1,1597 +1,1599 @@ /*********************************************************************************************************************** * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu) * * 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 eu.stratosphere.compiler.plantranslate; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import eu.stratosphere.api.common.aggregators.AggregatorRegistry; import eu.stratosphere.api.common.aggregators.AggregatorWithName; import eu.stratosphere.api.common.aggregators.ConvergenceCriterion; import eu.stratosphere.api.common.aggregators.LongSumAggregator; import eu.stratosphere.api.common.distributions.DataDistribution; import eu.stratosphere.api.common.typeutils.TypeComparatorFactory; import eu.stratosphere.api.common.typeutils.TypeSerializerFactory; import eu.stratosphere.compiler.CompilerException; import eu.stratosphere.compiler.dag.TempMode; import eu.stratosphere.compiler.plan.BulkIterationPlanNode; import eu.stratosphere.compiler.plan.BulkPartialSolutionPlanNode; import eu.stratosphere.compiler.plan.Channel; import eu.stratosphere.compiler.plan.DualInputPlanNode; import eu.stratosphere.compiler.plan.IterationPlanNode; import eu.stratosphere.compiler.plan.NAryUnionPlanNode; import eu.stratosphere.compiler.plan.NamedChannel; import eu.stratosphere.compiler.plan.OptimizedPlan; import eu.stratosphere.compiler.plan.PlanNode; import eu.stratosphere.compiler.plan.SingleInputPlanNode; import eu.stratosphere.compiler.plan.SinkPlanNode; import eu.stratosphere.compiler.plan.SolutionSetPlanNode; import eu.stratosphere.compiler.plan.SourcePlanNode; import eu.stratosphere.compiler.plan.WorksetIterationPlanNode; import eu.stratosphere.compiler.plan.WorksetPlanNode; import eu.stratosphere.configuration.Configuration; import eu.stratosphere.configuration.GlobalConfiguration; import eu.stratosphere.configuration.ConfigConstants; import eu.stratosphere.nephele.io.DistributionPattern; import eu.stratosphere.nephele.io.channels.ChannelType; import eu.stratosphere.nephele.jobgraph.AbstractJobOutputVertex; import eu.stratosphere.nephele.jobgraph.AbstractJobVertex; import eu.stratosphere.nephele.jobgraph.JobGraph; import eu.stratosphere.nephele.jobgraph.JobGraphDefinitionException; import eu.stratosphere.nephele.jobgraph.JobInputVertex; import eu.stratosphere.nephele.jobgraph.JobOutputVertex; import eu.stratosphere.nephele.jobgraph.JobTaskVertex; import eu.stratosphere.nephele.template.AbstractInputTask; import eu.stratosphere.pact.runtime.iterative.convergence.WorksetEmptyConvergenceCriterion; import eu.stratosphere.pact.runtime.iterative.io.FakeOutputTask; import eu.stratosphere.pact.runtime.iterative.task.IterationHeadPactTask; import eu.stratosphere.pact.runtime.iterative.task.IterationIntermediatePactTask; import eu.stratosphere.pact.runtime.iterative.task.IterationSynchronizationSinkTask; import eu.stratosphere.pact.runtime.iterative.task.IterationTailPactTask; import eu.stratosphere.pact.runtime.shipping.ShipStrategyType; import eu.stratosphere.pact.runtime.task.CoGroupDriver; import eu.stratosphere.pact.runtime.task.DataSinkTask; import eu.stratosphere.pact.runtime.task.DataSourceTask; import eu.stratosphere.pact.runtime.task.DriverStrategy; import eu.stratosphere.pact.runtime.task.JoinWithSolutionSetCoGroupDriver.SolutionSetFirstCoGroupDriver; import eu.stratosphere.pact.runtime.task.JoinWithSolutionSetCoGroupDriver.SolutionSetSecondCoGroupDriver; import eu.stratosphere.pact.runtime.task.JoinWithSolutionSetMatchDriver.SolutionSetFirstJoinDriver; import eu.stratosphere.pact.runtime.task.JoinWithSolutionSetMatchDriver.SolutionSetSecondJoinDriver; import eu.stratosphere.pact.runtime.task.MatchDriver; import eu.stratosphere.pact.runtime.task.NoOpDriver; import eu.stratosphere.pact.runtime.task.RegularPactTask; import eu.stratosphere.pact.runtime.task.chaining.ChainedDriver; import eu.stratosphere.pact.runtime.task.util.LocalStrategy; import eu.stratosphere.pact.runtime.task.util.TaskConfig; import eu.stratosphere.util.Visitor; /** * This component translates the optimizer's resulting plan a nephele job graph. The * translation is a one to one mapping. All decisions are made by the optimizer, this class * simply creates nephele data structures and descriptions corresponding to the optimizer's * result. * <p> * The basic method of operation is a top down traversal over the plan graph. On the way down, tasks are created * for the plan nodes, on the way back up, the nodes connect their predecessor. */ public class NepheleJobGraphGenerator implements Visitor<PlanNode> { public static final String MERGE_ITERATION_AUX_TASKS_KEY = "pact.compiler.merge-iteration-aux"; private static final boolean mergeIterationAuxTasks = GlobalConfiguration.getBoolean( MERGE_ITERATION_AUX_TASKS_KEY, true); private static final Log LOG = LogFactory.getLog(NepheleJobGraphGenerator.class); // ------------------------------------------------------------------------ private JobGraph jobGraph; // the job that is currently built private Map<PlanNode, AbstractJobVertex> vertices; // a map from optimizer nodes to nephele vertices private Map<PlanNode, TaskInChain> chainedTasks; // a map from optimizer nodes to nephele vertices private Map<IterationPlanNode, IterationDescriptor> iterations; private List<TaskInChain> chainedTasksInSequence; private List<AbstractJobVertex> auxVertices; // auxiliary vertices which are added during job graph generation private AbstractJobVertex maxDegreeVertex; // the vertex with the highest degree of parallelism private final int defaultMaxFan; private final float defaultSortSpillingThreshold; private int iterationIdEnumerator = 1; private IterationPlanNode currentIteration; // hack: as long as no nesting is possible, remember the enclosing iteration // ------------------------------------------------------------------------ /** * Creates a new job graph generator that uses the default values for its resource configuration. */ public NepheleJobGraphGenerator() { this.defaultMaxFan = ConfigConstants.DEFAULT_SPILLING_MAX_FAN; this.defaultSortSpillingThreshold = ConfigConstants.DEFAULT_SORT_SPILLING_THRESHOLD; } public NepheleJobGraphGenerator(Configuration config) { this.defaultMaxFan = config.getInteger(ConfigConstants.DEFAULT_SPILLING_MAX_FAN_KEY, ConfigConstants.DEFAULT_SPILLING_MAX_FAN); this.defaultSortSpillingThreshold = config.getFloat(ConfigConstants.DEFAULT_SORT_SPILLING_THRESHOLD_KEY, ConfigConstants.DEFAULT_SORT_SPILLING_THRESHOLD); } /** * Translates a {@link eu.stratosphere.compiler.plan.OptimizedPlan} into a * {@link eu.stratosphere.nephele.jobgraph.JobGraph}. * This is an 1-to-1 mapping. No optimization whatsoever is applied. * * @param program * Optimized PACT plan that is translated into a JobGraph. * @return JobGraph generated from PACT plan. */ public JobGraph compileJobGraph(OptimizedPlan program) { this.jobGraph = new JobGraph(program.getJobName()); this.vertices = new HashMap<PlanNode, AbstractJobVertex>(); this.chainedTasks = new HashMap<PlanNode, TaskInChain>(); this.chainedTasksInSequence = new ArrayList<TaskInChain>(); this.auxVertices = new ArrayList<AbstractJobVertex>(); this.iterations = new HashMap<IterationPlanNode, IterationDescriptor>(); this.maxDegreeVertex = null; // generate Nephele job graph program.accept(this); // finalize the iterations for (IterationDescriptor iteration : this.iterations.values()) { if (iteration.getIterationNode() instanceof BulkIterationPlanNode) { finalizeBulkIteration(iteration); } else if (iteration.getIterationNode() instanceof WorksetIterationPlanNode) { finalizeWorksetIteration(iteration); } else { throw new CompilerException(); } } // now that the traversal is done, we have the chained tasks write their configs into their // parents' configurations for (int i = 0; i < this.chainedTasksInSequence.size(); i++) { TaskInChain tic = this.chainedTasksInSequence.get(i); TaskConfig t = new TaskConfig(tic.getContainingVertex().getConfiguration()); t.addChainedTask(tic.getChainedTask(), tic.getTaskConfig(), tic.getTaskName()); } // now that all have been created, make sure that all share their instances with the one // with the highest degree of parallelism if (program.getInstanceTypeName() != null) { this.maxDegreeVertex.setInstanceType(program.getInstanceTypeName()); } else { LOG.warn("No instance type assigned to JobVertex."); } for (AbstractJobVertex vertex : this.vertices.values()) { if (vertex != this.maxDegreeVertex) { vertex.setVertexToShareInstancesWith(this.maxDegreeVertex); } } for (AbstractJobVertex vertex : this.auxVertices) { if (vertex != this.maxDegreeVertex) { vertex.setVertexToShareInstancesWith(this.maxDegreeVertex); } } JobGraph graph = this.jobGraph; // release all references again this.maxDegreeVertex = null; this.vertices = null; this.chainedTasks = null; this.chainedTasksInSequence = null; this.auxVertices = null; this.iterations = null; this.jobGraph = null; // return job graph return graph; } /** * This methods implements the pre-visiting during a depth-first traversal. It create the job vertex and * sets local strategy. * * @param node * The node that is currently processed. * @return True, if the visitor should descend to the node's children, false if not. * @see eu.stratosphere.util.Visitor#preVisit(eu.stratosphere.pact.common.plan.Visitable) */ @Override public boolean preVisit(PlanNode node) { // check if we have visited this node before. in non-tree graphs, this happens if (this.vertices.containsKey(node) || this.chainedTasks.containsKey(node) || this.iterations.containsKey(node)) { // return false to prevent further descend return false; } // the vertex to be created for the current node final AbstractJobVertex vertex; try { if (node instanceof SinkPlanNode) { vertex = createDataSinkVertex((SinkPlanNode) node); } else if (node instanceof SourcePlanNode) { vertex = createDataSourceVertex((SourcePlanNode) node); } else if (node instanceof BulkIterationPlanNode) { BulkIterationPlanNode iterationNode = (BulkIterationPlanNode) node; // for the bulk iteration, we skip creating anything for now. we create the graph // for the step function in the post visit. // check that the root of the step function has the same DOP as the iteration. // because the tail must have the same DOP as the head, we can only merge the last // operator with the tail, if they have the same DOP. not merging is currently not // implemented PlanNode root = iterationNode.getRootOfStepFunction(); if (root.getDegreeOfParallelism() != node.getDegreeOfParallelism() || root.getSubtasksPerInstance() != node.getSubtasksPerInstance()) { throw new CompilerException("Error: The final operator of the step " + "function has a different degree of parallelism than the iteration operator itself."); } IterationDescriptor descr = new IterationDescriptor(iterationNode, this.iterationIdEnumerator++); this.iterations.put(iterationNode, descr); vertex = null; } else if (node instanceof WorksetIterationPlanNode) { WorksetIterationPlanNode iterationNode = (WorksetIterationPlanNode) node; // we have the same constraints as for the bulk iteration PlanNode nextWorkSet = iterationNode.getNextWorkSetPlanNode(); PlanNode solutionSetDelta = iterationNode.getSolutionSetDeltaPlanNode(); if (nextWorkSet.getDegreeOfParallelism() != node.getDegreeOfParallelism() || nextWorkSet.getSubtasksPerInstance() != node.getSubtasksPerInstance()) { throw new CompilerException("It is currently not supported that the final operator of the step " + "function has a different degree of parallelism than the iteration operator itself."); } if (solutionSetDelta.getDegreeOfParallelism() != node.getDegreeOfParallelism() || solutionSetDelta.getSubtasksPerInstance() != node.getSubtasksPerInstance()) { throw new CompilerException("It is currently not supported that the final operator of the step " + "function has a different degree of parallelism than the iteration operator itself."); } IterationDescriptor descr = new IterationDescriptor(iterationNode, this.iterationIdEnumerator++); this.iterations.put(iterationNode, descr); vertex = null; } else if (node instanceof SingleInputPlanNode) { vertex = createSingleInputVertex((SingleInputPlanNode) node); } else if (node instanceof DualInputPlanNode) { vertex = createDualInputVertex((DualInputPlanNode) node); } else if (node instanceof NAryUnionPlanNode) { // skip the union for now vertex = null; } else if (node instanceof BulkPartialSolutionPlanNode) { // create a head node (or not, if it is merged into its successor) vertex = createBulkIterationHead((BulkPartialSolutionPlanNode) node); } else if (node instanceof SolutionSetPlanNode) { // skip the solution set place holder. we create the head at the workset place holder vertex = null; } else if (node instanceof WorksetPlanNode) { // create the iteration head here vertex = createWorksetIterationHead((WorksetPlanNode) node); } else { throw new CompilerException("Unrecognized node type: " + node.getClass().getName()); } } catch (Exception e) { throw new CompilerException("Error translating node '" + node + "': " + e.getMessage(), e); } // check if a vertex was created, or if it was chained or skipped if (vertex != null) { // set degree of parallelism int pd = node.getDegreeOfParallelism(); vertex.setNumberOfSubtasks(pd); // check whether this is the vertex with the highest degree of parallelism if (this.maxDegreeVertex == null || this.maxDegreeVertex.getNumberOfSubtasks() < pd) { this.maxDegreeVertex = vertex; } // set the number of tasks per instance if (node.getSubtasksPerInstance() >= 1) { vertex.setNumberOfSubtasksPerInstance(node.getSubtasksPerInstance()); } // check whether this vertex is part of an iteration step function if (this.currentIteration != null) { // check that the task has the same DOP as the iteration as such PlanNode iterationNode = (PlanNode) this.currentIteration; if (iterationNode.getDegreeOfParallelism() < pd) { throw new CompilerException("Error: All functions that are part of an iteration must have the same, or a lower, degree-of-parallelism than the iteration operator."); } if (iterationNode.getSubtasksPerInstance() < node.getSubtasksPerInstance()) { throw new CompilerException("Error: All functions that are part of an iteration must have the same, or a lower, number of subtasks-per-node than the iteration operator."); } // store the id of the iterations the step functions participate in IterationDescriptor descr = this.iterations.get(this.currentIteration); new TaskConfig(vertex.getConfiguration()).setIterationId(descr.getId()); } // store in the map this.vertices.put(node, vertex); } // returning true causes deeper descend return true; } /** * This method implements the post-visit during the depth-first traversal. When the post visit happens, * all of the descendants have been processed, so this method connects all of the current node's * predecessors to the current node. * * @param node * The node currently processed during the post-visit. * @see eu.stratosphere.util.Visitor#postVisit(eu.stratosphere.pact.common.plan.Visitable) */ @Override public void postVisit(PlanNode node) { try { // --------- check special cases for which we handle post visit differently ---------- // skip data source node (they have no inputs) // also, do nothing for union nodes, we connect them later when gathering the inputs for a task // solution sets have no input. the initial solution set input is connected when the iteration node is in its postVisit if (node instanceof SourcePlanNode || node instanceof NAryUnionPlanNode) { return; } // check if we have an iteration. in that case, translate the step function now if (node instanceof IterationPlanNode) { // for now, prevent nested iterations if (this.currentIteration != null) { throw new CompilerException("Nested Iterations are not possible at the moment!"); } this.currentIteration = (IterationPlanNode) node; this.currentIteration.acceptForStepFunction(this); this.currentIteration = null; // inputs for initial bulk partial solution or initial workset are already connected to the iteration head in the head's post visit. // connect the initial solution set now. if (node instanceof WorksetIterationPlanNode) { // connect the initial solution set WorksetIterationPlanNode wsNode = (WorksetIterationPlanNode) node; AbstractJobVertex headVertex = this.iterations.get(wsNode).getHeadTask(); TaskConfig headConfig = new TaskConfig(headVertex.getConfiguration()); int inputIndex = headConfig.getDriverStrategy().getNumInputs(); headConfig.setIterationHeadSolutionSetInputIndex(inputIndex); translateChannel(wsNode.getInitialSolutionSetInput(), inputIndex, headVertex, headConfig, false); } return; } else if (node instanceof SolutionSetPlanNode) { // this represents an access into the solution set index. // add the necessary information to all nodes that access the index if (node.getOutgoingChannels().size() != 1) { throw new CompilerException("Currently, only one join with the solution set is allowed."); } Channel c = node.getOutgoingChannels().get(0); DualInputPlanNode target = (DualInputPlanNode) c.getTarget(); AbstractJobVertex accessingVertex = this.vertices.get(target); TaskConfig conf = new TaskConfig(accessingVertex.getConfiguration()); int inputNum = c == target.getInput1() ? 0 : c == target.getInput2() ? 1 : -1; // sanity checks if (inputNum == -1) { throw new CompilerException(); } // adjust the driver if (conf.getDriver().equals(MatchDriver.class)) { conf.setDriver(inputNum == 0 ? SolutionSetFirstJoinDriver.class : SolutionSetSecondJoinDriver.class); } else if (conf.getDriver().equals(CoGroupDriver.class)) { conf.setDriver(inputNum == 0 ? SolutionSetFirstCoGroupDriver.class : SolutionSetSecondCoGroupDriver.class); } else { throw new CompilerException("Found join with solution set using incompatible operator (only Join/CoGroup are valid."); } // set the serializer / comparator information conf.setSolutionSetSerializer(((SolutionSetPlanNode) node).getContainingIterationNode().getSolutionSetSerializer()); // hack: for now, we need the prober in the workset iteration head task IterationDescriptor iter = this.iterations.get(((SolutionSetPlanNode) node).getContainingIterationNode()); TaskConfig headConf = iter.getHeadConfig(); TypeSerializerFactory<?> otherSerializer; TypeComparatorFactory<?> otherComparator; if (inputNum == 0) { otherSerializer = target.getInput2().getSerializer(); otherComparator = target.getComparator2(); } else { otherSerializer = target.getInput1().getSerializer(); otherComparator = target.getComparator1(); } headConf.setSolutionSetProberSerializer(otherSerializer); headConf.setSolutionSetProberComparator(otherComparator); headConf.setSolutionSetPairComparator(target.getPairComparator()); return; } // --------- Main Path: Translation of channels ---------- // // There are two paths of translation: One for chained tasks (or merged tasks in general), // which do not have their own task vertex. The other for tasks that have their own vertex, // or are the primary task in a vertex (to which the others are chained). final AbstractJobVertex targetVertex = this.vertices.get(node); // check whether this node has its own task, or is merged with another one if (targetVertex == null) { // node's task is merged with another task. it is either chained, of a merged head vertex // from an iteration final TaskInChain chainedTask; if ((chainedTask = this.chainedTasks.get(node)) != null) { // Chained Task. Sanity check first... final Iterator<Channel> inConns = node.getInputs(); if (!inConns.hasNext()) { throw new CompilerException("Bug: Found chained task with no input."); } final Channel inConn = inConns.next(); if (inConns.hasNext()) { throw new CompilerException("Bug: Found a chained task with more than one input!"); } if (inConn.getLocalStrategy() != null && inConn.getLocalStrategy() != LocalStrategy.NONE) { throw new CompilerException("Bug: Found a chained task with an input local strategy."); } if (inConn.getShipStrategy() != null && inConn.getShipStrategy() != ShipStrategyType.FORWARD) { throw new CompilerException("Bug: Found a chained task with an input ship strategy other than FORWARD."); } AbstractJobVertex container = chainedTask.getContainingVertex(); if (container == null) { final PlanNode sourceNode = inConn.getSource(); container = this.vertices.get(sourceNode); if (container == null) { // predecessor is itself chained container = this.chainedTasks.get(sourceNode).getContainingVertex(); if (container == null) throw new IllegalStateException("Bug: Chained task predecessor has not been assigned its containing vertex."); } else { // predecessor is a proper task job vertex and this is the first chained task. add a forward connection entry. new TaskConfig(container.getConfiguration()).addOutputShipStrategy(ShipStrategyType.FORWARD); } chainedTask.setContainingVertex(container); } // add info about the input serializer type chainedTask.getTaskConfig().setInputSerializer(inConn.getSerializer(), 0); // update name of container task String containerTaskName = container.getName(); if(containerTaskName.startsWith("CHAIN ")) { container.setName(containerTaskName+" -> "+chainedTask.getTaskName()); } else { container.setName("CHAIN "+containerTaskName+" -> "+chainedTask.getTaskName()); } this.chainedTasksInSequence.add(chainedTask); return; } else if (node instanceof BulkPartialSolutionPlanNode || node instanceof WorksetPlanNode) { // merged iteration head task. the task that the head is merged with will take care of it return; } else { throw new CompilerException("Bug: Unrecognized merged task vertex."); } } // -------- Here, we translate non-chained tasks ------------- // create the config that will contain all the description of the inputs final TaskConfig targetVertexConfig = new TaskConfig(targetVertex.getConfiguration()); // get the inputs. if this node is the head of an iteration, we obtain the inputs from the // enclosing iteration node, because the inputs are the initial inputs to the iteration. final Iterator<Channel> inConns; if (node instanceof BulkPartialSolutionPlanNode) { inConns = ((BulkPartialSolutionPlanNode) node).getContainingIterationNode().getInputs(); // because the partial solution has its own vertex, is has only one (logical) input. // note this in the task configuration targetVertexConfig.setIterationHeadPartialSolutionOrWorksetInputIndex(0); } else if (node instanceof WorksetPlanNode) { WorksetPlanNode wspn = (WorksetPlanNode) node; // input that is the initial workset inConns = Collections.singleton(wspn.getContainingIterationNode().getInput2()).iterator(); // because we have a stand-alone (non-merged) workset iteration head, the initial workset will // be input 0 and the solution set will be input 1 targetVertexConfig.setIterationHeadPartialSolutionOrWorksetInputIndex(0); targetVertexConfig.setIterationHeadSolutionSetInputIndex(1); } else { inConns = node.getInputs(); } if (!inConns.hasNext()) { throw new CompilerException("Bug: Found a non-source task with no input."); } int inputIndex = 0; while (inConns.hasNext()) { Channel input = inConns.next(); inputIndex += translateChannel(input, inputIndex, targetVertex, targetVertexConfig, false); } // broadcast variables int broadcastInputIndex = 0; for (NamedChannel broadcastInput: node.getBroadcastInputs()) { int broadcastInputIndexDelta = translateChannel(broadcastInput, broadcastInputIndex, targetVertex, targetVertexConfig, true); targetVertexConfig.setBroadcastInputName(broadcastInput.getName(), broadcastInputIndex); targetVertexConfig.setBroadcastInputSerializer(broadcastInput.getSerializer(), broadcastInputIndex); broadcastInputIndex += broadcastInputIndexDelta; } } catch (Exception e) { throw new CompilerException( "An error occurred while translating the optimized plan to a nephele JobGraph: " + e.getMessage(), e); } } private int translateChannel(Channel input, int inputIndex, AbstractJobVertex targetVertex, TaskConfig targetVertexConfig, boolean isBroadcast) throws Exception { final PlanNode inputPlanNode = input.getSource(); final Iterator<Channel> allInChannels; if (inputPlanNode instanceof NAryUnionPlanNode) { allInChannels = ((NAryUnionPlanNode) inputPlanNode).getListOfInputs().iterator(); } else if (inputPlanNode instanceof BulkPartialSolutionPlanNode) { if (this.vertices.get(inputPlanNode) == null) { // merged iteration head final BulkPartialSolutionPlanNode pspn = (BulkPartialSolutionPlanNode) inputPlanNode; final BulkIterationPlanNode iterationNode = pspn.getContainingIterationNode(); // check if the iteration's input is a union if (iterationNode.getInput().getSource() instanceof NAryUnionPlanNode) { allInChannels = ((NAryUnionPlanNode) iterationNode.getInput().getSource()).getInputs(); } else { allInChannels = Collections.singletonList(iterationNode.getInput()).iterator(); } // also, set the index of the gate with the partial solution targetVertexConfig.setIterationHeadPartialSolutionOrWorksetInputIndex(inputIndex); } else { // standalone iteration head allInChannels = Collections.singletonList(input).iterator(); } } else if (inputPlanNode instanceof WorksetPlanNode) { if (this.vertices.get(inputPlanNode) == null) { // merged iteration head final WorksetPlanNode wspn = (WorksetPlanNode) inputPlanNode; final WorksetIterationPlanNode iterationNode = wspn.getContainingIterationNode(); // check if the iteration's input is a union if (iterationNode.getInput2().getSource() instanceof NAryUnionPlanNode) { allInChannels = ((NAryUnionPlanNode) iterationNode.getInput2().getSource()).getInputs(); } else { allInChannels = Collections.singletonList(iterationNode.getInput2()).iterator(); } // also, set the index of the gate with the partial solution targetVertexConfig.setIterationHeadPartialSolutionOrWorksetInputIndex(inputIndex); } else { // standalone iteration head allInChannels = Collections.singletonList(input).iterator(); } } else if (inputPlanNode instanceof SolutionSetPlanNode) { // for now, skip connections with the solution set node, as this is a local index access (later to be parameterized here) // rather than a vertex connection return 0; } else { allInChannels = Collections.singletonList(input).iterator(); } // check that the type serializer is consistent TypeSerializerFactory<?> typeSerFact = null; // accounting for channels on the dynamic path int numChannelsTotal = 0; int numChannelsDynamicPath = 0; int numDynamicSenderTasksTotal = 0; // expand the channel to all the union channels, in case there is a union operator at its source while (allInChannels.hasNext()) { final Channel inConn = allInChannels.next(); // sanity check the common serializer if (typeSerFact == null) { typeSerFact = inConn.getSerializer(); } else if (!typeSerFact.equals(inConn.getSerializer())) { throw new CompilerException("Conflicting types in union operator."); } final PlanNode sourceNode = inConn.getSource(); AbstractJobVertex sourceVertex = this.vertices.get(sourceNode); TaskConfig sourceVertexConfig; if (sourceVertex == null) { // this predecessor is chained to another task or an iteration final TaskInChain chainedTask; final IterationDescriptor iteration; if ((chainedTask = this.chainedTasks.get(sourceNode)) != null) { // push chained task if (chainedTask.getContainingVertex() == null) throw new IllegalStateException("Bug: Chained task has not been assigned its containing vertex when connecting."); sourceVertex = chainedTask.getContainingVertex(); sourceVertexConfig = chainedTask.getTaskConfig(); } else if ((iteration = this.iterations.get(sourceNode)) != null) { // predecessor is an iteration sourceVertex = iteration.getHeadTask(); sourceVertexConfig = iteration.getHeadFinalResultConfig(); } else { throw new CompilerException("Bug: Could not resolve source node for a channel."); } } else { // predecessor is its own vertex sourceVertexConfig = new TaskConfig(sourceVertex.getConfiguration()); } DistributionPattern pattern = connectJobVertices( inConn, inputIndex, sourceVertex, sourceVertexConfig, targetVertex, targetVertexConfig, isBroadcast); // accounting on channels and senders numChannelsTotal++; if (inConn.isOnDynamicPath()) { numChannelsDynamicPath++; numDynamicSenderTasksTotal += getNumberOfSendersPerReceiver(pattern, sourceVertex.getNumberOfSubtasks(), targetVertex.getNumberOfSubtasks()); } } // for the iterations, check that the number of dynamic channels is the same as the number // of channels for this logical input. this condition is violated at the moment, if there // is a union between nodes on the static and nodes on the dynamic path if (numChannelsDynamicPath > 0 && numChannelsTotal != numChannelsDynamicPath) { throw new CompilerException("Error: It is currently not supported to union between dynamic and static path in an iteration."); } if (numDynamicSenderTasksTotal > 0) { if (isBroadcast) { targetVertexConfig.setBroadcastGateIterativeWithNumberOfEventsUntilInterrupt(inputIndex, numDynamicSenderTasksTotal); } else { targetVertexConfig.setGateIterativeWithNumberOfEventsUntilInterrupt(inputIndex, numDynamicSenderTasksTotal); } } // the local strategy is added only once. in non-union case that is the actual edge, // in the union case, it is the edge between union and the target node addLocalInfoFromChannelToConfig(input, targetVertexConfig, inputIndex, isBroadcast); return 1; } private int getNumberOfSendersPerReceiver(DistributionPattern pattern, int numSenders, int numReceivers) { if (pattern == DistributionPattern.BIPARTITE) { return numSenders; } else if (pattern == DistributionPattern.POINTWISE) { if (numSenders != numReceivers) { if (numReceivers == 1) { return numSenders; } else if (numSenders == 1) { return 1; } else { throw new CompilerException("Error: A changing degree of parallelism is currently " + "not supported between tasks within an iteration."); } } else { return 1; } } else { throw new CompilerException("Unknown distribution pattern for channels: " + pattern); } } // ------------------------------------------------------------------------ // Methods for creating individual vertices // ------------------------------------------------------------------------ private JobTaskVertex createSingleInputVertex(SingleInputPlanNode node) throws CompilerException { final String taskName = node.getNodeName(); final DriverStrategy ds = node.getDriverStrategy(); // check, whether chaining is possible boolean chaining = false; { Channel inConn = node.getInput(); PlanNode pred = inConn.getSource(); chaining = ds.getPushChainDriverClass() != null && !(pred instanceof NAryUnionPlanNode) && // first op after union is stand-alone, because union is merged !(pred instanceof BulkPartialSolutionPlanNode) && // partial solution merges anyways !(pred instanceof IterationPlanNode) && // cannot chain with iteration heads currently inConn.getShipStrategy() == ShipStrategyType.FORWARD && inConn.getLocalStrategy() == LocalStrategy.NONE && pred.getOutgoingChannels().size() == 1 && node.getDegreeOfParallelism() == pred.getDegreeOfParallelism() && node.getSubtasksPerInstance() == pred.getSubtasksPerInstance() && node.getBroadcastInputs().isEmpty(); // cannot chain the nodes that produce the next workset or the next solution set, if they are not the // in a tail if (this.currentIteration != null && this.currentIteration instanceof WorksetIterationPlanNode && node.getOutgoingChannels().size() > 0) { WorksetIterationPlanNode wspn = (WorksetIterationPlanNode) this.currentIteration; if (wspn.getSolutionSetDeltaPlanNode() == pred || wspn.getNextWorkSetPlanNode() == pred) { chaining = false; } } // cannot chain the nodes that produce the next workset in a bulk iteration if a termination criterion follows - if (this.currentIteration != null && this.currentIteration instanceof BulkIterationPlanNode && - node.getOutgoingChannels().size() > 0) + if (this.currentIteration != null && this.currentIteration instanceof BulkIterationPlanNode) { BulkIterationPlanNode wspn = (BulkIterationPlanNode) this.currentIteration; - if (wspn.getRootOfStepFunction() == pred || wspn.getRootOfTerminationCriterion() == pred) { + if(node == wspn.getRootOfTerminationCriterion() && wspn.getRootOfStepFunction() == pred){ + chaining = false; + }else if(node.getOutgoingChannels().size() > 0 &&(wspn.getRootOfStepFunction() == pred || + wspn.getRootOfTerminationCriterion() == pred)) { chaining = false; } } } final JobTaskVertex vertex; final TaskConfig config; if (chaining) { vertex = null; config = new TaskConfig(new Configuration()); this.chainedTasks.put(node, new TaskInChain(ds.getPushChainDriverClass(), config, taskName)); } else { // create task vertex vertex = new JobTaskVertex(taskName, this.jobGraph); vertex.setTaskClass( (this.currentIteration != null && node.isOnDynamicPath()) ? IterationIntermediatePactTask.class : RegularPactTask.class); config = new TaskConfig(vertex.getConfiguration()); config.setDriver(ds.getDriverClass()); } // set user code config.setStubWrapper(node.getPactContract().getUserCodeWrapper()); config.setStubParameters(node.getPactContract().getParameters()); // set the driver strategy config.setDriverStrategy(ds); if (node.getComparator() != null) { config.setDriverComparator(node.getComparator(), 0); } // assign memory, file-handles, etc. assignDriverResources(node, config); return vertex; } private JobTaskVertex createDualInputVertex(DualInputPlanNode node) throws CompilerException { final String taskName = node.getNodeName(); final DriverStrategy ds = node.getDriverStrategy(); final JobTaskVertex vertex = new JobTaskVertex(taskName, this.jobGraph); final TaskConfig config = new TaskConfig(vertex.getConfiguration()); vertex.setTaskClass( (this.currentIteration != null && node.isOnDynamicPath()) ? IterationIntermediatePactTask.class : RegularPactTask.class); // set user code config.setStubWrapper(node.getPactContract().getUserCodeWrapper()); config.setStubParameters(node.getPactContract().getParameters()); // set the driver strategy config.setDriver(ds.getDriverClass()); config.setDriverStrategy(ds); if (node.getComparator1() != null) { config.setDriverComparator(node.getComparator1(), 0); } if (node.getComparator2() != null) { config.setDriverComparator(node.getComparator2(), 1); } if (node.getPairComparator() != null) { config.setDriverPairComparator(node.getPairComparator()); } // assign memory, file-handles, etc. assignDriverResources(node, config); return vertex; } private JobInputVertex createDataSourceVertex(SourcePlanNode node) throws CompilerException { final JobInputVertex vertex = new JobInputVertex(node.getNodeName(), this.jobGraph); final TaskConfig config = new TaskConfig(vertex.getConfiguration()); // set task class @SuppressWarnings("unchecked") final Class<AbstractInputTask<?>> clazz = (Class<AbstractInputTask<?>>) (Class<?>) DataSourceTask.class; vertex.setInputClass(clazz); // set user code config.setStubWrapper(node.getPactContract().getUserCodeWrapper()); config.setStubParameters(node.getPactContract().getParameters()); config.setOutputSerializer(node.getSerializer()); return vertex; } private AbstractJobOutputVertex createDataSinkVertex(SinkPlanNode node) throws CompilerException { final JobOutputVertex vertex = new JobOutputVertex(node.getNodeName(), this.jobGraph); final TaskConfig config = new TaskConfig(vertex.getConfiguration()); vertex.setOutputClass(DataSinkTask.class); vertex.getConfiguration().setInteger(DataSinkTask.DEGREE_OF_PARALLELISM_KEY, node.getDegreeOfParallelism()); // set user code config.setStubWrapper(node.getPactContract().getUserCodeWrapper()); config.setStubParameters(node.getPactContract().getParameters()); return vertex; } private JobTaskVertex createBulkIterationHead(BulkPartialSolutionPlanNode pspn) { // get the bulk iteration that corresponds to this partial solution node final BulkIterationPlanNode iteration = pspn.getContainingIterationNode(); // check whether we need an individual vertex for the partial solution, or whether we // attach ourselves to the vertex of the parent node. We can combine the head with a node of // the step function, if // 1) There is one parent that the partial solution connects to via a forward pattern and no // local strategy // 2) DOP and the number of subtasks per instance does not change // 3) That successor is not a union // 4) That successor is not itself the last node of the step function // 5) There is no local strategy on the edge for the initial partial solution, as // this translates to a local strategy that would only be executed in the first iteration final boolean merge; if (mergeIterationAuxTasks && pspn.getOutgoingChannels().size() == 1) { final Channel c = pspn.getOutgoingChannels().get(0); final PlanNode successor = c.getTarget(); merge = c.getShipStrategy() == ShipStrategyType.FORWARD && c.getLocalStrategy() == LocalStrategy.NONE && c.getTempMode() == TempMode.NONE && successor.getDegreeOfParallelism() == pspn.getDegreeOfParallelism() && successor.getSubtasksPerInstance() == pspn.getSubtasksPerInstance() && !(successor instanceof NAryUnionPlanNode) && successor != iteration.getRootOfStepFunction() && iteration.getInput().getLocalStrategy() == LocalStrategy.NONE; } else { merge = false; } // create or adopt the head vertex final JobTaskVertex toReturn; final JobTaskVertex headVertex; final TaskConfig headConfig; if (merge) { final PlanNode successor = pspn.getOutgoingChannels().get(0).getTarget(); headVertex = (JobTaskVertex) this.vertices.get(successor); if (headVertex == null) { throw new CompilerException( "Bug: Trying to merge solution set with its sucessor, but successor has not been created."); } // reset the vertex type to iteration head headVertex.setTaskClass(IterationHeadPactTask.class); headConfig = new TaskConfig(headVertex.getConfiguration()); toReturn = null; } else { // instantiate the head vertex and give it a no-op driver as the driver strategy. // everything else happens in the post visit, after the input (the initial partial solution) // is connected. headVertex = new JobTaskVertex("PartialSolution ("+iteration.getNodeName()+")", this.jobGraph); headVertex.setTaskClass(IterationHeadPactTask.class); headConfig = new TaskConfig(headVertex.getConfiguration()); headConfig.setDriver(NoOpDriver.class); toReturn = headVertex; } // create the iteration descriptor and the iteration to it IterationDescriptor descr = this.iterations.get(iteration); if (descr == null) { throw new CompilerException("Bug: Iteration descriptor was not created at when translating the iteration node."); } descr.setHeadTask(headVertex, headConfig); return toReturn; } private JobTaskVertex createWorksetIterationHead(WorksetPlanNode wspn) { // get the bulk iteration that corresponds to this partial solution node final WorksetIterationPlanNode iteration = wspn.getContainingIterationNode(); // check whether we need an individual vertex for the partial solution, or whether we // attach ourselves to the vertex of the parent node. We can combine the head with a node of // the step function, if // 1) There is one parent that the partial solution connects to via a forward pattern and no // local strategy // 2) DOP and the number of subtasks per instance does not change // 3) That successor is not a union // 4) That successor is not itself the last node of the step function // 5) There is no local strategy on the edge for the initial workset, as // this translates to a local strategy that would only be executed in the first superstep final boolean merge; if (mergeIterationAuxTasks && wspn.getOutgoingChannels().size() == 1) { final Channel c = wspn.getOutgoingChannels().get(0); final PlanNode successor = c.getTarget(); merge = c.getShipStrategy() == ShipStrategyType.FORWARD && c.getLocalStrategy() == LocalStrategy.NONE && c.getTempMode() == TempMode.NONE && successor.getDegreeOfParallelism() == wspn.getDegreeOfParallelism() && successor.getSubtasksPerInstance() == wspn.getSubtasksPerInstance() && !(successor instanceof NAryUnionPlanNode) && successor != iteration.getNextWorkSetPlanNode() && iteration.getInitialWorksetInput().getLocalStrategy() == LocalStrategy.NONE; } else { merge = false; } // create or adopt the head vertex final JobTaskVertex toReturn; final JobTaskVertex headVertex; final TaskConfig headConfig; if (merge) { final PlanNode successor = wspn.getOutgoingChannels().get(0).getTarget(); headVertex = (JobTaskVertex) this.vertices.get(successor); if (headVertex == null) { throw new CompilerException( "Bug: Trying to merge solution set with its sucessor, but successor has not been created."); } // reset the vertex type to iteration head headVertex.setTaskClass(IterationHeadPactTask.class); headConfig = new TaskConfig(headVertex.getConfiguration()); toReturn = null; } else { // instantiate the head vertex and give it a no-op driver as the driver strategy. // everything else happens in the post visit, after the input (the initial partial solution) // is connected. headVertex = new JobTaskVertex("IterationHead("+iteration.getNodeName()+")", this.jobGraph); headVertex.setTaskClass(IterationHeadPactTask.class); headConfig = new TaskConfig(headVertex.getConfiguration()); headConfig.setDriver(NoOpDriver.class); toReturn = headVertex; } // create the iteration descriptor and the iteration to it IterationDescriptor descr = this.iterations.get(iteration); if (descr == null) { throw new CompilerException("Bug: Iteration descriptor was not created at when translating the iteration node."); } descr.setHeadTask(headVertex, headConfig); return toReturn; } private void assignDriverResources(PlanNode node, TaskConfig config) { final long mem = node.getMemoryPerSubTask(); if (mem > 0) { config.setMemoryDriver(mem); config.setFilehandlesDriver(this.defaultMaxFan); config.setSpillingThresholdDriver(this.defaultSortSpillingThreshold); } } private void assignLocalStrategyResources(Channel c, TaskConfig config, int inputNum) { if (c.getMemoryLocalStrategy() > 0) { config.setMemoryInput(inputNum, c.getMemoryLocalStrategy()); config.setFilehandlesInput(inputNum, this.defaultMaxFan); config.setSpillingThresholdInput(inputNum, this.defaultSortSpillingThreshold); } } // ------------------------------------------------------------------------ // Connecting Vertices // ------------------------------------------------------------------------ /** * NOTE: The channel for global and local strategies are different if we connect a union. The global strategy * channel is then the channel into the union node, the local strategy channel the one from the union to the * actual target operator. * * @param channelForGlobalStrategy * @param channelForLocalStrategy * @param inputNumber * @param sourceVertex * @param sourceConfig * @param targetVertex * @param targetConfig * @throws JobGraphDefinitionException * @throws CompilerException */ private DistributionPattern connectJobVertices(Channel channel, int inputNumber, final AbstractJobVertex sourceVertex, final TaskConfig sourceConfig, final AbstractJobVertex targetVertex, final TaskConfig targetConfig, boolean isBroadcast) throws JobGraphDefinitionException, CompilerException { // ------------ connect the vertices to the job graph -------------- final ChannelType channelType; final DistributionPattern distributionPattern; switch (channel.getShipStrategy()) { case FORWARD: case PARTITION_LOCAL_HASH: distributionPattern = DistributionPattern.POINTWISE; channelType = ChannelType.NETWORK; break; case PARTITION_RANDOM: case BROADCAST: case PARTITION_HASH: case PARTITION_RANGE: distributionPattern = DistributionPattern.BIPARTITE; channelType = ChannelType.NETWORK; break; default: throw new RuntimeException("Unknown runtime ship strategy: " + channel.getShipStrategy()); } sourceVertex.connectTo(targetVertex, channelType, distributionPattern); // -------------- configure the source task's ship strategy strategies in task config -------------- final int outputIndex = sourceConfig.getNumOutputs(); sourceConfig.addOutputShipStrategy(channel.getShipStrategy()); if (outputIndex == 0) { sourceConfig.setOutputSerializer(channel.getSerializer()); } if (channel.getShipStrategyComparator() != null) { sourceConfig.setOutputComparator(channel.getShipStrategyComparator(), outputIndex); } if (channel.getShipStrategy() == ShipStrategyType.PARTITION_RANGE) { final DataDistribution dataDistribution = channel.getDataDistribution(); if(dataDistribution != null) { sourceConfig.setOutputDataDistribution(dataDistribution, outputIndex); } else { throw new RuntimeException("Range partitioning requires data distribution"); // TODO: inject code and configuration for automatic histogram generation } } // if (targetContract instanceof GenericDataSink) { // final DataDistribution distri = ((GenericDataSink) targetContract).getDataDistribution(); // if (distri != null) { // configForOutputShipStrategy.setOutputDataDistribution(distri); // } // } // ---------------- configure the receiver ------------------- if (isBroadcast) { targetConfig.addBroadcastInputToGroup(inputNumber); } else { targetConfig.addInputToGroup(inputNumber); } return distributionPattern; } private void addLocalInfoFromChannelToConfig(Channel channel, TaskConfig config, int inputNum, boolean isBroadcastChannel) { // serializer if (isBroadcastChannel) { config.setBroadcastInputSerializer(channel.getSerializer(), inputNum); if (channel.getLocalStrategy() != LocalStrategy.NONE || (channel.getTempMode() != null && channel.getTempMode() != TempMode.NONE)) { throw new CompilerException("Found local strategy or temp mode on a broadcast variable channel."); } else { return; } } else { config.setInputSerializer(channel.getSerializer(), inputNum); } // local strategy if (channel.getLocalStrategy() != LocalStrategy.NONE) { config.setInputLocalStrategy(inputNum, channel.getLocalStrategy()); if (channel.getLocalStrategyComparator() != null) { config.setInputComparator(channel.getLocalStrategyComparator(), inputNum); } } assignLocalStrategyResources(channel, config, inputNum); // materialization / caching if (channel.getTempMode() != null) { final TempMode tm = channel.getTempMode(); boolean needsMemory = false; if (tm.breaksPipeline()) { config.setInputAsynchronouslyMaterialized(inputNum, true); needsMemory = true; } if (tm.isCached()) { config.setInputCached(inputNum, true); needsMemory = true; } if (needsMemory) { // sanity check if (tm == null || tm == TempMode.NONE || channel.getTempMemory() < 1) { throw new CompilerException("Bug in compiler: Inconsistent description of input materialization."); } config.setInputMaterializationMemory(inputNum, channel.getTempMemory()); } } } private void finalizeBulkIteration(IterationDescriptor descr) { final BulkIterationPlanNode bulkNode = (BulkIterationPlanNode) descr.getIterationNode(); final JobTaskVertex headVertex = descr.getHeadTask(); final TaskConfig headConfig = new TaskConfig(headVertex.getConfiguration()); final TaskConfig headFinalOutputConfig = descr.getHeadFinalResultConfig(); // ------------ finalize the head config with the final outputs and the sync gate ------------ final int numStepFunctionOuts = headConfig.getNumOutputs(); final int numFinalOuts = headFinalOutputConfig.getNumOutputs(); headConfig.setIterationHeadFinalOutputConfig(headFinalOutputConfig); headConfig.setIterationHeadIndexOfSyncOutput(numStepFunctionOuts + numFinalOuts); final long memForBackChannel = bulkNode.getMemoryPerSubTask(); if (memForBackChannel <= 0) { throw new CompilerException("Bug: No memory has been assigned to the iteration back channel."); } headConfig.setBackChannelMemory(memForBackChannel); // --------------------------- create the sync task --------------------------- final JobOutputVertex sync = new JobOutputVertex("Sync(" + bulkNode.getNodeName() + ")", this.jobGraph); sync.setOutputClass(IterationSynchronizationSinkTask.class); sync.setNumberOfSubtasks(1); this.auxVertices.add(sync); final TaskConfig syncConfig = new TaskConfig(sync.getConfiguration()); syncConfig.setGateIterativeWithNumberOfEventsUntilInterrupt(0, headVertex.getNumberOfSubtasks()); // set the number of iteration / convergence criterion for the sync final int maxNumIterations = bulkNode.getIterationNode().getIterationContract().getMaximumNumberOfIterations(); if (maxNumIterations < 1) { throw new CompilerException("Cannot create bulk iteration with unspecified maximum number of iterations."); } syncConfig.setNumberOfIterations(maxNumIterations); // connect the sync task try { headVertex.connectTo(sync, ChannelType.NETWORK, DistributionPattern.POINTWISE); } catch (JobGraphDefinitionException e) { throw new CompilerException("Bug: Cannot connect head vertex to sync task."); } // ----------------------------- create the iteration tail ------------------------------ final PlanNode rootOfTerminationCriterion = bulkNode.getRootOfTerminationCriterion(); final PlanNode rootOfStepFunction = bulkNode.getRootOfStepFunction(); final TaskConfig tailConfig; JobTaskVertex rootOfStepFunctionVertex = (JobTaskVertex) this.vertices.get(rootOfStepFunction); if (rootOfStepFunctionVertex == null) { // last op is chained final TaskInChain taskInChain = this.chainedTasks.get(rootOfStepFunction); if (taskInChain == null) { throw new CompilerException("Bug: Tail of step function not found as vertex or chained task."); } rootOfStepFunctionVertex = (JobTaskVertex) taskInChain.getContainingVertex(); // the fake channel is statically typed to pact record. no data is sent over this channel anyways. tailConfig = taskInChain.getTaskConfig(); } else { tailConfig = new TaskConfig(rootOfStepFunctionVertex.getConfiguration()); } tailConfig.setIsWorksetUpdate(); // No following termination criterion if(rootOfStepFunction.getOutgoingChannels().isEmpty()) { rootOfStepFunctionVertex.setTaskClass(IterationTailPactTask.class); tailConfig.setOutputSerializer(bulkNode.getSerializerForIterationChannel()); tailConfig.addOutputShipStrategy(ShipStrategyType.FORWARD); // create the fake output task JobOutputVertex fakeTail = new JobOutputVertex("Fake Tail", this.jobGraph); fakeTail.setOutputClass(FakeOutputTask.class); fakeTail.setNumberOfSubtasks(headVertex.getNumberOfSubtasks()); fakeTail.setNumberOfSubtasksPerInstance(headVertex.getNumberOfSubtasksPerInstance()); this.auxVertices.add(fakeTail); // connect the fake tail try { rootOfStepFunctionVertex.connectTo(fakeTail, ChannelType.INMEMORY, DistributionPattern.POINTWISE); } catch (JobGraphDefinitionException e) { throw new CompilerException("Bug: Cannot connect iteration tail vertex fake tail task"); } } // create the fake output task for termination criterion, if needed final TaskConfig tailConfigOfTerminationCriterion; // If we have a termination criterion and it is not an intermediate node if(rootOfTerminationCriterion != null && rootOfTerminationCriterion.getOutgoingChannels().isEmpty()) { JobTaskVertex rootOfTerminationCriterionVertex = (JobTaskVertex) this.vertices.get(rootOfTerminationCriterion); if (rootOfTerminationCriterionVertex == null) { // last op is chained final TaskInChain taskInChain = this.chainedTasks.get(rootOfTerminationCriterion); if (taskInChain == null) { throw new CompilerException("Bug: Tail of termination criterion not found as vertex or chained task."); } rootOfTerminationCriterionVertex = (JobTaskVertex) taskInChain.getContainingVertex(); // the fake channel is statically typed to pact record. no data is sent over this channel anyways. tailConfigOfTerminationCriterion = taskInChain.getTaskConfig(); } else { tailConfigOfTerminationCriterion = new TaskConfig(rootOfTerminationCriterionVertex.getConfiguration()); } rootOfTerminationCriterionVertex.setTaskClass(IterationTailPactTask.class); // Hack tailConfigOfTerminationCriterion.setIsSolutionSetUpdate(); tailConfigOfTerminationCriterion.setOutputSerializer(bulkNode.getSerializerForIterationChannel()); tailConfigOfTerminationCriterion.addOutputShipStrategy(ShipStrategyType.FORWARD); JobOutputVertex fakeTailTerminationCriterion = new JobOutputVertex("Fake Tail for Termination Criterion", this.jobGraph); fakeTailTerminationCriterion.setOutputClass(FakeOutputTask.class); fakeTailTerminationCriterion.setNumberOfSubtasks(headVertex.getNumberOfSubtasks()); fakeTailTerminationCriterion.setNumberOfSubtasksPerInstance(headVertex.getNumberOfSubtasksPerInstance()); this.auxVertices.add(fakeTailTerminationCriterion); // connect the fake tail try { rootOfTerminationCriterionVertex.connectTo(fakeTailTerminationCriterion, ChannelType.INMEMORY, DistributionPattern.POINTWISE); } catch (JobGraphDefinitionException e) { throw new CompilerException("Bug: Cannot connect iteration tail vertex fake tail task for termination criterion"); } // tell the head that it needs to wait for the solution set updates headConfig.setWaitForSolutionSetUpdate(); } // ------------------- register the aggregators ------------------- AggregatorRegistry aggs = bulkNode.getIterationNode().getIterationContract().getAggregators(); Collection<AggregatorWithName<?>> allAggregators = aggs.getAllRegisteredAggregators(); headConfig.addIterationAggregators(allAggregators); syncConfig.addIterationAggregators(allAggregators); String convAggName = aggs.getConvergenceCriterionAggregatorName(); Class<? extends ConvergenceCriterion<?>> convCriterion = aggs.getConvergenceCriterion(); if (convCriterion != null || convAggName != null) { if (convCriterion == null) { throw new CompilerException("Error: Convergence criterion aggregator set, but criterion is null."); } if (convAggName == null) { throw new CompilerException("Error: Aggregator convergence criterion set, but aggregator is null."); } syncConfig.setConvergenceCriterion(convAggName, convCriterion); } } private void finalizeWorksetIteration(IterationDescriptor descr) { final WorksetIterationPlanNode iterNode = (WorksetIterationPlanNode) descr.getIterationNode(); final JobTaskVertex headVertex = descr.getHeadTask(); final TaskConfig headConfig = new TaskConfig(headVertex.getConfiguration()); final TaskConfig headFinalOutputConfig = descr.getHeadFinalResultConfig(); // ------------ finalize the head config with the final outputs and the sync gate ------------ { final int numStepFunctionOuts = headConfig.getNumOutputs(); final int numFinalOuts = headFinalOutputConfig.getNumOutputs(); headConfig.setIterationHeadFinalOutputConfig(headFinalOutputConfig); headConfig.setIterationHeadIndexOfSyncOutput(numStepFunctionOuts + numFinalOuts); final long mem = iterNode.getMemoryPerSubTask(); if (mem <= 0) { throw new CompilerException("Bug: No memory has been assigned to the workset iteration."); } headConfig.setIsWorksetIteration(); headConfig.setBackChannelMemory(mem / 2); headConfig.setSolutionSetMemory(mem / 2); // set the solution set serializer and comparator headConfig.setSolutionSetSerializer(iterNode.getSolutionSetSerializer()); headConfig.setSolutionSetComparator(iterNode.getSolutionSetComparator()); } // --------------------------- create the sync task --------------------------- final TaskConfig syncConfig; { final JobOutputVertex sync = new JobOutputVertex("Sync (" + iterNode.getNodeName() + ")", this.jobGraph); sync.setOutputClass(IterationSynchronizationSinkTask.class); sync.setNumberOfSubtasks(1); this.auxVertices.add(sync); syncConfig = new TaskConfig(sync.getConfiguration()); syncConfig.setGateIterativeWithNumberOfEventsUntilInterrupt(0, headVertex.getNumberOfSubtasks()); // set the number of iteration / convergence criterion for the sync final int maxNumIterations = iterNode.getIterationNode().getIterationContract().getMaximumNumberOfIterations(); if (maxNumIterations < 1) { throw new CompilerException("Cannot create workset iteration with unspecified maximum number of iterations."); } syncConfig.setNumberOfIterations(maxNumIterations); // connect the sync task try { headVertex.connectTo(sync, ChannelType.NETWORK, DistributionPattern.POINTWISE); } catch (JobGraphDefinitionException e) { throw new CompilerException("Bug: Cannot connect head vertex to sync task."); } } // ----------------------------- create the iteration tails ----------------------------- // ----------------------- for next workset and solution set delta----------------------- { // we have three possible cases: // 1) Two tails, one for workset update, one for solution set update // 2) One tail for workset update, solution set update happens in an intermediate task // 3) One tail for solution set update, workset update happens in an intermediate task final PlanNode nextWorksetNode = iterNode.getNextWorkSetPlanNode(); final PlanNode solutionDeltaNode = iterNode.getSolutionSetDeltaPlanNode(); final boolean hasWorksetTail = nextWorksetNode.getOutgoingChannels().isEmpty(); final boolean hasSolutionSetTail = (!iterNode.isImmediateSolutionSetUpdate()) || (!hasWorksetTail); { // get the vertex for the workset update final TaskConfig worksetTailConfig; JobTaskVertex nextWorksetVertex = (JobTaskVertex) this.vertices.get(nextWorksetNode); if (nextWorksetVertex == null) { // nextWorksetVertex is chained TaskInChain taskInChain = this.chainedTasks.get(nextWorksetNode); if (taskInChain == null) { throw new CompilerException("Bug: Next workset node not found as vertex or chained task."); } nextWorksetVertex = (JobTaskVertex) taskInChain.getContainingVertex(); worksetTailConfig = taskInChain.getTaskConfig(); } else { worksetTailConfig = new TaskConfig(nextWorksetVertex.getConfiguration()); } // mark the node to perform workset updates worksetTailConfig.setIsWorksetIteration(); worksetTailConfig.setIsWorksetUpdate(); if (hasWorksetTail) { nextWorksetVertex.setTaskClass(IterationTailPactTask.class); worksetTailConfig.setOutputSerializer(iterNode.getWorksetSerializer()); worksetTailConfig.addOutputShipStrategy(ShipStrategyType.FORWARD); // create the fake output task JobOutputVertex fakeTail = new JobOutputVertex("Fake Tail", this.jobGraph); fakeTail.setOutputClass(FakeOutputTask.class); fakeTail.setNumberOfSubtasks(headVertex.getNumberOfSubtasks()); fakeTail.setNumberOfSubtasksPerInstance(headVertex.getNumberOfSubtasksPerInstance()); this.auxVertices.add(fakeTail); // connect the fake tail try { nextWorksetVertex.connectTo(fakeTail, ChannelType.INMEMORY, DistributionPattern.POINTWISE); } catch (JobGraphDefinitionException e) { throw new CompilerException("Bug: Cannot connect iteration tail vertex fake tail task"); } } } { final TaskConfig solutionDeltaConfig; JobTaskVertex solutionDeltaVertex = (JobTaskVertex) this.vertices.get(solutionDeltaNode); if (solutionDeltaVertex == null) { // last op is chained TaskInChain taskInChain = this.chainedTasks.get(solutionDeltaNode); if (taskInChain == null) { throw new CompilerException("Bug: Solution Set Delta not found as vertex or chained task."); } solutionDeltaVertex = (JobTaskVertex) taskInChain.getContainingVertex(); solutionDeltaConfig = taskInChain.getTaskConfig(); } else { solutionDeltaConfig = new TaskConfig(solutionDeltaVertex.getConfiguration()); } solutionDeltaConfig.setIsWorksetIteration(); solutionDeltaConfig.setIsSolutionSetUpdate(); if (hasSolutionSetTail) { solutionDeltaVertex.setTaskClass(IterationTailPactTask.class); solutionDeltaConfig.setOutputSerializer(iterNode.getSolutionSetSerializer()); solutionDeltaConfig.addOutputShipStrategy(ShipStrategyType.FORWARD); // create the fake output task JobOutputVertex fakeTail = new JobOutputVertex("Fake Tail", this.jobGraph); fakeTail.setOutputClass(FakeOutputTask.class); fakeTail.setNumberOfSubtasks(headVertex.getNumberOfSubtasks()); fakeTail.setNumberOfSubtasksPerInstance(headVertex.getNumberOfSubtasksPerInstance()); this.auxVertices.add(fakeTail); // connect the fake tail try { solutionDeltaVertex.connectTo(fakeTail, ChannelType.INMEMORY, DistributionPattern.POINTWISE); } catch (JobGraphDefinitionException e) { throw new CompilerException("Bug: Cannot connect iteration tail vertex fake tail task"); } // tell the head that it needs to wait for the solution set updates headConfig.setWaitForSolutionSetUpdate(); } else { // no tail, intermediate update. must be immediate update if (!iterNode.isImmediateSolutionSetUpdate()) { throw new CompilerException("A solution set update without dedicated tail is not set to perform immediate updates."); } solutionDeltaConfig.setIsSolutionSetUpdateWithoutReprobe(); } } } // ------------------- register the aggregators ------------------- AggregatorRegistry aggs = iterNode.getIterationNode().getIterationContract().getAggregators(); Collection<AggregatorWithName<?>> allAggregators = aggs.getAllRegisteredAggregators(); for (AggregatorWithName<?> agg : allAggregators) { if (agg.getName().equals(WorksetEmptyConvergenceCriterion.AGGREGATOR_NAME)) { throw new CompilerException("User defined aggregator used the same name as built-in workset " + "termination check aggregator: " + WorksetEmptyConvergenceCriterion.AGGREGATOR_NAME); } } headConfig.addIterationAggregators(allAggregators); syncConfig.addIterationAggregators(allAggregators); String convAggName = aggs.getConvergenceCriterionAggregatorName(); Class<? extends ConvergenceCriterion<?>> convCriterion = aggs.getConvergenceCriterion(); if (convCriterion != null || convAggName != null) { throw new CompilerException("Error: Cannot use custom convergence criterion with workset iteration. Workset iterations have implicit convergence criterion where workset is empty."); } headConfig.addIterationAggregator(WorksetEmptyConvergenceCriterion.AGGREGATOR_NAME, LongSumAggregator.class); syncConfig.addIterationAggregator(WorksetEmptyConvergenceCriterion.AGGREGATOR_NAME, LongSumAggregator.class); syncConfig.setConvergenceCriterion(WorksetEmptyConvergenceCriterion.AGGREGATOR_NAME, WorksetEmptyConvergenceCriterion.class); } // ------------------------------------------------------------------------------------- // Descriptors for tasks / configurations that are chained or merged with other tasks // ------------------------------------------------------------------------------------- /** * Utility class that describes a task in a sequence of chained tasks. Chained tasks are tasks that run * together in one thread. */ private static final class TaskInChain { private final Class<? extends ChainedDriver<?, ?>> chainedTask; private final TaskConfig taskConfig; private final String taskName; private AbstractJobVertex containingVertex; @SuppressWarnings("unchecked") TaskInChain(@SuppressWarnings("rawtypes") Class<? extends ChainedDriver> chainedTask, TaskConfig taskConfig, String taskName) { this.chainedTask = (Class<? extends ChainedDriver<?, ?>>) chainedTask; this.taskConfig = taskConfig; this.taskName = taskName; } public Class<? extends ChainedDriver<?, ?>> getChainedTask() { return this.chainedTask; } public TaskConfig getTaskConfig() { return this.taskConfig; } public String getTaskName() { return this.taskName; } public AbstractJobVertex getContainingVertex() { return this.containingVertex; } public void setContainingVertex(AbstractJobVertex containingVertex) { this.containingVertex = containingVertex; } } private static final class IterationDescriptor { private final IterationPlanNode iterationNode; private JobTaskVertex headTask; private TaskConfig headConfig; private TaskConfig headFinalResultConfig; private final int id; public IterationDescriptor(IterationPlanNode iterationNode, int id) { this.iterationNode = iterationNode; this.id = id; } public IterationPlanNode getIterationNode() { return iterationNode; } public void setHeadTask(JobTaskVertex headTask, TaskConfig headConfig) { this.headTask = headTask; this.headFinalResultConfig = new TaskConfig(new Configuration()); // check if we already had a configuration, for example if the solution set was if (this.headConfig != null) { headConfig.getConfiguration().addAll(this.headConfig.getConfiguration()); } this.headConfig = headConfig; } public JobTaskVertex getHeadTask() { return headTask; } public TaskConfig getHeadConfig() { // if there is no configuration yet (solution set parameterization before the // head is created) then we create one now if (this.headConfig == null) { this.headConfig = new TaskConfig(new Configuration()); } return headConfig; } public TaskConfig getHeadFinalResultConfig() { return headFinalResultConfig; } public int getId() { return this.id; } } }
false
false
null
null
diff --git a/src/util/ConsoleReader.java b/src/util/ConsoleReader.java index 0a0d3b0..951aa4d 100755 --- a/src/util/ConsoleReader.java +++ b/src/util/ConsoleReader.java @@ -1,137 +1,146 @@ package util; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; /** * Provides variety of methods to simplify getting user input from console. * * @author Robert C. Duvall */ public class ConsoleReader { // by default, read input from the user's console private static Scanner in = new Scanner(new InputStreamReader(System.in)); /** * Prompts the user to input an integer value. * * @param prompt output to the user before waiting for input * @return the value entered, waiting if necessary until one is given */ public static int promptInt (String prompt) { System.out.print(prompt); return in.nextInt(); } /** * Prompts the user to input an real value. * * @param prompt output to the user before waiting for input * @return the value entered, waiting if necessary until one is given */ public static double promptDouble (String prompt) { System.out.print(prompt); return in.nextDouble(); } /** * Prompts the user to input a word. * * @param prompt output to the user before waiting for input * @return the value entered, waiting if necessary until one is given */ public static String promptString (String prompt) { System.out.print(prompt); return in.next(); } /** * Prompts the user to input an integer value between the given values, * inclusive. Note, repeatedly prompts the user until a valid value is * entered. * * @param prompt output to the user before waiting for input * @param low minimum possible valid value allowed * @param hi maximum possible valid value allowed * @return the value entered, waiting if necessary until one is given */ public static int promptRange (String prompt, int low, int hi) { int answer; do { answer = promptInt(prompt + " between " + low + " and " + hi + "? "); } while (low > answer || answer > hi); return answer; } /** * Prompts the user to input an real value between the given values, * inclusive. Note, repeatedly prompts the user until a valid value is * entered. * * @param prompt output to the user before waiting for input * @param low minimum possible valid value allowed * @param hi maximum possible valid value allowed * @return the value entered, waiting if necessary until one is given */ public static double promptRange (String prompt, double low, double hi) { double answer; do { answer = promptDouble(prompt + " between " + low + " and " + hi + "? "); } while (low > answer || answer > hi); return answer; } /** * Prompts the user to input one of the given choices to the question. Note, * repeatedly prompts the user until a valid choice is entered. * * @param prompt output to the user before waiting for input * @param choices possible valid responses user can enter * @return the value entered, waiting if necessary until one is given */ public static String promptOneOf (String prompt, String ... choices) { Set<String> choiceSet = new TreeSet<String>(Arrays.asList(choices)); String result; do { - result = promptString(prompt + " one of " + choices + "? "); + StringBuilder buf = new StringBuilder(); + for( int i=0; i<choices.length; i++ ) + { + if( i > 0 ) + { + buf.append( ", " ); + } + buf.append( choices[i] ); + } + result = promptString(prompt + " one of " + buf.toString() + "? "); } while (!choiceSet.contains(result)); return result; } /** * Prompts the user to input yes or no to the given question. Note, * repeatedly prompts the user until yes or no is entered. * * @param prompt output to the user before waiting for input * @return the value entered, waiting if necessary until one is given */ public static boolean promptYesNo (String prompt) { String answer = promptOneOf(prompt, "yes", "Yes", "y", "Y", "no", "No", "n", "N"); return (answer.toLowerCase().startsWith("y")); } }
true
true
public static String promptOneOf (String prompt, String ... choices) { Set<String> choiceSet = new TreeSet<String>(Arrays.asList(choices)); String result; do { result = promptString(prompt + " one of " + choices + "? "); } while (!choiceSet.contains(result)); return result; }
public static String promptOneOf (String prompt, String ... choices) { Set<String> choiceSet = new TreeSet<String>(Arrays.asList(choices)); String result; do { StringBuilder buf = new StringBuilder(); for( int i=0; i<choices.length; i++ ) { if( i > 0 ) { buf.append( ", " ); } buf.append( choices[i] ); } result = promptString(prompt + " one of " + buf.toString() + "? "); } while (!choiceSet.contains(result)); return result; }
diff --git a/Harvester/trunk/src/main/java/org/vivoweb/ingest/score/Score.java b/Harvester/trunk/src/main/java/org/vivoweb/ingest/score/Score.java index 0f69363a..d8f836f6 100644 --- a/Harvester/trunk/src/main/java/org/vivoweb/ingest/score/Score.java +++ b/Harvester/trunk/src/main/java/org/vivoweb/ingest/score/Score.java @@ -1,385 +1,389 @@ /******************************************************************************* * Copyright (c) 2010 Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams. * All rights reserved. This program and the accompanying materials * are made available under the terms of the new BSD license * which accompanies this distribution, and is available at * http://www.opensource.org/licenses/bsd-license.html * * Contributors: * Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams - initial API and implementation * Christoper Barnes, Narayan Raum - scoring ideas and algorithim * Yang Li - pairwise scoring algorithm ******************************************************************************/ package org.vivoweb.ingest.score; import java.io.ByteArrayInputStream; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.vivoweb.ingest.util.JenaConnect; import org.vivoweb.ingest.util.Record; import org.vivoweb.ingest.util.RecordHandler; import org.xml.sax.SAXException; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.*; /*** * VIVO Score * @author Nicholas Skaggs nskaggs@ichp.ufl.edu */ public class Score { /** * Log4J Logger */ private static Log log = LogFactory.getLog(Score.class); /** * Model for VIVO instance */ private Model vivo; /** * Model where input is stored */ private Model scoreInput; /** * Model where output is stored */ private Model scoreOutput; /** * Main Method * @param args command line arguments rdfRecordHandler tempJenaConfig vivoJenaConfig outputJenaConfig */ final static public void main(String[] args) { log.info("Scoring: Start"); //pass models from command line //TODO Nicholas: proper args handler if (args.length != 4) { log.error("Usage requires 4 arguments rdfRecordHandler tempJenaConfig vivoJenaConfig outputJenaConfig"); return; } try { log.info("Loading configuration and models"); RecordHandler rh = RecordHandler.parseConfig(args[0]); JenaConnect jenaTempDB = JenaConnect.parseConfig(args[1]); JenaConnect jenaVivoDB = JenaConnect.parseConfig(args[2]); JenaConnect jenaOutputDB = JenaConnect.parseConfig(args[3]); Model jenaInputDB = jenaTempDB.getJenaModel(); for (Record r: rh) { jenaInputDB.read(new ByteArrayInputStream(r.getData().getBytes()), null); } new Score(jenaVivoDB.getJenaModel(), jenaInputDB, jenaOutputDB.getJenaModel()).execute(); } catch(ParserConfigurationException e) { log.fatal(e.getMessage(),e); } catch(SAXException e) { log.fatal(e.getMessage(),e); } catch(IOException e) { log.fatal(e.getMessage(),e); } log.info("Scoring: End"); } /** * Constructor * @param jenaVivo model containing vivo statements * @param jenaScoreInput model containing statements to be scored * @param jenaScoreOutput output model */ public Score(Model jenaVivo, Model jenaScoreInput, Model jenaScoreOutput) { this.vivo = jenaVivo; this.scoreInput = jenaScoreInput; this.scoreOutput = jenaScoreOutput; } /** * Executes scoring algorithms */ public void execute() { ResultSet scoreInputResult; //DEBUG //TODO Nicholas: howto pass this in via config log.info("Executing matchResult"); String matchAttribute = "email"; String matchQuery = "PREFIX score: <http://vivoweb.org/ontology/score#> " + "SELECT ?x ?email " + "WHERE { ?x score:workEmail ?email}"; String coreAttribute = "core:workEmail"; //DEBUG //Attempt Matching //Exact Matches //TODO Nicholas: finish implementation of exact matching loop //for each matchAttribute scoreInputResult = executeQuery(this.scoreInput, matchQuery); - exactMatch(this.vivo,this.scoreInput,matchAttribute,coreAttribute,scoreInputResult); + exactMatch(this.vivo,this.scoreOutput,matchAttribute,coreAttribute,scoreInputResult); //end for //DEBUG //TODO Nicholas: howto pass this in via config //matchAttribute = "author"; //matchQuery = "PREFIX score: <http://vivoweb.org/ontology/score#> " + // "SELECT ?x ?author " + // "WHERE { ?x score:author ?author}"; //coreAttribute = "core:author"; //DEBUG //Pairwise Matches //TODO Nicholas: finish implementation of pairwise matching loop //for each matchAttribute //scoreInputResult = executeQuery(scoreInput, matchQuery); //pairwiseScore(vivo,scoreInput,matchAttribute,coreAttribute,scoreInputResult); //end for //Close and done this.scoreInput.close(); this.scoreOutput.close(); this.vivo.close(); } /** * Executes a sparql query against a JENA model and returns a result set * @param model a model containing statements * @param queryString the query to execute against the model * @return queryExec the executed query result set */ private static ResultSet executeQuery(Model model, String queryString) { Query query = QueryFactory.create(queryString); QueryExecution queryExec = QueryExecutionFactory.create(query, model); return queryExec.execSelect(); } /** * Commits resultset to a matched model * @param result a model containing vivo statements * @param storeResult the result to be stored * @param paperResource the paper of the resource * @param matchNode the node to match * @param paperNode the node of the paper */ private static void commitResultSet(Model result, ResultSet storeResult, Resource paperResource, RDFNode matchNode, RDFNode paperNode) { RDFNode authorNode; QuerySolution vivoSolution; //loop thru resultset while (storeResult.hasNext()) { vivoSolution = storeResult.nextSolution(); //Grab person URI authorNode = vivoSolution.get("x"); log.info("Found " + matchNode.toString() + " for person " + authorNode.toString()); log.info("Adding paper " + paperNode.toString()); result.add(recursiveSanitizeBuild(paperResource,null)); - replaceResource(authorNode, paperNode, result); + replaceResource(authorNode,paperNode, result); //take results and store in matched model result.commit(); } } /** * Traverses paperNode and adds to toReplace model * @param mainNode primary node * @param paperNode node of paper * @param toReplace model to replace - * @return a model (toReplace to be exact) //TODO Nicholas: you know that this is unnecessary as Java passes Objects by reference? You can just be void -CAH */ - private static Model replaceResource(RDFNode mainNode, RDFNode paperNode, Model toReplace){ + private static void replaceResource(RDFNode mainNode, RDFNode paperNode, Model toReplace){ Resource authorship; Property linkedAuthorOf = ResourceFactory.createProperty("http://vivoweb.org/ontology/core#linkedAuthor"); Property authorshipForPerson = ResourceFactory.createProperty("http://vivoweb.org/ontology/core#authorInAuthorship"); Property authorshipForPaper = ResourceFactory.createProperty("http://vivoweb.org/ontology/core#informationResourceInAuthorship"); Property paperOf = ResourceFactory.createProperty("http://vivoweb.org/ontology/core#linkedInformationResource"); Resource flag1 = ResourceFactory.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/0.7#Flag1Value1Thing"); Property rdfType = ResourceFactory.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); Property rdfLabel = ResourceFactory.createProperty("http://www.w3.org/2000/01/rdf-schema#label"); log.info("Link paper " + paperNode.toString() + " to person " + mainNode.toString() + " in VIVO"); authorship = ResourceFactory.createResource(paperNode.toString() + "/vivoAuthorship/1"); //string that finds the last name of the person in VIVO - Statement authorLName = ((Resource)mainNode).getProperty(ResourceFactory.createProperty("http://xmlns.com/foaf/0.1/lastname")); + Statement authorLName = ((Resource)mainNode).getProperty(ResourceFactory.createProperty("http://xmlns.com/foaf/0.1/lastName")); String authorQuery = "PREFIX core: <http://vivoweb.org/ontology/core#> " + "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " + "SELECT ?x " + - "WHERE {?badNode foaf:lastName " + authorLName.getObject().toString() + " ." + - "?badNode http://vivoweb.org/ontology/core#authorInAuthorship ?authorship}" + - "?authorship http://vivoweb.org/ontology/core#linkedInformationResource " + paperNode.toString() ; + "WHERE {?badNode foaf:lastName \"" + authorLName.getObject().toString() + "\" . " + + "?badNode core:authorInAuthorship ?authorship . " + + "?authorship core:linkedInformationResource <" + paperNode.toString() + "> }"; log.debug(authorQuery); ResultSet killList = executeQuery(toReplace,authorQuery); while(killList.hasNext()){ //query the paper for the first author node (assumption that affiliation matches first author) Resource removeAuthor = toReplace.getResource(killList.next().toString()); //return a statment iterator with all the statements for the Author that matches, then remove those statements StmtIterator deleteStmts = toReplace.listStatements(null, null, removeAuthor); toReplace.remove(deleteStmts); deleteStmts = toReplace.listStatements(removeAuthor, null, (RDFNode)null); toReplace.remove(deleteStmts); } toReplace.add(authorship,linkedAuthorOf,mainNode); log.trace("Link Statement [" + authorship.toString() + ", " + linkedAuthorOf.toString() + ", " + mainNode.toString() + "]"); toReplace.add((Resource)mainNode,authorshipForPerson,authorship); log.trace("Link Statement [" + mainNode.toString() + ", " + authorshipForPerson.toString() + ", " + authorship.toString() + "]"); toReplace.add(authorship,paperOf,paperNode); log.trace("Link Statement [" + authorship.toString() + ", " + paperOf.toString() + ", " + paperNode.toString() + "]"); toReplace.add((Resource)paperNode,authorshipForPaper,authorship); log.trace("Link Statement [" + paperNode.toString() + ", " + authorshipForPaper.toString() + ", " + authorship.toString() + "]"); toReplace.add(authorship,rdfType,flag1); log.trace("Link Statement [" + authorship.toString() + ", " + rdfType.toString() + ", " + flag1.toString() + "]"); toReplace.add(authorship,rdfLabel,"Authorship for Paper"); log.trace("Link Statement [" + authorship.toString() + ", " + rdfLabel.toString() + ", " + "Authorship for Paper]"); - - return toReplace; } /** * Traverses paperNode and adds to toReplace model * @param mainRes the main resource * @param linkRes the resource to link it to * @return the model containing the sanitized info so far */ private static Model recursiveSanitizeBuild(Resource mainRes, Resource linkRes){ Model returnModel = ModelFactory.createDefaultModel(); Statement stmt; StmtIterator mainStmts = mainRes.listProperties(); while (mainStmts.hasNext()) { stmt = mainStmts.nextStatement(); log.trace("Statement " + stmt.toString()); //Don't add any scoring statements if (!stmt.getPredicate().toString().contains("/score")) { returnModel.add(stmt); - if (stmt.getObject().isResource() && (Resource)stmt.getObject() != linkRes) { + if ((stmt.getObject().isResource() && !((Resource)stmt.getObject()).equals(linkRes)) && !((Resource)stmt.getObject()).equals(mainRes)) { returnModel.add(recursiveSanitizeBuild((Resource)stmt.getObject(), mainRes)); } + if (!stmt.getSubject().equals(linkRes) && !stmt.getSubject().equals(mainRes)) { + returnModel.add(recursiveSanitizeBuild(stmt.getSubject(), mainRes)); + } } } return returnModel; } /** * Executes a pair scoring method, utilizing the matchAttribute. This attribute is expected to * return 2 to n results from the given query. This "pair" will then be utilized as a matching scheme * to construct a sub dataset. This dataset can be scored and stored as a match * @param matched a model containing statements describing known authors * @param score a model containing statements to be disambiguated * @param matchAttribute an attribute to perform the exact match * @param coreAttribute an attribute to perform the exact match against from core ontology * @param matchResult contains a resultset of the matchAttribute * @return score model */ @SuppressWarnings("unused") private static Model pairwiseScore(Model matched, Model score, String matchAttribute, String coreAttribute, ResultSet matchResult) { //iterate thru scoringInput pairs against matched pairs //TODO Nicholas: support partial scoring, multiples matches against several pairs //if pairs match, store publication to matched author in Model //TODO Nicholas: return scoreInput minus the scored statements String scoreMatch; RDFNode matchNode; QuerySolution scoreSolution; //create pairs of *attribute* from matched log.info("Creating pairs of " + matchAttribute + " from input"); //look for exact match in vivo while (matchResult.hasNext()) { scoreSolution = matchResult.nextSolution(); matchNode = scoreSolution.get(matchAttribute); scoreMatch = matchNode.toString(); log.info("\nChecking for " + scoreMatch + " in VIVO"); } //TODO Nicholas: return scoreInput minus the scored statements return score; } /** * Executes an exact matching algorithm for author disambiguation * @param matched a model containing statements describing authors * @param output a model containing statements to be disambiguated * @param matchAttribute an attribute to perform the exact match * @param coreAttribute an attribute to perform the exact match against from core ontology * @param matchResult contains a resultset of the matchAttribute * @return model of matched statements */ private static Model exactMatch(Model matched, Model output, String matchAttribute, String coreAttribute, ResultSet matchResult) { String scoreMatch; String queryString; Resource paperResource; RDFNode matchNode; RDFNode paperNode; ResultSet vivoResult; QuerySolution scoreSolution; log.info("Looping thru " + matchAttribute + " from input"); //look for exact match in vivo while (matchResult.hasNext()) { scoreSolution = matchResult.nextSolution(); matchNode = scoreSolution.get(matchAttribute); //TODO Nicholas: paperNode must currently be 'x'; howto abstract? paperNode = scoreSolution.get("x"); //TODO Nicholas: paperResource must currently be 'x'; howto abstract? paperResource = scoreSolution.getResource("x"); scoreMatch = matchNode.toString(); log.info("\nChecking for " + scoreMatch + " from " + paperNode.toString() + " in VIVO"); //Select all matching attributes from vivo store queryString = "PREFIX core: <http://vivoweb.org/ontology/core#> " + "SELECT ?x " + - "WHERE { ?x " + coreAttribute + " \"" + scoreMatch + "\"}"; + "WHERE { ?x " + coreAttribute + " \"" + scoreMatch + "\" }"; log.debug(queryString); //TODO Nicholas: how to combine result sets? not possible in JENA vivoResult = executeQuery(matched, queryString); - commitResultSet(output,vivoResult,paperResource,paperNode,matchNode); + //while (vivoResult.hasNext()) { + // System.out.println(vivoResult.toString()); + //} + + commitResultSet(output,vivoResult,paperResource,matchNode,paperNode); } //TODO Nicholas: return scoreInput minus the scored statements return output; } }
false
false
null
null
diff --git a/src/org/rascalmpl/test/ConcreteSyntaxTests.java b/src/org/rascalmpl/test/ConcreteSyntaxTests.java index 470e8146f0..67ca50a9ee 100644 --- a/src/org/rascalmpl/test/ConcreteSyntaxTests.java +++ b/src/org/rascalmpl/test/ConcreteSyntaxTests.java @@ -1,766 +1,766 @@ package org.rascalmpl.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Ignore; import org.junit.Test; import org.rascalmpl.interpreter.staticErrors.AmbiguousConcretePattern; import org.rascalmpl.interpreter.staticErrors.StaticError; import org.rascalmpl.interpreter.staticErrors.UndeclaredVariableError; public class ConcreteSyntaxTests extends TestFramework { @Test public void parseDS(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("parse(#DS, \"d d d\") == (DS)`d d d`;")); } @Test public void parseDSInModule(){ prepareModule("M", "module M " + "import GrammarABCDE;" + "public DS ds = (DS)`d d d`;" + "public DS parseDS(str input) { return parse(#DS, input); }"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("parseDS(\"d d d\") == ds;")); } @Test public void parseDSfromFile(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("parse(#DS, |cwd:///src/org/rascalmpl/test/data/DS.trm|) == (DS)`d d d`;")); } @Test public void singleA(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a` := `a`;")); } @Test public void singleAspaces1(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("` a ` := `a`;")); } @Test public void singleAspaces2(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a` := ` a `;")); } @Test public void singleATyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("(A)`a` := `a`;")); } @Test public void singleAUnquoted1(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("a := `a`;")); } @Test(expected=UndeclaredVariableError.class) public void singleAUnquoted2(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("a := a;")); } @Test public void AB(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a b` := `a b`;")); } @Test public void ABspaces1(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a b` := `a b`;")); } @Test public void ABspaces2(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a b` := ` a b `;")); } @Test(expected=AmbiguousConcretePattern.class) public void varAQuoted(){ prepare("import GrammarABCDE;"); runTestInSameEvaluator("`<someA>` := `a`;"); } @Test public void varAassign(){ prepare("import GrammarABCDE;"); runTestInSameEvaluator("{someA := `a` && someA == `a`;}"); } @Test public void varAQuotedTyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`<A someA>` := `a`;")); } @Test public void varAQuotedDeclaredBefore(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{A someA; (A)`<someA>` := `a`;}")); } public void VarATypedInsertAmbiguous(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `<A someA>` := `a` && someA == `a`; }")); } public void VarATypedInsert(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `<A someA>` := `a` && someA == `a`; }")); } @Test public void ABvars1(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a <someB>` := `a b`;")); } @Test public void ABvars1Typed(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a <B someB>` := `a b`;")); } - @Test(expected=AmbiguousConcretePattern.class) + @Test // (expected=AmbiguousConcretePattern.class) public void ABvars2(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`<someA> <someB>` := `a b`;")); } public void ABvars2Typed(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`<A someA> <B someB>` := `a b`;")); } @Test public void ABvars2TypedEq(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{`<A someA> <B someB>` := `a b` && someA ==`a` && someB == `b`;}")); } - @Test(expected=AmbiguousConcretePattern.class) + @Test // (expected=AmbiguousConcretePattern.class) public void ABvars2TypedInsertWithoutTypes(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `<A someA><B someB>` := `a b` && `<someA><someB>` == `a b`;}")); } @Test public void ABvars2TypedInsertWithTypes(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `<A someA><B someB>` := `a b` && (C)`<someA><someB>` == `a b`;}")); } @Test public void ABequal1(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a b` == `a b`;")); } @Test public void ABequal2(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a b` == ` a b`;")); } @Test public void ABequal3(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a b` == `a b `;")); } @Test public void ABequal4(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a b` == ` a b `;")); } @Test public void ABequal5(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a b` == `a b`;")); } @Test public void ABequal6(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`a b` == ` a b `;")); } @Test public void D1(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`d` := `d`;")); } @Test public void D2(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`d d` := `d d`;")); } public void D3(){ prepare("import GrammarABCDE;"); assertFalse(runTestInSameEvaluator("(DS)`d d` := `d d`;")); } public void D4(){ prepare("import GrammarABCDE;"); assertFalse(runTestInSameEvaluator("`d d` := (DS)`d d`;")); } @Test public void D5(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("(DS)`d d` := (DS)`d d`;")); } @Test(expected=AmbiguousConcretePattern.class) public void Dvars(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`<Xs>` := `d d`;")); } @Test public void DvarsTyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ D+ Xs := `d d` && Xs == ` d d `; }")); } @Test public void DvarsTypedInsert1(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ D+ Xs := `d d` && Xs == ` d d `; }")); } @Test public void DvarsTypedInsert2(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ (DS)`<D+ Xs>` := (DS)`d`; }")); } @Test public void DvarsTypedInsert3(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ (DS)`<D+ Xs>` := (DS)`d d`; }")); } @Test(expected=StaticError.class) public void DvarsTypedInsert2Untyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `<D+ Xs>` := `d`; }")); } @Test public void DvarsTypedInsert3Untyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `<D+ Xs>` := `d d`; }")); } @Test public void DvarsTypedInsert4UnTyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("(`d <D+ Xs>` := `d d`) && ` d <D+ Xs> ` == ` d d `;")); } @Test public void DvarsTypedInsert4(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("(DS)`d <D+ Xs>` := (DS)`d d` && (DS)` d <D+ Xs> ` == (DS)` d d `;")); } @Test public void DvarsTypedInsert5Untyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `d <D+ Xs>` := `d d d` && ` d <D+ Xs> ` == `d d d`; }")); } @Test public void DvarsTypedInsert5(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ (DS)`d <D+ Xs>` := (DS)`d d d` && (DS)` d <D+ Xs> ` == (DS)`d d d`; }")); } @Test public void E1(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`e` := `e`;")); } @Test public void E2(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`e, e` := `e, e`;")); } @Test public void E2spaces1(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`e, e` := `e , e`;")); } @Test public void E2spaces2(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`e, e` := `e , e`;")); } @Test public void Evars1(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ Xs := `e, e` && Xs == ` e, e`;}")); } @Test public void Evar1Typed(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ {E \",\"}+ Xs := `e, e` && Xs == ` e, e`;}")); } - @Test(expected=AmbiguousConcretePattern.class) + @Test // (expected=AmbiguousConcretePattern.class) public void Evars2(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `e, <Xs>` := `e, e` && Xs == ` e `;}")); } @Test public void NoStarSubjectToPlusVar(){ prepare("import GrammarABCDE;"); assertFalse(runTestInSameEvaluator("{E \",\"}+ Xs := ({E \",\"}*) ` `;")); } public void plusListShouldNotMatchEmptyList() { prepare("import GrammarABCDE;"); assertFalse(runTestInSameEvaluator("` e, <{E \",\"}+ Es> ` := ({E \",\"}+) ` e `;")); } @Test public void starListPatternShouldMatchPlusListSubject() { prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{E \",\"}* Zs := ({E \",\"}+) ` e, e `;")); } @Test public void plusListPatternShouldMatchPStarListSubjectIfNotEmpty() { prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{E \",\"}+ Zs := ({E \",\"}*) ` e, e `;")); } @Test public void plusListPatternShouldNotMatchPStarListSubjectIfEmpty() { prepare("import GrammarABCDE;"); assertFalse(runTestInSameEvaluator("{E \",\"}+ Zs := ({E \",\"}*) ` `;")); } @Test public void emptyListVariablePatternShouldBeSplicedInbetweenSeparators() { prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`e, <{E \",\"}* Xs>, e` := ` e, e `;")); } @Test public void emptyListVariablePatternShouldBeSplicedInbetweenSeparatorsAndBindToEmptyList() { prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("`e, <{E \",\"}* Xs>, e` := ` e, e ` && Xs == ({E \",\"}*) ` `;")); } @Test public void emptySepListShouldSpliceCorrectly(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{E \",\"}* Xs := ({E \",\"}*) ` ` && `e, <{E \",\"}* Xs>, e ` == ` e, e `;")); } @Test public void Evars2Typed(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `e, <{E \",\"}+ Xs>` := `e, e` && Xs == ({E \",\"}+) ` e `;}")); } - @Test(expected=AmbiguousConcretePattern.class) - @Ignore("needs to be reinstated when we have a type checker") + @Test // (expected=AmbiguousConcretePattern.class) + // @Ignore("needs to be reinstated when we have a type checker") public void Evars3(){ prepare("import GrammarABCDE;"); - assertTrue(runTestInSameEvaluator("{ `e, <Xs>` := `e, e` Xs == ` e ` && ` e, <Xs> ` == ` e, e`; }")); + assertTrue(runTestInSameEvaluator("{ `e, <Xs>` := `e, e` && Xs == ` e ` && ` e, <Xs> ` == ` e, e`; }")); } @Test public void Evars3Typed(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `e, <{E \",\"}+ Xs>` := `e, e` && Xs == ({E \",\"}+) ` e ` && ({E \",\"}+) ` e, <{E \",\"}+ Xs> ` == ` e, e`; }")); } - @Test(expected=AmbiguousConcretePattern.class) + @Test // (expected=AmbiguousConcretePattern.class) @Ignore("needs to be reinstated when we have a type checker") public void Evars4(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `e, <Xs>` := `e` && Xs == ` ` && ` e, <Xs> ` == ` e `; }")); } @Test public void EvarsTyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{E \",\"}+ Xs := `e, e`;")); } @Test public void EvarsTypedInsert1(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `<{E \",\"}+ Xs>` := `e, e` && ` e, <{E \",\"}+ Xs> ` == ` e, e, e `; }")); } @Test public void EvarsTypedInsert1Typed(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `<{E \",\"}+ Xs>` := `e, e` && ` e, <{E \",\"}+ Xs> ` == ` e, e, e `; }")); } @Test public void EvarsTypedInsert2(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ `<{E \",\"}+ Xs>` := `e, e` && ` e, <{E \",\"}+ Xs> ` == ` e, e, e `; }")); } @Test public void EvarsTypedInsert3(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{ ` e, <{E \",\"}+ Xs> ` := `e, e, e` && ` e, <{E \",\"}+ Xs> ` == ` e, e, e `; }")); } @Test public void sortsInGrammar(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{A vA; B vB; C vC; D vD; DS vDS; E vE; ES vES; {E \",\"}+ vES2; true;}")); } @Test public void enumeratorDs1Untyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{L = [X | X <- `d` ]; L == [`d`];}")); } @Test public void enumeratorDs1Typed(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{L = [X | D X <- `d` ]; L == [ `d` ];}")); } @Test public void enumeratorDsUnyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{L = [X | X <- `d d d` ]; L == [`d`, `d`, `d`];}")); } @Test public void enumeratorDsTyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{L = [X | D X <- `d d d` ]; L == [`d`, `d`, `d`];}")); } @Test public void enumeratorEs1Untyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{L = [X | X <- `e` ]; L == [ `e` ];}")); } @Test public void enumeratorEs1Typed(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{L = [X | E X <- `e` ]; L == [ `e` ];}")); } @Test public void enumeratorEsUntyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{L = [X | X <- `e, e, e` ]; L == [`e`, `e`, `e`];}")); } @Test public void enumeratorEsTyped(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("{L = [X | E X <- `e, e, e` ]; L == [`e`, `e`, `e`];}")); } @Test public void EvarsTypedInsert3Empty(){ prepare("import GrammarABCDE;"); assertTrue(runTestInSameEvaluator("` e, <{E \",\"}* Xs> ` := ({E \",\"}+) `e`;")); } @Test public void Pico1(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{t1 = `begin declare x: natural; x := 10 end`;true;}")); } @Test public void Pico2(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{PROGRAM P := `begin declare x: natural; x := 10 end`;}")); } @Test public void Pico3(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{`<PROGRAM P>` := `begin declare x: natural; x := 10 end`;}")); } @Test public void Pico4(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{`begin <decls> <stats> end` := `begin declare x: natural; x := 10 end`;}")); } @Test public void Pico5(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{`begin <DECLS decls> <{STATEMENT \";\"}* stats> end` := `begin declare x: natural; x := 10 end`;}")); } @Test public void Pico6(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{DECLS decls; {STATEMENT \";\"}* stats; `begin <decls> <stats> end` := `begin declare x: natural; x := 10 end`;}")); } @Test public void Pico7a(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{`begin <DECLS decls> <{STATEMENT \";\"}+ stats> end` := `begin declare x: natural; x := 1; x := 2 end` &&" + "(decls == `declare x: natural;`);}")); } @Test public void Pico7b(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{`begin <DECLS decls> <{STATEMENT \";\"}+ stats> end` := `begin declare x: natural; x := 1; x := 2 end` &&" + "(decls == `declare x: natural;`) && (stats == ({STATEMENT \";\"}+)`x := 1; x := 2`);}")); } @Test public void Pico7c(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{`begin <DECLS decls> <{STATEMENT \";\"}* stats> end` := `begin declare x: natural; x := 1; x := 2 end` &&" + "(decls == `declare x: natural;`) && (stats == ({STATEMENT \";\"}*)`x := 1; x := 2`);}")); } @Test public void Pico8(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{ bool B;" + " if(`begin <DECLS decls> <{STATEMENT \";\"}* stats> end` := `begin declare x: natural; x := 1; x := 2 end`){" + " B = (decls == `declare x: natural;`);" + " } else" + " B = false; " + " B;" + "}")); } private String QmoduleM = "module M\n" + "import languages::pico::syntax::Pico;\n" + "public Tree t1 = `begin declare x: natural; x := 10 end`;\n" + "public Tree t2 = `declare x : natural;`;\n"; @Test public void PicoQuoted0() { prepareModule("M", QmoduleM + "public bool match1() { return `<PROGRAM program>` := t1; }\n"); } @Test public void PicoQuoted1(){ prepareModule("M", QmoduleM + "public bool match1() { return `<PROGRAM program>` := t1; }\n"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match1();")); } @Test public void PicoQuoted2(){ prepareModule("M", QmoduleM + "public bool match2() { return PROGRAM program := t1; }\n"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match2();")); } @Test public void PicoQuoted3(){ prepareModule("M", QmoduleM + "public bool match3() { return `begin <decls> <stats> end` := t1; }\n"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match3();")); } @Test public void PicoQuoted4(){ prepareModule("M", QmoduleM + "public bool match4() { return `begin <DECLS decls> <stats> end` := t1; }"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match4();")); } @Test public void PicoQuoted5(){ prepareModule("M", QmoduleM + "public bool match5() { return `begin <decls> <{STATEMENT \";\"}* stats> end` := t1; }"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match5();")); } @Test public void PicoQuoted6(){ prepareModule("M", QmoduleM + "public bool match6() { return `begin <DECLS decls> <{STATEMENT \";\"}* stats> end` := t1; }"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match6();")); } @Test public void PicoQuoted7(){ prepareModule("M", QmoduleM + "public bool match7() { return ` begin declare <{\\ID-TYPE \",\" }* decls>; <{STATEMENT \";\"}* Stats> end ` := t1; }"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match7();")); } @Test public void PicoQuoted8(){ prepareModule("M", QmoduleM + "public bool match8() { return ` declare <{\\ID-TYPE \",\" }* decls>; ` := t2; }"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match8();")); } private String UQmoduleM = "module M\n" + "import languages::pico::syntax::Pico;\n" + "public Tree t1 = begin declare x: natural; x := 10 end;\n"; @Test(expected=StaticError.class) // Directly antiquoting without quotes not allowed. public void PicoUnQuoted1(){ prepareModule("M", UQmoduleM + "public bool match1() { return <PROGRAM program> := t1; }\n"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match1();")); } @Test public void PicoUnQuoted2(){ prepareModule("M", UQmoduleM + "public bool match2() { return PROGRAM program := t1; }\n"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match2();")); } @Test public void PicoUnQuoted3(){ prepareModule("M", UQmoduleM + "public bool match3() { return begin <decls> <stats> end := t1; }\n"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match3();")); } @Test public void PicoUnQuoted4(){ prepareModule("M", UQmoduleM + "public bool match4() { return begin <DECLS decls> <stats> end := t1; }"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match4();")); } @Test public void PicoUnQuoted5(){ prepareModule("M", UQmoduleM + "public bool match5() { return begin <decls> <{STATEMENT \";\"}* stats> end := t1; }"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match5();")); } @Test public void PicoUnQuoted6(){ prepareModule("M", UQmoduleM + "public bool match6() { return begin <DECLS decls> <{STATEMENT \";\"}* stats> end := t1; }"); prepareMore("import M;"); assertTrue(runTestInSameEvaluator("match6();")); } @Test public void enumeratorPicoStatement1Untyped(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{L = [X | X <- `a:=1` ]; L == [ `a:=1` ];}")); } @Test public void enumeratorPicoStatement1Typed(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{L = [X | STATEMENT X <- `a:=1` ]; L == [ `a:=1` ];}")); } @Test public void enumeratorPicoStatementsUntyped(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{L = [X | X <- `a:=1;a:=2;a:=3` ]; L == [`a:=1`, `a:=2`, `a:=3`];}")); } @Test public void enumeratorPicoStatementsTyped(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{L = [X | STATEMENT X <- `a:=1;a:=2;a:=3` ]; L == [`a:=1`, `a:=2`, `a:=3`];}")); } @Test public void enumeratorPicoStatementsConcretePattern1(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{L = [X | `<\\PICO-ID X>:=1` <- `a:=1;b:=2;c:=1` ]; L == [ `a`, `c` ];}")); } @Test public void enumeratorPicoStatementsConcretePattern2(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{L = [X | /`b:=<EXP X>` <- `a:=1;b:=2;c:=3` ]; L == [ (EXP)`2` ];}")); } @Test public void enumeratorPicoStatementsConcretePattern3(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{L = [Id | /`<\\PICO-ID Id> : <TYPE Tp>` <- `x : natural, y : string` ]; L == [ `x`, `y` ];}")); } @Test public void enumeratorPicoStatementsConcretePattern4(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{L = []; for(/`<\\PICO-ID Id> : <TYPE Tp>` <- `x : natural, y : string`){L += Id;} L == [ `x`, `y` ];}")); } @Test public void forPicoStatementsTyped1(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{L = [X | /STATEMENT X <- `a:=1;a:=2;a:=3` ]; L == [`a:=1`, `a:=2`, `a:=3`];}")); } @Test public void forPicoStatementsTyped2(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{L = [X | /STATEMENT X <- `begin declare a : natural; a:=1;a:=2;a:=3 end` ]; L == [`a:=1`, `a:=2`, `a:=3`];}")); } @Test public void forPicoStatementsTyped3(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{L = [X | /EXP X <- `begin declare a : natural; a:=1;b:=2;c:=3 end` ]; L == [(EXP)`1`, (EXP)`2`, (EXP)`3` ];}")); } @Test public void PicoStringDoesNotOverrideRascalString1(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{str s = \"abc\"; s == \"abc\";}")); } @Test public void PicoStringDoesNotOverrideRascalString2(){ prepare("import languages::pico::syntax::Pico;"); assertTrue(runTestInSameEvaluator("{int n = 3; s = \"abc<n>\"; s == \"abc3\";}")); } } diff --git a/src/org/rascalmpl/test/PatternTests.java b/src/org/rascalmpl/test/PatternTests.java index edb4dc2a21..ae50ad7a82 100644 --- a/src/org/rascalmpl/test/PatternTests.java +++ b/src/org/rascalmpl/test/PatternTests.java @@ -1,965 +1,965 @@ package org.rascalmpl.test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Ignore; import org.junit.Test; import org.rascalmpl.interpreter.staticErrors.RedeclaredVariableError; import org.rascalmpl.interpreter.staticErrors.StaticError; import org.rascalmpl.interpreter.staticErrors.UndeclaredVariableError; import org.rascalmpl.interpreter.staticErrors.UnexpectedTypeError; public class PatternTests extends TestFramework { @Test(expected=StaticError.class) public void cannotMatchListStr(){ assertFalse(runTest("[1] := \"a\";")); } @Test public void matchList1() { assertFalse(runTest("[] := [2];")); assertFalse(runTest("[1] := [];")); assertTrue(runTest("[] := [];")); assertTrue(runTest("[1] := [1];")); assertTrue(runTest("[1,2] := [1,2];")); assertFalse(runTest("[1] := [2];")); assertFalse(runTest("[1,2] := [1,2,3];")); assertTrue(runTest("([int N] := [1]) && (N == 1);")); assertTrue(runTest("[ _ ] := [1];")); assertTrue(runTest("([int N, 2, int M] := [1,2,3]) && (N == 1) && (M==3);")); assertTrue(runTest("[ _, 2, _] := [1,2,3];")); assertTrue(runTest("([int N, 2, N] := [1,2,1]) && (N == 1);")); assertFalse(runTest("([int N, 2, N] := [1,2,3]);")); assertFalse(runTest("([int N, 2, N] := [1,2,\"a\"]);")); assertTrue(runTest("{int N = 1; ([N, 2, int M] := [1,2,3]) && (N == 1) && (M==3);}")); assertFalse(runTest("{int N = 1; ([N, 2, int M] := [4,2,3]);}")); assertTrue(runTest("{list[int] L = [3]; [1,2,L] := [1,2,3];}")); assertTrue(runTest("{list[int] L = [2, 3]; [1, L] := [1,2,3];}")); assertTrue(runTest("[1, [2, 3], 4] := [1, [2, 3], 4];")); assertFalse(runTest("[1, [2, 3], 4] := [1, [2, 3, 4], 4];")); assertTrue(runTest("([list[int] L] := []) && (L == []);")); assertTrue(runTest("{ list[int] X = []; ([list[int] L] := X) && (L == []); }")); assertTrue(runTest("([list[int] L] := ([1] - [1])) && (L == []);")); assertTrue(runTest("([list[int] L] := [1]) && (L == [1]);")); assertTrue(runTest("([list[int] L] := [1,2]) && (L == [1,2]);")); assertTrue(runTest("([1, list[int] L] := [1]) && (L == []);")); assertTrue(runTest("([1, list[int] L] := [1, 2]) && (L == [2]);")); assertTrue(runTest("([1, list[int] L] := [1, 2, 3]) && (L == [2, 3]);")); assertTrue(runTest("([list[int] L, 10] := [10]) && (L == []);")); assertTrue(runTest("([list[int] L, 10] := [1,10]) && (L == [1]);")); assertTrue(runTest("([list[int] L, 10] := [1,2,10]) && (L == [1,2]);")); assertTrue(runTest("([1, list[int] L, 10] := [1,10]) && (L == []);")); assertTrue(runTest("([1, list[int] L, 10] := [1,2,10]) && (L == [2]);")); assertTrue(runTest("([1, list[int] L, 10, list[int] M, 20] := [1,10,20]) && (L == []) && (M == []);")); assertTrue(runTest("([1, list[int] L, 10, list[int] M, 20] := [1,2,10,20]) && (L == [2]) && (M == []);")); assertTrue(runTest("([1, list[int] L, 10, list[int] M, 20] := [1,2,10,3,20]) && (L == [2]) && (M==[3]);")); assertTrue(runTest("([1, list[int] L, 10, list[int] M, 20] := [1,2,3,10,4,5,20]) && (L == [2,3]) && (M==[4,5]);")); assertTrue(runTest("([1, list[int] L, 10, L, 20] := [1,2,3,10,2,3,20]) && (L == [2,3]);")); assertFalse(runTest("([1, list[int] L, 10, L, 20] := [1,2,3,10,2,4,20]);")); assertTrue(runTest("[list[int] _] := [];")); assertTrue(runTest("[list[int] _] := [1];")); assertTrue(runTest("[list[int] _] := [1,2];")); assertTrue(runTest("([1, list[int] _, 10, list[int] _, 20] := [1,2,10,20]);")); // assertTrue(runTest("([1, list[int] L, [10, list[int] M, 100], list[int] N, 1000] := [1, [10,100],1000]);")); } @Test public void matchExternalListVars(){ assertTrue(runTest("{int n; n := 3 && n == 3; }")); assertTrue(runTest("{list[int] L; ([1, L, 4, 5] := [1, 2, 3, 4, 5] && L == [2, 3]);}")); } @Test public void matchListMultiVars(){ assertTrue(runTest("{[1, L*, 4, 5] := [1, 2, 3, 4, 5] && L == [2, 3];}")); assertTrue(runTest("{[1, _*, 4, 5] := [1, 2, 3, 4, 5];}")); assertTrue(runTest("{[1, L*, 4, L, 5] := [1, 2, 3, 4, 2, 3, 5] && L == [2, 3];}")); } @Test public void matchSetMultiVars(){ assertTrue(runTest("{{1, S*, 4, 5}:= {1, 2, 3, 4, 5} && S == {2, 3};}")); assertTrue(runTest("{{1, _*, 4, 5} := {1, 2, 3, 4, 5};}")); } @Test(expected=UndeclaredVariableError.class) public void unguardedMatchNoEscape() { // m should not be declared after the unguarded pattern match. assertTrue(runTest("{int n = 3; int m := n; m == n; }")); } @Test public void matchListHasOrderedElement() { prepare("import ListMatchingTests;"); assertTrue(runTestInSameEvaluator("hasOrderedElement([]) == false;")); assertTrue(runTestInSameEvaluator("hasOrderedElement([1]) == false;")); assertTrue(runTestInSameEvaluator("hasOrderedElement([1,2]) == false;")); assertTrue(runTestInSameEvaluator("hasOrderedElement([1,2,1]) == true;")); assertTrue(runTestInSameEvaluator("hasOrderedElement([1,2,3,4,3,2,1]) == true;")); } @Test public void matchListHasDuplicateElement() { prepare("import ListMatchingTests;"); assertTrue(runTestInSameEvaluator("hasDuplicateElement([]) == false;")); assertTrue(runTestInSameEvaluator("hasDuplicateElement([1]) == false;")); assertTrue(runTestInSameEvaluator("hasDuplicateElement([1,2]) == false;")); assertTrue(runTestInSameEvaluator("hasDuplicateElement([1,1]) == true;")); assertTrue(runTestInSameEvaluator("hasDuplicateElement([1,2,3]) == false;")); assertTrue(runTestInSameEvaluator("hasDuplicateElement([1,2,3,1]) == true;")); assertTrue(runTestInSameEvaluator("hasDuplicateElement([1,2,3,2]) == true;")); assertTrue(runTestInSameEvaluator("hasDuplicateElement([1,2,3,3]) == true;")); } @Test public void matchListIsDuo1() { prepare("import ListMatchingTests;"); assertTrue(runTestInSameEvaluator("isDuo1([]) == true;")); assertTrue(runTestInSameEvaluator("isDuo1([1]) == false;")); assertTrue(runTestInSameEvaluator("isDuo1([1,1]) == true;")); assertTrue(runTestInSameEvaluator("isDuo1([1,2]) == false;")); assertTrue(runTestInSameEvaluator("isDuo1([1,2, 1]) == false;")); assertTrue(runTestInSameEvaluator("isDuo1([1,2, 1,2]) == true;")); assertTrue(runTestInSameEvaluator("isDuo1([1,2,3, 1,2]) == false;")); assertTrue(runTestInSameEvaluator("isDuo1([1,2,3, 1,2, 3]) == true;")); } @Test public void matchListIsDuo2() { prepare("import ListMatchingTests;"); assertTrue(runTestInSameEvaluator("isDuo2([]) == true;")); assertTrue(runTestInSameEvaluator("isDuo2([1]) == false;")); assertTrue(runTestInSameEvaluator("isDuo2([1,1]) == true;")); assertTrue(runTestInSameEvaluator("isDuo2([1,2]) == false;")); assertTrue(runTestInSameEvaluator("isDuo2([1,2, 1]) == false;")); assertTrue(runTestInSameEvaluator("isDuo2([1,2, 1,2]) == true;")); assertTrue(runTestInSameEvaluator("isDuo2([1,2,3, 1,2]) == false;")); assertTrue(runTestInSameEvaluator("isDuo2([1,2,3, 1,2, 3]) == true;")); } @Test public void matchListIsDuo3() { prepare("import ListMatchingTests;"); assertTrue(runTestInSameEvaluator("isDuo3([]) == true;")); assertTrue(runTestInSameEvaluator("isDuo3([1]) == false;")); assertTrue(runTestInSameEvaluator("isDuo3([1,1]) == true;")); assertTrue(runTestInSameEvaluator("isDuo3([1,2]) == false;")); assertTrue(runTestInSameEvaluator("isDuo3([1,2, 1]) == false;")); assertTrue(runTestInSameEvaluator("isDuo3([1,2, 1,2]) == true;")); assertTrue(runTestInSameEvaluator("isDuo3([1,2,3, 1,2]) == false;")); assertTrue(runTestInSameEvaluator("isDuo3([1,2,3, 1,2, 3]) == true;")); } @Test public void matchListIsTrio1() { prepare("import ListMatchingTests;"); assertTrue(runTestInSameEvaluator("isTrio1([]) == true;")); assertTrue(runTestInSameEvaluator("isTrio1([1]) == false;")); assertTrue(runTestInSameEvaluator("isTrio1([1,1]) == false;")); assertTrue(runTestInSameEvaluator("isTrio1([1,1,1]) == true;")); assertTrue(runTestInSameEvaluator("isTrio1([2,1,1]) == false;")); assertTrue(runTestInSameEvaluator("isTrio1([1,2,1]) == false;")); assertTrue(runTestInSameEvaluator("isTrio1([1,1,2]) == false;")); assertTrue(runTestInSameEvaluator("isTrio1([1,2, 1,2, 1,2]) == true;")); } @Test public void matchListIsTrio2() { prepare("import ListMatchingTests;"); assertTrue(runTestInSameEvaluator("isTrio2([]) == true;")); assertTrue(runTestInSameEvaluator("isTrio2([1]) == false;")); assertTrue(runTestInSameEvaluator("isTrio2([1,1]) == false;")); assertTrue(runTestInSameEvaluator("isTrio2([1,1,1]) == true;")); assertTrue(runTestInSameEvaluator("isTrio2([2,1,1]) == false;")); assertTrue(runTestInSameEvaluator("isTrio2([1,2,1]) == false;")); assertTrue(runTestInSameEvaluator("isTrio2([1,1,2]) == false;")); assertTrue(runTestInSameEvaluator("isTrio2([1,2, 1,2, 1,2]) == true;")); } @Test public void matchListIsTrio3() { prepare("import ListMatchingTests;"); assertTrue(runTestInSameEvaluator("isTrio3([]) == true;")); assertTrue(runTestInSameEvaluator("isTrio3([1]) == false;")); assertTrue(runTestInSameEvaluator("isTrio3([1,1]) == false;")); assertTrue(runTestInSameEvaluator("isTrio3([1,1,1]) == true;")); assertTrue(runTestInSameEvaluator("isTrio3([2,1,1]) == false;")); assertTrue(runTestInSameEvaluator("isTrio3([1,2,1]) == false;")); assertTrue(runTestInSameEvaluator("isTrio3([1,1,2]) == false;")); assertTrue(runTestInSameEvaluator("isTrio3([1,2, 1,2, 1,2]) == true;")); } @Test public void matchList3() { prepare("data DATA = a() | b() | c() | d() | e(int N) | f(list[DATA] S);"); assertTrue(runTestInSameEvaluator("[a(), b()] := [a(), b()];")); assertTrue(runTestInSameEvaluator("([DATA X1, b()] := [a(), b()]) && (X1 == a());")); assertFalse(runTestInSameEvaluator("([DATA X2, DATA Y, c()] := [a(), b()]);")); assertTrue(runTestInSameEvaluator("([e(int X3), b()] := [e(3), b()]) && (X3 == 3);")); assertTrue(runTestInSameEvaluator("([e(int X4)] := [e(3)]) && (X4 == 3);")); assertFalse(runTestInSameEvaluator("([e(int X5)] := [a()]);")); assertTrue(runTestInSameEvaluator("([a(), f([a(), b(), DATA X6])] := [a(), f([a(),b(),c()])]) && (X6 == c());")); assertTrue(runTestInSameEvaluator("([a(), f([a(), b(), DATA X7]), list[DATA] Y7] := [a(), f([a(),b(),c()]), b()]) && (X7 == c() && Y7 == [b()]);")); assertTrue(runTestInSameEvaluator("([DATA A1, f([A1, b(), DATA X8])] := [a(), f([a(),b(),c()])]) && (A1 == a());")); assertTrue(runTestInSameEvaluator("([DATA A2, f([A2, b(), list[DATA] SX1]), SX1] := [a(), f([a(),b(),c()]), c()]) && (A2 == a()) && (SX1 ==[c()]);")); assertFalse(runTestInSameEvaluator("([DATA A3, f([A3, b(), list[DATA] SX2]), SX2] := [d(), f([a(),b(),c()]), a()]);")); assertFalse(runTestInSameEvaluator("([DATA A4, f([A4, b(), list[DATA] SX3]), SX3] := [c(), f([a(),b(),c()]), d()]);")); } @Ignore @Test(expected=StaticError.class) public void recursiveDataTypeNoPossibleMatchVertical() { prepare("data Bool = and(Bool, Bool) | t;"); runTestInSameEvaluator("t := and(t,t);"); } @Test(expected=StaticError.class) public void recursiveDataTypeNoPossibleMatchHorizontal() { prepare("data Bool = and(Bool, Bool) | t;"); prepareMore("data Prop = or(Prop, Prop) | f;"); runTestInSameEvaluator("Prop p := and(t,t);"); } @Ignore @Test(expected=StaticError.class) public void recursiveDataTypeNoPossibleHiddenRecursion() { prepare("data Prop = f;"); prepareMore("data Bool = and(list[Prop], list[Prop]) | t;"); prepareMore("data Prop = or(Bool, Bool);"); runTestInSameEvaluator("{p = or(t,t); and(t,t) := p;}"); } @Test(expected=RedeclaredVariableError.class) public void matchListError12() { runTest("{list[int] x = [1,2,3]; [1, list[int] L, 2, list[int] L] := x;}"); } public void matchListError1() { assertTrue(runTest("{list[int] x = [1,2,3]; [1, list[int] L, 2, list[int] M] := x;}")); } public void matchListError11() { assertFalse(runTest("[1, list[int] L, 2, list[int] L] := [1,2,3];")); } public void matchListError2() { assertFalse(runTest("[1, list[str] L, 2] := [1,2,3];")); } @Test(expected=UnexpectedTypeError.class) public void matchListError22() { runTest("{ list[int] l = [1,2,3]; [1, list[str] L, 2] := l; }"); } @Test public void matchListFalse3() { assertFalse(runTest("{ list[value] l = [1,2,3]; [1, str S, 2] := l;}")); } @Test(expected=StaticError.class) public void matchListError3() { runTest("{ list[int] x = [1,2,3] ; [1, str S, 2] := x;}"); } public void matchListError4() { assertFalse(runTest("{str S = \"a\"; [1, S, 2] := [1,2,3];}")); } @Test(expected=StaticError.class) public void matchListError42() { runTest("{str S = \"a\"; list[int] x = [1,2,3]; [1, S, 2] := x;}"); } public void matchListError5() { assertFalse(runTest("{list[str] S = [\"a\"]; [1, S, 2] := [1,2,3];}")); } @Test(expected=StaticError.class) public void matchListError55() { runTest("{list[str] S = [\"a\"]; list[int] x = [1,2,3]; [1, S, 2] := x;}"); } @Test public void matchListExternalVar() { runTest("{list[int] S; [1, S, 2] := [1,2,3] && S == [3];}"); } @Test public void matchListSet() { prepare("data DATA = a() | b() | c() | d() | e(int N) | f(list[DATA] S) | f(set[DATA] S);"); assertTrue(runTestInSameEvaluator("[a(), b()] := [a(), b()];")); assertTrue(runTestInSameEvaluator("([DATA X1, b()] := [a(), b()]) && (X1 == a());")); assertFalse(runTestInSameEvaluator("([DATA X2, DATA Y2, c()] := [a(), b()]);")); assertTrue(runTestInSameEvaluator("([e(int X3), b()] := [e(3), b()]) && (X3 == 3);")); assertTrue(runTestInSameEvaluator("([e(int X4)] := [e(3)]) && (X4 == 3);")); assertFalse(runTestInSameEvaluator("([e(int X5)] := [a()]);")); assertTrue(runTestInSameEvaluator("([a(), f({a(), b(), DATA X6})] := [a(), f({a(),b(),c()})]) && (X6 == c());")); assertTrue(runTestInSameEvaluator("({a(), f([a(), b(), DATA X7])} := {a(), f([a(),b(),c()])}) && (X7 == c());")); assertTrue(runTestInSameEvaluator("([a(), f({a(), b(), DATA X8}), list[DATA] Y8] := [a(), f({a(),b(),c()}), b()]) && (X8 == c() && Y8 == [b()]);")); assertTrue(runTestInSameEvaluator("({a(), f([a(), b(), DATA X9]), set[DATA] Y9} := {a(), f([a(),b(),c()]), b()}) && (X9 == c() && Y9 == {b()});")); assertTrue(runTestInSameEvaluator("([DATA A1, f({A1, b(), DATA X10})] := [a(), f({a(),b(),c()})]) && (A1 == a());")); assertTrue(runTestInSameEvaluator("({DATA A2, f([A2, b(), DATA X11])} := {a(), f([a(),b(),c()])}) && (A2 == a());")); } @Test(expected=StaticError.class) public void matchBoolIntError1(){ assertFalse(runTest("true := 1;")); } @Test(expected=StaticError.class) public void matchBoolIntError2(){ assertFalse(runTest("1 := true;")); } @Test(expected=StaticError.class) public void noMatchBoolIntError1(){ assertTrue(runTest("true !:= 1;")); } @Test(expected=StaticError.class) public void noMatchBoolIntError2(){ assertTrue(runTest("1 !:= true;")); } @Test(expected=StaticError.class) public void matchStringBoolError1(){ assertFalse(runTest("\"abc\" := true;")); } @Test(expected=StaticError.class) public void matchStringBoolError2(){ assertFalse(runTest("true := \"abc\";")); } @Test(expected=StaticError.class) public void noMatchStringBoolError1(){ assertTrue(runTest("\"abc\" !:= true;")); } @Test(expected=StaticError.class) public void noMatchStringBoolError2(){ assertTrue(runTest("true !:= \"abc\";")); } @Test(expected=StaticError.class) public void matchStringIntError1(){ assertFalse(runTest("\"abc\" := 1;")); } @Test(expected=StaticError.class) public void matchStringIntError2(){ assertFalse(runTest("1 := \"abc\";")); } @Test(expected=StaticError.class) public void noMatchStringIntError1(){ assertTrue(runTest("\"abc\" !:= 1;")); } @Test(expected=StaticError.class) public void noMatchStringIntError2(){ assertTrue(runTest("1 !:= \"abc\";")); } @Test(expected=StaticError.class) public void matchStringRealError1(){ assertFalse(runTest("\"abc\" := 1.5;")); } @Test(expected=StaticError.class) public void matchStringRealError2(){ assertFalse(runTest("1.5 := \"abc\";")); } @Test(expected=StaticError.class) public void noMatchStringRealError1(){ assertTrue(runTest("\"abc\" !:= 1.5;")); } @Test(expected=StaticError.class) public void noMatchStringRealError2(){ assertTrue(runTest("1.5 !:= \"abc\";")); } @Test(expected=StaticError.class) public void matchIntRealError1(){ assertFalse(runTest("2 := 1.5;")); } @Test(expected=StaticError.class) public void matchIntRealError2(){ assertFalse(runTest("1.5 := 2;")); } @Test(expected=StaticError.class) public void noMatchIntRealError1(){ assertTrue(runTest("2 !:= 1.5;")); } @Test(expected=StaticError.class) public void noMatchIntRealError2(){ assertTrue(runTest("1.5 !:= 2;")); } @Test public void matchLiteral() { assertTrue(runTest("true := true;")); assertFalse(runTest("true := false;")); assertTrue(runTest("true !:= false;")); assertTrue(runTest("1 := 1;")); assertFalse(runTest("2 := 1;")); assertTrue(runTest("2 !:= 1;")); assertTrue(runTest("1.5 := 1.5;")); assertFalse(runTest("2.5 := 1.5;")); assertTrue(runTest("2.5 !:= 1.5;")); assertFalse(runTest("1.0 := 1.5;")); assertTrue(runTest("1.0 !:= 1.5;")); assertTrue(runTest("\"abc\" := \"abc\";")); assertFalse(runTest("\"def\" := \"abc\";")); assertTrue(runTest("\"def\" !:= \"abc\";")); } @Test(expected=StaticError.class) public void matchADTStringError1(){ prepare("data F = f(int N) | f(int N, int M) | f(int N, value f, bool B) | g(str S);"); assertFalse(runTestInSameEvaluator("f(1) := \"abc\";")); } @Test(expected=StaticError.class) public void matchADTStringError2(){ prepare("data F = f(int N) | f(int N, int M) | f(int N, value f, bool B) | g(str S);"); assertFalse(runTestInSameEvaluator("\"abc\" := f(1);")); } @Test(expected=StaticError.class) public void noMatchADTStringError1(){ prepare("data F = f(int N) | f(int N, int M) | f(int N, value f, bool B) | g(str S);"); assertTrue(runTestInSameEvaluator("f(1) !:= \"abc\";")); } @Test(expected=StaticError.class) public void noMatchADTStringError2(){ prepare("data F = f(int N) | f(int N, int M) | f(int N, value f, bool B) | g(str S);"); assertTrue(runTestInSameEvaluator("\"abc\" !:= f(1);")); } @Test public void matchNode() { prepare("data F = f(int N) | f(int N, int M) | f(int N, value f, bool B) | g(str S);"); assertTrue(runTestInSameEvaluator("f(1) := f(1);")); assertTrue(runTestInSameEvaluator("f(1, g(\"abc\"), true) := f(1, g(\"abc\"), true);")); assertFalse(runTestInSameEvaluator("g(1) := f(1);")); assertTrue(runTestInSameEvaluator("g(1) !:= f(1);")); assertFalse(runTestInSameEvaluator("f(1, 2) := f(1);")); assertTrue(runTestInSameEvaluator("f(1, 2) !:= f(1);")); assertTrue(runTestInSameEvaluator("f(_) := f(1);")); assertTrue(runTestInSameEvaluator("f(_,_) := f(1,2);")); assertTrue(runTestInSameEvaluator("f(_,_,_) := f(1,2.5,true);")); } @Ignore @Test(expected=StaticError.class) public void NoDataDecl(){ runTest("f(1) := 1;"); } @Test(expected=StaticError.class) public void matchSetStringError(){ assertFalse(runTest("{1} := \"a\";")); } @Test public void matchSet1() { assertTrue(runTest("{} := {};")); assertTrue(runTest("{1} := {1};")); assertTrue(runTest("{1, 2} := {1, 2};")); assertTrue(runTest("{int _} := {1};")); assertTrue(runTest("{int _, int _} := {1, 2};")); assertTrue(runTest("{_} := {1};")); assertTrue(runTest("{_, _} := {1, 2};")); assertFalse(runTest("{_} := {1, 2};")); assertFalse(runTest("{_, _} := {1};")); assertFalse(runTest("{_, _} := {1, 2, 3};")); assertFalse(runTest("{_, _, _} := {1, 2};")); assertFalse(runTest("{} := {1};")); assertFalse(runTest("{1} := {2};")); assertFalse(runTest("{1,2} := {1,3};")); assertTrue(runTest("{ {set[int] X} := {} && X == {};}")); assertTrue(runTest("{ {set[int] X} := {1} && X == {1};}")); assertTrue(runTest("{ {set[int] X} := {1,2} && X == {1,2};}")); assertTrue(runTest("{ {Y*} := {1,2} && Y == {1,2};}")); //TODO: Test related to + multivariables are commented out since they are not yet supported by //the Rascal syntax // assertTrue(runTest("{ {Y+} := {1,2} && Y == {1,2};}")); assertTrue(runTest("{ {set[int] _} := {1,2}; }")); assertTrue(runTest("{ {_*} := {1,2}; }")); // assertTrue(runTest("{ {_+} := {1,2}; }")); assertTrue(runTest("({int N, 2, N} := {1,2}) && (N == 1);")); assertFalse(runTest("({int N, 2, N} := {1,2,3});")); assertFalse(runTest("({int N, 2, N} := {1,2,\"a\"});")); assertTrue(runTest("{int N = 3; {N, 2, 1} := {1,2,3};}")); assertTrue(runTest("{set[int] S = {3}; {S, 2, 1} := {1,2,3};}")); assertTrue(runTest("{set[int] S = {2, 3}; {S, 1} := {1,2,3};}")); assertTrue(runTest("{ {1, set[int] X, 2} := {1,2} && X == {};}")); assertTrue(runTest("{ {1, X*, 2} := {1,2} && X == {};}")); assertTrue(runTest("{ {1, _*, 2} := {1,2};}")); // assertFalse(runTest("{ {1, X+, 2} := {1,2};}")); - assertFalse(runTest("{ {1, _+, 2} := {1,2};}")); +// assertFalse(runTest("{ {1, _+, 2} := {1,2};}")); _+ does not exist yet assertTrue(runTest("{ {1, X*, 2} := {1,2} && X == {};}")); assertFalse(runTest("{ {1, X*, 2} := {1,3};}")); assertFalse(runTest("{ {1, _*, 2} := {1,3};}")); assertTrue(runTest("{ {1, set[int] X, 2} := {1,2,3} && X == {3};}")); assertTrue(runTest("{ {1, X*, 2} := {1,2,3} && X == {3};}")); // assertTrue(runTest("{ {1, X+, 2} := {1,2,3} && X == {3};}")); assertTrue(runTest("{ {1, _*, 2} := {1,2,3};}")); // assertTrue(runTest("{ {1, _+, 2} := {1,2,3};}")); assertTrue(runTest("{ {1, set[int] X, 2} := {1,2,3,4} && X == {3,4};}")); assertTrue(runTest("{ {set[int] X, set[int] Y} := {} && X == {} && Y == {};}")); assertTrue(runTest("{ {1, set[int] X, set[int] Y} := {1} && X == {} && Y == {};}")); assertTrue(runTest("{ {set[int] X, 1, set[int] Y} := {1} && X == {} && Y == {};}")); assertTrue(runTest("{ {set[int] X, set[int] Y, 1} := {1} && X == {} && Y == {};}")); assertFalse(runTest("{ {set[int] X, set[int] Y, 1} := {2};}")); assertFalse(runTest("{ {X*, Y*, 1} := {2};}")); assertTrue(runTest("{ {set[int] X, set[int] Y} := {1} && ((X == {} && Y == {1}) || (X == {1} && Y == {}));}")); assertTrue(runTest("{ {X*, Y*} := {1} && ((X == {} && Y == {1}) || (X == {1} && Y == {}));}")); assertTrue(runTest("{ {set[int] X, set[int] Y, set[int] Z} := {} && X == {} && Y == {} && Z == {};}")); assertTrue(runTest("{ {X*, Y*, Z*} := {} && X == {} && Y == {} && Z == {};}")); assertTrue(runTest("{ {set[int] X, set[int] Y, set[int] Z} := {1} && (X == {1} && Y == {} && Z == {}) || (X == {} && Y == {1} && Z == {}) || (X == {} && Y == {} && Z == {1});}")); assertTrue(runTest("{ {X*, Y*, Z*} := {1} && (X == {1} && Y == {} && Z == {}) || (X == {} && Y == {1} && Z == {}) || (X == {} && Y == {} && Z == {1});}")); assertTrue(runTest("{ {int X, set[int] Y} := {1} && X == 1 && Y == {};}")); assertTrue(runTest("{ {set[int] X, int Y} := {1} && X == {} && Y == 1;}")); assertTrue(runTest("{ {X*, int Y} := {1} && X == {} && Y == 1;}")); // assertFalse(runTest("{ {X+, int Y} := {1};}")); assertTrue(runTest("{ {set[int] _, int _} := {1}; }")); assertTrue(runTest("{ {_*, int _} := {1}; }")); assertTrue(runTest("{ {_*, _} := {1}; }")); // assertFalse(runTest("{ {_+, _} := {1}; }")); assertTrue(runTest("{ {set[int] X, int Y} := {1, 2} && (X == {1} && Y == 2) || (X == {2} && Y == 1);}")); assertTrue(runTest("{ {X*, int Y} := {1, 2} && (X == {1} && Y == 2) || (X == {2} && Y == 1);}")); assertTrue(runTest("{ {set[int] X, int Y} := {1, 2} && (X == {1} && Y == 2) || (X == {2} && Y == 1);}")); assertTrue(runTest("{ {X*, Y*} := { 1, 5.5, 2, 6.5} && (X == {1,2} && Y == {5.5, 6.5});}")); assertTrue(runTest("{ set[int] x = {}; {} := x; }")); } @Test public void matchSet2() { prepare("data DATA = a() | b() | c() | d() | e(int N) | f(set[DATA] S);"); assertTrue(runTestInSameEvaluator("{a(), b()} := {a(), b()};")); assertTrue(runTestInSameEvaluator("({DATA X1, b()} := {a(), b()}) && (X1 == a());")); assertFalse(runTestInSameEvaluator("({DATA X2, DATA Y2, c()} := {a(), b()});")); assertTrue(runTestInSameEvaluator("({e(int X3), b()} := {e(3), b()}) && (X3 == 3);")); assertTrue(runTestInSameEvaluator("({e(int X4)} := {e(3)}) && (X4 == 3);")); assertFalse(runTestInSameEvaluator("({e(int X5)} := {a()});")); assertTrue(runTestInSameEvaluator("({a(), f({a(), b(), DATA X6})} := {a(), f({a(),b(),c()})}) && (X6 == c());")); assertTrue(runTestInSameEvaluator("({f({a(), b(), DATA X7}), a()} := {a(), f({a(),b(),c()})}) && (X7 == c());")); assertTrue(runTestInSameEvaluator("({a(), f({a(), b(), DATA X8}), set[DATA] Y8} := {a(), b(), f({a(),b(),c()})}) && (X8 == c() && Y8 == {b()});")); assertTrue(runTestInSameEvaluator("({DATA A1, f({A1, b(), DATA X9})} := {a(), f({a(),b(),c()})}) && (A1 == a());")); assertTrue(runTestInSameEvaluator("({DATA A2, f({A2, b(), DATA X10})} := {f({a(),b(),c()}), a()}) && (A2 == a());")); assertTrue(runTestInSameEvaluator("({DATA A3, f({A3, b(), set[DATA] SX1}), SX1} := {a(), f({a(),b(),c()}), c()}) && (A3== a()) && (SX1 =={c()});")); assertTrue(runTestInSameEvaluator("({DATA A4, f({A4, b(), set[DATA] SX2}), SX2} := {f({a(),b(),c()}), a(), c()}) && (A4== a()) && (SX2 =={c()});")); assertTrue(runTestInSameEvaluator("({DATA A5, f({A5, b(), set[DATA] SX3}), SX3} := {c(), f({a(),b(),c()}), a()}) && (A5 == a()) && (SX3 =={c()});")); assertFalse(runTestInSameEvaluator("({DATA A6, f({A6, b(), set[DATA] SX4}), SX4} := {d(), f({a(),b(),c()}), a()});")); assertFalse(runTestInSameEvaluator("({DATA A7, f({A7, b(), set[DATA] SX5}), SX5} := {c(), f({a(),b(),c()}), d()});")); } @Ignore @Test public void matchConstructor1(){ - prepare("data Bool = btrue | bfalse | band(Bool left, Bool right) | bor(Bool left, Bool right);"); + prepare("data Bool = btrue() | bfalse() | band(Bool left, Bool right) | bor(Bool left, Bool right);"); - //assertTrue(runTestInSameEvaluator("Bool::btrue := btrue;")); - assertTrue(runTestInSameEvaluator("btrue := btrue;")); - //assertTrue(runTestInSameEvaluator("Bool::band := band(btrue, bfalse);")); + assertTrue(runTestInSameEvaluator("Bool::btrue b := btrue;")); + assertTrue(runTestInSameEvaluator("btrue := btrue();")); + assertTrue(runTestInSameEvaluator("Bool::band b := band(btrue, bfalse);")); assertTrue(runTestInSameEvaluator("band := band(btrue, bfalse);")); } @Ignore @Test public void matchConstructor2(){ prepareModule("Bool", "module Bool " + "data Bool = btrue | bfalse | band(Bool left, Bool right) | bor(Bool left, Bool right);"); assertTrue(runTestInSameEvaluator("import Bool;")); assertTrue(runTestInSameEvaluator("btrue := btrue;")); assertTrue(runTestInSameEvaluator("Bool::band := band(btrue, bfalse);")); } @Test(expected=StaticError.class) public void matchSetDoubleDeclError() { runTest("{1, set[int] L, 2, set[int] L} := {1,2,3};"); } @Test(expected=StaticError.class) public void matchSetWrongElemError() { runTest("{1, \"a\", 2, set[int] L} := {1,2,3};"); } @Test(expected=StaticError.class) public void matchSetWrongElemError2() { runTest("{1, set[str] L, 2} := {1,2,3};"); } @Test(expected=StaticError.class) public void matchSetWrongElemError3() { runTest("{1, str S, 2} := {1,2,3};"); } @Test(expected=StaticError.class) public void matchSetWrongElemError4() { runTest("{set[str] S = {\"a\"}; {1, S, 2} := {1,2,3};}"); } @Test public void matchSetExternalVar() { runTest("{set[int] S; {1, S, 2} := {1,2,3} && S == {3};}"); } @Test(expected=StaticError.class) public void matchTupleStringError() { assertFalse(runTest("<1> := \"a\";")); } @Test(expected=StaticError.class) public void matchTupleArityError() { assertFalse(runTest("<1,2> := <1>;")); } @Test(expected=StaticError.class) public void noMatchTupleArityError(){ assertTrue(runTest("<1> !:= <1,2>;")); } @Test public void matchTuple() { assertTrue(runTest("<1> := <1>;")); assertTrue(runTest("<1, \"abc\"> := <1, \"abc\">;")); assertFalse(runTest("<2> := <1>;")); assertTrue(runTest("<2> !:= <1>;")); assertFalse(runTest("<1, \"abc\"> := <1, \"def\">;")); assertTrue(runTest("<1, \"abc\"> !:= <1, \"def\">;")); assertTrue(runTest("<_, \"abc\"> := <1, \"abc\">;")); assertTrue(runTest("<1, _> := <1, \"abc\">;")); assertTrue(runTest("<_, _> := <1, \"abc\">;")); } @Test public void matchTupleExternalVar(){ assertTrue(runTest("{tuple[int,int] T; T := <1,2> && T[0] == 1 && T[1] == 2;}")); } @Test public void matchVariable() { prepare("data F = f(int N);"); assertTrue(runTestInSameEvaluator("(n1 := 1) && (n1 == 1);")); assertTrue(runTestInSameEvaluator("{int n2 = 1; (n2 := 1) && (n2 == 1);}")); assertTrue(runTestInSameEvaluator("{int n3 = 1; (n3 !:= 2) && (n3 == 1);}")); assertTrue(runTestInSameEvaluator("(f(n5) := f(1)) && (n5 == 1);")); assertTrue(runTestInSameEvaluator("{int n6 = 1; (f(n6) := f(1)) && (n6 == 1);}")); assertTrue(runTestInSameEvaluator("(f(_) := f(1));")); } @Test public void matchTypedVariableBecomes() { assertTrue(runTest("{int N : 3 := 3 && N == 3;}")); assertTrue(runTest("{list[int] L1 : [int N, list[int] L2, int M] := [1,2,3] && L1 == [1,2,3] && N == 1 && L2 == [2] && M == 3;}")); assertTrue(runTest("{[1, list[int] L: [int N], 2] := [1,[2],2] && L == [2];}")); assertTrue(runTest("{[1, list[int] L1: [list[int] L2, int N], 5] := [1,[2,3,4],5] && L1 == [2,3,4] && L2==[2,3] && N ==4;}")); assertTrue(runTest("{[1, list[int] L1: [list[int] L2, int N], L1] := [1,[2,3,4],[2,3,4]] && L1 == [2,3,4] && L2==[2,3] && N ==4;}")); } @Test(expected=StaticError.class) public void typedVariableBecomesWrongType(){ assertTrue(runTest("{str N : 3 := 3; N == 3;}")); } @Test public void redeclaredTypedVariableBecomesShadowsAnother(){ assertTrue(runTest("{int N = 5; int N : 3 := 3 && N == 3;}")); } @Test(expected=StaticError.class) public void doubleTypedVariableBecomes(){ assertTrue(runTest("{[int N : 3, int N : 4] := [3,4] && N == 3;}")); } @Test public void matchVariableBecomes() { assertTrue(runTest("{N : 3 := 3 && N == 3;}")); assertTrue(runTest("{L1 : [int N, list[int] L2, int M] := [1,2,3] && L1 == [1,2,3] && N == 1 && L2 == [2] && M == 3;}")); assertTrue(runTest("{[1, L: [int N], 2] := [1,[2],2] && L == [2];}")); assertTrue(runTest("{[1, L1: [list[int] L2, int N], 5] := [1,[2,3,4],5] && L1 == [2,3,4] && L2==[2,3] && N ==4;}")); assertTrue(runTest("{[1, L1: [list[int] L2, int N], L1] := [1,[2,3,4],[2,3,4]] && L1 == [2,3,4] && L2==[2,3] && N ==4;}")); } public void variableBecomesEquality(){ assertFalse(runTest("{int N = 5; N : 3 := 3 && N == 3;}")); assertTrue(runTest("{int N = 3; N : 3 := 3 && N == 3;}")); } public void doubleVariableBecomes(){ assertFalse(runTest("{[N : 3, N : 4] := [3,4] && N == 3;}")); assertTrue(runTest("{[N : 3, N : 3] := [3,3] && N == 3;}")); } @Test(expected=StaticError.class) public void UndeclaredTypeError(){ runTest("STRANGE X := 123;"); } @Test public void antiPattern(){ assertTrue(runTest("{!4 := 3;}")); assertFalse(runTest("{!3 := 3;}")); assertTrue(runTest("{![1,2,3] := [1,2,4];}")); assertFalse(runTest("{![1,2,3] := [1,2,3];}")); } @Test(expected=UndeclaredVariableError.class) public void antiPatternDoesNotDeclare() { runTest("{![1,int X,3] := [1,2,4] && (X ? 10) == 10;}"); } @Test public void descendant1(){ assertTrue(runTest("/int N := 1 && N == 1;")); assertTrue(runTest("!/int N := true;")); assertFalse(runTest("/int N := [];")); assertTrue(runTest("/int N := [1] && N == 1;")); assertTrue(runTest("/int N := [1,2,3,2] && N > 2;")); assertTrue(runTest("!/4 := [1,2,3,2];")); assertTrue(runTest("/int N := (1 : 10) && (N == 1 || N == 10);")); assertFalse(runTest("/int N := {};")); assertTrue(runTest("/int N := {1} && N == 1;")); assertTrue(runTest("/int N := {<false,1>} && N == 1;")); assertTrue(runTest("/int N := (\"a\" : 1) && N == 1;")); assertTrue(runTest("/int N := <\"a\", 1> && N == 1;")); assertTrue(runTest("{[1, /int N, 3] := [1, [1,2,3,2], 3] && N == 1;}")); assertTrue(runTest("{[1, /int N, 3] := [1, [1,2,3,2], 3] && N == 2;}")); } @Test public void descendant2(){ prepare("data F = f(F left, F right) | g(int N);"); assertTrue(runTestInSameEvaluator("/g(2) := f(g(1),f(g(2),g(3)));")); assertTrue(runTestInSameEvaluator("[1, /g(2), 3] := [1, f(g(1),f(g(2),g(3))), 3];")); assertTrue(runTestInSameEvaluator("[1, !/g(5), 3] := [1, f(g(1),f(g(2),g(3))), 3];")); assertTrue(runTestInSameEvaluator("[1, /f(/g(2), _), 3] := [1, f(g(1),f(g(2),g(3))), 3];")); assertTrue(runTestInSameEvaluator("[1, /f(/g(2),/g(3)), 3] := [1, f(g(1),f(g(2),g(3))), 3];")); assertTrue(runTestInSameEvaluator("[1, F outer: /f(/F inner: g(2), _), 3] := [1, f(g(1),f(g(2),g(3))), 3] && outer == f(g(1),f(g(2),g(3))) && inner == g(2);")); assertTrue(runTestInSameEvaluator("{[1, /g(int N1), 3] := [1, f(g(1),f(g(2),g(3))), 3] && N1 == 1;}")); assertTrue(runTestInSameEvaluator("{[1, /g(int N2), 3] := [1, f(g(1),f(g(2),g(3))), 3] && N2 == 2;}")); assertTrue(runTestInSameEvaluator("{[1, /g(int N3), 3] := [1, f(g(1),f(g(2),g(3))), 3] && N3 == 3;}")); } @Test public void descendant3(){ assertTrue(runTestInSameEvaluator("[n | /int n <- [1,2,3]] == [1,2,3];")); assertTrue(runTestInSameEvaluator("[b | /bool b <- [true,false,true]] == [true,false,true];")); assertTrue(runTestInSameEvaluator("[s | /str s <- [\"a\",\"b\"]] == [\"a\",\"b\"];")); assertTrue(runTestInSameEvaluator("{n | /int n <- {1,2,3}} == {1,2,3};")); assertTrue(runTestInSameEvaluator("{n | /int n <- {<1,2,3>}} == {1,2,3};")); assertTrue(runTestInSameEvaluator("{v | /value v <- {<1,\"b\",true>}} == {1,\"b\",true, <1,\"b\",true>};")); } /* * The following test requires deeper analysis of the data signature */ @Ignore @Test(expected=StaticError.class) public void descendantWrongType(){ prepare("data F = f(F left, F right) | g(int N);"); assertTrue(runTestInSameEvaluator("/true := f(g(1),f(g(2),g(3)));")); } @Test public void listCount1(){ String cnt = "int cnt(list[int] L){" + " int count = 0;" + " while ([int N, list[int] Ns] := L) { " + " count = count + 1;" + " L = tail(L);" + " }" + " return count;" + "}"; prepare("import List;"); assertTrue(runTestInSameEvaluator("{" + cnt + "cnt([1,2,3]) == 3;}")); } @Test public void listCount2(){ String cnt = "int cnt(list[int] L){" + " int count = 0;" + " while ([int N, list[int] _] := L) { " + " count = count + 1;" + " L = tail(L);" + " }" + " return count;" + "}"; prepare("import List;"); assertTrue(runTestInSameEvaluator("{" + cnt + "cnt([1,2,3]) == 3;}")); } @Test public void listCount3(){ String cnt = "int cnt(list[int] L){" + " int count = 0;" + " while ([N, list[int] _] := L) { " + " count = count + 1;" + " L = tail(L);" + " }" + " return count;" + "}"; prepare("import List;"); assertTrue(runTestInSameEvaluator("{" + cnt + "cnt([1,2,3]) == 3;}")); } @Test public void setCount1(){ String cnt = "int cnt(set[int] S){" + " int count = 0;" + " while ({int N, set[int] Ns} := S) { " + " count = count + 1;" + " S = S - {N};" + " }" + " return count;" + "}"; assertTrue(runTestInSameEvaluator("{" + cnt + "cnt({1,2,3}) == 3;}")); } @Test public void setCount2(){ String cnt = "int cnt(set[int] S){" + " int count = 0;" + " while ({int N, set[int] _} := S) { " + " count = count + 1;" + " S = S - {N};" + " }" + " return count;" + "}"; assertTrue(runTestInSameEvaluator("{" + cnt + "cnt({1,2,3}) == 3;}")); } @Test public void setCount3(){ String cnt = "int cnt(set[int] S){" + " int count = 0;" + " while ({N, set[int] _} := S) { " + " count = count + 1;" + " S = S - {N};" + " }" + " return count;" + "}"; assertTrue(runTestInSameEvaluator("{" + cnt + "cnt({1,2,3}) == 3;}")); } }
false
false
null
null
diff --git a/src/org/inaturalist/android/INaturalistService.java b/src/org/inaturalist/android/INaturalistService.java index 8d12a35a..6aff4920 100644 --- a/src/org/inaturalist/android/INaturalistService.java +++ b/src/org/inaturalist/android/INaturalistService.java @@ -1,1535 +1,1534 @@ package org.inaturalist.android; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks; import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.location.LocationClient; import android.app.IntentService; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.MediaStore; import android.util.Base64; import android.util.Log; import android.widget.Toast; public class INaturalistService extends IntentService implements ConnectionCallbacks, OnConnectionFailedListener { // How many observations should we initially download for the user private static final int INITIAL_SYNC_OBSERVATION_COUNT = 100; public static final String OBSERVATION_ID = "observation_id"; public static final String OBSERVATION_RESULT = "observation_result"; public static final String PROJECTS_RESULT = "projects_result"; public static final String ADD_OBSERVATION_TO_PROJECT_RESULT = "add_observation_to_project_result"; public static final String TAXON_ID = "taxon_id"; public static final String COMMENT_BODY = "comment_body"; public static final String IDENTIFICATION_BODY = "id_body"; public static final String PROJECT_ID = "project_id"; public static final String CHECK_LIST_ID = "check_list_id"; public static final String ACTION_CHECK_LIST_RESULT = "action_check_list_result"; public static final String CHECK_LIST_RESULT = "check_list_result"; public static final String ACTION_GET_TAXON_RESULT = "action_get_taxon_result"; public static final String TAXON_RESULT = "taxon_result"; public static String TAG = "INaturalistService"; public static String HOST = "https://www.inaturalist.org"; // public static String HOST = "http://10.0.2.2:3000"; public static String MEDIA_HOST = HOST; public static String USER_AGENT = "iNaturalist/" + INaturalistApp.VERSION + " (" + "Android " + System.getProperty("os.version") + " " + android.os.Build.VERSION.INCREMENTAL + "; " + "SDK " + android.os.Build.VERSION.SDK + "; " + android.os.Build.DEVICE + " " + android.os.Build.MODEL + " " + android.os.Build.PRODUCT + ")"; public static String ACTION_PASSIVE_SYNC = "passive_sync"; public static String ACTION_ADD_IDENTIFICATION = "add_identification"; public static String ACTION_GET_TAXON = "get_taxon"; public static String ACTION_FIRST_SYNC = "first_sync"; public static String ACTION_GET_OBSERVATION = "get_observation"; public static String ACTION_GET_CHECK_LIST = "get_check_list"; public static String ACTION_JOIN_PROJECT = "join_project"; public static String ACTION_LEAVE_PROJECT = "leave_project"; public static String ACTION_GET_JOINED_PROJECTS = "get_joined_projects"; public static String ACTION_GET_NEARBY_PROJECTS = "get_nearby_projects"; public static String ACTION_GET_FEATURED_PROJECTS = "get_featured_projects"; public static String ACTION_ADD_OBSERVATION_TO_PROJECT = "add_observation_to_project"; public static String ACTION_REMOVE_OBSERVATION_FROM_PROJECT = "remove_observation_from_project"; public static String ACTION_SYNC = "sync"; public static String ACTION_NEARBY = "nearby"; public static String ACTION_AGREE_ID = "agree_id"; public static String ACTION_ADD_COMMENT = "add_comment"; public static String ACTION_SYNC_COMPLETE = "sync_complete"; public static String ACTION_OBSERVATION_RESULT = "observation_result"; public static String ACTION_PROJECTS_RESULT = "projects_result"; public static Integer SYNC_OBSERVATIONS_NOTIFICATION = 1; public static Integer SYNC_PHOTOS_NOTIFICATION = 2; public static Integer AUTH_NOTIFICATION = 3; private String mLogin; private String mCredentials; private SharedPreferences mPreferences; private boolean mPassive; private INaturalistApp app; private LoginType mLoginType; private boolean mIsSyncing; private Handler mHandler; private LocationClient mLocationClient; private ArrayList<SerializableJSONArray> mProjectObservations; private Hashtable<Integer, Hashtable<Integer, ProjectFieldValue>> mProjectFieldValues; private Header[] mResponseHeaders = null; public enum LoginType { PASSWORD, GOOGLE, FACEBOOK }; public INaturalistService() { super("INaturalistService"); mHandler = new Handler(); } @Override protected void onHandleIntent(Intent intent) { mPreferences = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); mLogin = mPreferences.getString("username", null); mCredentials = mPreferences.getString("credentials", null); mLoginType = LoginType.valueOf(mPreferences.getString("login_type", LoginType.PASSWORD.toString())); app = (INaturalistApp) getApplicationContext(); String action = intent.getAction(); mPassive = action.equals(ACTION_PASSIVE_SYNC); try { if (action.equals(ACTION_NEARBY)) { getNearbyObservations(intent); } else if (action.equals(ACTION_FIRST_SYNC)) { saveJoinedProjects(); getUserObservations(INITIAL_SYNC_OBSERVATION_COUNT); syncObservationFields(); postProjectObservations(); } else if (action.equals(ACTION_AGREE_ID)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int taxonId = intent.getIntExtra(TAXON_ID, 0); agreeIdentification(observationId, taxonId); } else if (action.equals(ACTION_ADD_IDENTIFICATION)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int taxonId = intent.getIntExtra(TAXON_ID, 0); String body = intent.getStringExtra(IDENTIFICATION_BODY); addIdentification(observationId, taxonId, body); } else if (action.equals(ACTION_GET_TAXON)) { int taxonId = intent.getIntExtra(TAXON_ID, 0); BetterJSONObject taxon = getTaxon(taxonId); Intent reply = new Intent(ACTION_GET_TAXON_RESULT); reply.putExtra(TAXON_RESULT, taxon); sendBroadcast(reply); } else if (action.equals(ACTION_ADD_COMMENT)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); String body = intent.getStringExtra(COMMENT_BODY); addComment(observationId, body); } else if (action.equals(ACTION_GET_NEARBY_PROJECTS)) { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); // If Google Play services is available if (ConnectionResult.SUCCESS == resultCode) { // Use Google Location Services to determine location mLocationClient = new LocationClient(getApplicationContext(), this, this); mLocationClient.connect(); // Only once we're connected - we'll call getNearByProjects() } else { // Use GPS for the location SerializableJSONArray projects = getNearByProjects(false); Intent reply = new Intent(ACTION_PROJECTS_RESULT); reply.putExtra(PROJECTS_RESULT, projects); sendBroadcast(reply); } } else if (action.equals(ACTION_GET_FEATURED_PROJECTS)) { SerializableJSONArray projects = getFeaturedProjects(); Intent reply = new Intent(ACTION_PROJECTS_RESULT); reply.putExtra(PROJECTS_RESULT, projects); sendBroadcast(reply); } else if (action.equals(ACTION_GET_JOINED_PROJECTS)) { SerializableJSONArray projects = getJoinedProjectsOffline(); Intent reply = new Intent(ACTION_PROJECTS_RESULT); reply.putExtra(PROJECTS_RESULT, projects); sendBroadcast(reply); } else if (action.equals(ACTION_REMOVE_OBSERVATION_FROM_PROJECT)) { int observationId = intent.getExtras().getInt(OBSERVATION_ID); int projectId = intent.getExtras().getInt(PROJECT_ID); BetterJSONObject result = removeObservationFromProject(observationId, projectId); } else if (action.equals(ACTION_ADD_OBSERVATION_TO_PROJECT)) { int observationId = intent.getExtras().getInt(OBSERVATION_ID); int projectId = intent.getExtras().getInt(PROJECT_ID); BetterJSONObject result = addObservationToProject(observationId, projectId); Intent reply = new Intent(ADD_OBSERVATION_TO_PROJECT_RESULT); reply.putExtra(ADD_OBSERVATION_TO_PROJECT_RESULT, result); sendBroadcast(reply); } else if (action.equals(ACTION_GET_CHECK_LIST)) { int id = intent.getExtras().getInt(CHECK_LIST_ID); SerializableJSONArray checkList = getCheckList(id); Intent reply = new Intent(ACTION_CHECK_LIST_RESULT); reply.putExtra(CHECK_LIST_RESULT, checkList); sendBroadcast(reply); } else if (action.equals(ACTION_GET_OBSERVATION)) { int id = intent.getExtras().getInt(OBSERVATION_ID); Observation observation = getObservation(id); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); reply.putExtra(OBSERVATION_RESULT, observation); sendBroadcast(reply); } else if (action.equals(ACTION_JOIN_PROJECT)) { int id = intent.getExtras().getInt(PROJECT_ID); joinProject(id); } else if (action.equals(ACTION_LEAVE_PROJECT)) { int id = intent.getExtras().getInt(PROJECT_ID); leaveProject(id); } else { mIsSyncing = true; syncObservations(); // Update last sync time long lastSync = System.currentTimeMillis(); mPreferences.edit().putLong("last_sync_time", lastSync).commit(); } } catch (AuthenticationException e) { if (!mPassive) { requestCredentials(); } } finally { if (mIsSyncing) { mIsSyncing = false; Log.i(TAG, "Sending ACTION_SYNC_COMPLETE"); // Notify the rest of the app of the completion of the sync Intent reply = new Intent(ACTION_SYNC_COMPLETE); sendBroadcast(reply); } } } private void syncObservations() throws AuthenticationException { deleteObservations(); // Delete locally-removed observations saveJoinedProjects(); getUserObservations(0); // First, download remote observations (new/updated) postObservations(); // Next, update local-to-remote observations syncObservationFields(); postPhotos(); postProjectObservations(); // Toast.makeText(getApplicationContext(), "Observations synced", Toast.LENGTH_SHORT); } private BetterJSONObject getTaxon(int id) throws AuthenticationException { String url = String.format("%s/taxa/%d.json", HOST, id); JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); } catch (JSONException e) { return null; } return new BetterJSONObject(res); } private void postProjectObservations() throws AuthenticationException { // First, delete any project-observations that were deleted by the user Cursor c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "is_deleted = 1", null, ProjectObservation.DEFAULT_SORT_ORDER); c.moveToFirst(); while (c.isAfterLast() == false) { ProjectObservation projectObservation = new ProjectObservation(c); removeObservationFromProject(projectObservation.observation_id, projectObservation.project_id); c.moveToNext(); } // Now it's safe to delete all of the project-observations locally getContentResolver().delete(ProjectObservation.CONTENT_URI, "is_deleted = 1", null); // Next, add new project observations c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "is_new = 1", null, ProjectObservation.DEFAULT_SORT_ORDER); c.moveToFirst(); while (c.isAfterLast() == false) { ProjectObservation projectObservation = new ProjectObservation(c); BetterJSONObject result = addObservationToProject(projectObservation.observation_id, projectObservation.project_id); SerializableJSONArray errors = result.getJSONArray("errors"); if (errors != null) { // Couldn't add the observation to the project (probably didn't pass validation) String error; try { error = errors.getJSONArray().getString(0); } catch (JSONException e) { e.printStackTrace(); c.moveToNext(); continue; } Cursor c2 = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = '"+projectObservation.observation_id+"'", null, Observation.DEFAULT_SORT_ORDER); c2.moveToFirst(); Observation observation = new Observation(c2); c2.close(); c2 = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, "id = '"+projectObservation.project_id+"'", null, Project.DEFAULT_SORT_ORDER); c2.moveToFirst(); Project project = new Project(c2); c2.close(); final String errorMessage = String.format(getString(R.string.failed_to_add_obs_to_project), observation.species_guess, project.title, error); // Notify user app.sweepingNotify(SYNC_OBSERVATIONS_NOTIFICATION, getString(R.string.syncing_observations), errorMessage, getString(R.string.syncing)); // Display toast in this main thread handler (since otherwise it won't get displayed) mHandler.post(new Runnable() { @Override public void run() { // Toast doesn't support longer periods of display - this is a workaround for (int i = 0; i < 3; i++) { Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_LONG).show(); } } }); } else { // Unmark as new projectObservation.is_new = false; ContentValues cv = projectObservation.getContentValues(); getContentResolver().update(projectObservation.getUri(), cv, null, null); } c.moveToNext(); } // Finally, retrieve all project observations for (int j = 0; j < mProjectObservations.size(); j++) { JSONArray projectObservations = mProjectObservations.get(j).getJSONArray(); for (int i = 0; i < projectObservations.length(); i++) { JSONObject jsonProjectObservation; try { jsonProjectObservation = projectObservations.getJSONObject(i); ProjectObservation projectObservation = new ProjectObservation(new BetterJSONObject(jsonProjectObservation)); ContentValues cv = projectObservation.getContentValues(); getContentResolver().insert(ProjectObservation.CONTENT_URI, cv); } catch (JSONException e) { e.printStackTrace(); } } } } private void saveJoinedProjects() throws AuthenticationException { SerializableJSONArray projects = getJoinedProjects(); if (projects != null) { JSONArray arr = projects.getJSONArray(); try { // First, delete all joined projects getContentResolver().delete(Project.CONTENT_URI, null, null); } catch (Exception exc) { exc.printStackTrace(); return; } // Next, add the new joined projects for (int i = 0; i < arr.length(); i++) { try { JSONObject jsonProject = arr.getJSONObject(i); Project project = new Project(new BetterJSONObject(jsonProject)); ContentValues cv = project.getContentValues(); getContentResolver().insert(Project.CONTENT_URI, cv); } catch (JSONException e) { e.printStackTrace(); } } } } private void deleteObservations() throws AuthenticationException { // Remotely delete any locally-removed observations Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "is_deleted = 1 AND user_login = '"+mLogin+"'", null, Observation.DEFAULT_SORT_ORDER); // for each observation DELETE to /observations/:id c.moveToFirst(); while (c.isAfterLast() == false) { Observation observation = new Observation(c); delete(HOST + "/observations/" + observation.id + ".json", null); c.moveToNext(); } // Now it's safe to delete all of the observations locally getContentResolver().delete(Observation.CONTENT_URI, "is_deleted = 1", null); } private void agreeIdentification(int observationId, int taxonId) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("identification[observation_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("identification[taxon_id]", new Integer(taxonId).toString())); post(HOST + "/identifications.json", params); } private void addIdentification(int observationId, int taxonId, String body) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("identification[observation_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("identification[taxon_id]", new Integer(taxonId).toString())); params.add(new BasicNameValuePair("identification[body]", body)); JSONArray arrayResult = post(HOST + "/identifications.json", params); if (arrayResult != null) { BetterJSONObject result; try { result = new BetterJSONObject(arrayResult.getJSONObject(0)); JSONObject jsonObservation = result.getJSONObject("observation"); Observation remoteObservation = new Observation(new BetterJSONObject(jsonObservation)); Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = "+ remoteObservation.id, null, Observation.DEFAULT_SORT_ORDER); // update local observation c.moveToFirst(); if (c.isAfterLast() == false) { Observation observation = new Observation(c); boolean isModified = observation.merge(remoteObservation); ContentValues cv = observation.getContentValues(); if (observation._updated_at.before(remoteObservation.updated_at)) { // Remote observation is newer (and thus has overwritten the local one) - update its // sync at time so we won't update the remote servers later on (since we won't // accidently consider this an updated record) cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); } if (isModified) { // Only update the DB if needed getContentResolver().update(observation.getUri(), cv, null, null); } } c.close(); } catch (JSONException e) { e.printStackTrace(); } } } private void addComment(int observationId, String body) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("comment[parent_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("comment[parent_type]", "Observation")); params.add(new BasicNameValuePair("comment[body]", body)); post(HOST + "/comments.json", params); } private void postObservations() throws AuthenticationException { Observation observation; // query observations where _updated_at > updated_at Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "_updated_at > _synced_at AND _synced_at IS NOT NULL AND user_login = '"+mLogin+"'", null, Observation.DEFAULT_SORT_ORDER); int updatedCount = c.getCount(); app.sweepingNotify(SYNC_OBSERVATIONS_NOTIFICATION, getString(R.string.syncing_observations), String.format(getString(R.string.syncing_x_observations), c.getCount()), getString(R.string.syncing)); // for each observation PUT to /observations/:id c.moveToFirst(); while (c.isAfterLast() == false) { app.notify(SYNC_OBSERVATIONS_NOTIFICATION, getString(R.string.updating_observations), String.format(getString(R.string.updating_x_observations), (c.getPosition() + 1), c.getCount()), getString(R.string.syncing)); observation = new Observation(c); handleObservationResponse( observation, put(HOST + "/observations/" + observation.id + ".json", paramsForObservation(observation)) ); c.moveToNext(); } c.close(); // query observations where _synced_at IS NULL c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id IS NULL", null, Observation.DEFAULT_SORT_ORDER); int createdCount = c.getCount(); // for each observation POST to /observations/ c.moveToFirst(); while (c.isAfterLast() == false) { app.notify(SYNC_OBSERVATIONS_NOTIFICATION, getString(R.string.posting_observations), String.format(getString(R.string.posting_x_observations), (c.getPosition() + 1), c.getCount()), getString(R.string.syncing)); observation = new Observation(c); handleObservationResponse( observation, post(HOST + "/observations.json", paramsForObservation(observation)) ); c.moveToNext(); } c.close(); app.notify(SYNC_OBSERVATIONS_NOTIFICATION, getString(R.string.observation_sync_complete), String.format(getString(R.string.observation_sync_status), createdCount, updatedCount), getString(R.string.sync_complete)); } private Observation getObservation(int id) throws AuthenticationException { String url = String.format("%s/observations/%d.json", HOST, id); JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject observation; try { observation = (JSONObject) json.get(0); } catch (JSONException e) { return null; } return new Observation(new BetterJSONObject(observation)); } private void postPhotos() throws AuthenticationException { ObservationPhoto op; int createdCount = 0; // query observations where _updated_at > updated_at Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "_synced_at IS NULL", null, ObservationPhoto.DEFAULT_SORT_ORDER); if (c.getCount() == 0) { return; } // for each observation PUT to /observations/:id ContentValues cv; c.moveToFirst(); while (c.isAfterLast() == false) { app.notify(SYNC_PHOTOS_NOTIFICATION, getString(R.string.posting_photos), String.format(getString(R.string.posting_x_photos), (c.getPosition() + 1), c.getCount()), getString(R.string.syncing)); op = new ObservationPhoto(c); ArrayList <NameValuePair> params = op.getParams(); // http://stackoverflow.com/questions/2935946/sending-images-using-http-post Uri photoUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, op._photo_id); Cursor pc = getContentResolver().query(photoUri, new String[] {MediaStore.MediaColumns._ID, MediaStore.Images.Media.DATA}, null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER); if (pc.getCount() == 0) { // photo has been deleted, destroy the ObservationPhoto getContentResolver().delete(op.getUri(), null, null); continue; } else { pc.moveToFirst(); } String imgFilePath = pc.getString(pc.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); params.add(new BasicNameValuePair("file", imgFilePath)); // TODO LATER resize the image for upload, maybe a 1024px jpg JSONArray response = post(MEDIA_HOST + "/observation_photos.json", params); try { if (response == null || response.length() != 1) { break; } JSONObject json = response.getJSONObject(0); BetterJSONObject j = new BetterJSONObject(json); ObservationPhoto jsonObservationPhoto = new ObservationPhoto(j); op.merge(jsonObservationPhoto); cv = op.getContentValues(); cv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(op.getUri(), cv, null, null); createdCount += 1; } catch (JSONException e) { Log.e(TAG, "JSONException: " + e.toString()); } c.moveToNext(); } c.close(); app.notify(SYNC_PHOTOS_NOTIFICATION, getString(R.string.photo_sync_complete), String.format(getString(R.string.posted_new_x_photos), createdCount), getString(R.string.sync_complete)); } private SerializableJSONArray getNearByProjects(Location location) throws AuthenticationException { if (location == null) { // No location found - return an empty result Log.e(TAG, "Current location is null"); return new SerializableJSONArray(); } double lat = location.getLatitude(); double lon = location.getLongitude(); String url = HOST + String.format("/projects.json?latitude=%s&longitude=%s", lat, lon); Log.e(TAG, url); JSONArray json = get(url); return new SerializableJSONArray(json); } private SerializableJSONArray getNearByProjects(boolean useLocationServices) throws AuthenticationException { if (useLocationServices) { Location location = mLocationClient.getLastLocation(); return getNearByProjects(location); } else { // Use GPS alone to determine location LocationManager locationManager = (LocationManager)app.getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = locationManager.getBestProvider(criteria, false); Location location = locationManager.getLastKnownLocation(provider); return getNearByProjects(location); } } private SerializableJSONArray getFeaturedProjects() throws AuthenticationException { if (ensureCredentials() == false) { return null; } String url = HOST + "/projects.json?featured=true"; JSONArray json = get(url); return new SerializableJSONArray(json); } private void addProjectFields(JSONArray jsonFields) { int projectId = -1; ArrayList<ProjectField> projectFields = new ArrayList<ProjectField>(); for (int i = 0; i < jsonFields.length(); i++) { try { BetterJSONObject jsonField = new BetterJSONObject(jsonFields.getJSONObject(i)); ProjectField field = new ProjectField(jsonField); projectId = field.project_id; projectFields.add(field); } catch (JSONException e) { e.printStackTrace(); } } if (projectId != -1) { // First, delete all previous project fields (for that project) getContentResolver().delete(ProjectField.CONTENT_URI, "(project_id IS NOT NULL) and (project_id = "+projectId+")", null); // Next, re-add all project fields for (int i = 0; i < projectFields.size(); i++) { ProjectField field = projectFields.get(i); getContentResolver().insert(ProjectField.CONTENT_URI, field.getContentValues()); } } } public void joinProject(int projectId) throws AuthenticationException { post(String.format("%s/projects/%d/join", HOST, projectId), null); try { JSONArray result = get(String.format("%s/projects/%d.json", HOST, projectId)); BetterJSONObject jsonProject = new BetterJSONObject(result.getJSONObject(0)); Project project = new Project(jsonProject); // Add joined project locally ContentValues cv = project.getContentValues(); getContentResolver().insert(Project.CONTENT_URI, cv); // Save project fields addProjectFields(jsonProject.getJSONArray("project_observation_fields").getJSONArray()); } catch (JSONException e) { e.printStackTrace(); } } public void leaveProject(int projectId) throws AuthenticationException { delete(String.format("%s/projects/%d/leave", HOST, projectId), null); // Remove locally saved project (because we left it) getContentResolver().delete(Project.CONTENT_URI, "(id IS NOT NULL) and (id = "+projectId+")", null); } private BetterJSONObject removeObservationFromProject(int observationId, int projectId) throws AuthenticationException { if (ensureCredentials() == false) { return null; } String url = String.format("%s/projects/%d/remove.json?observation_id=%d", HOST, projectId, observationId); JSONArray json = delete(url, null); try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { e.printStackTrace(); return new BetterJSONObject(); } } private BetterJSONObject addObservationToProject(int observationId, int projectId) throws AuthenticationException { if (ensureCredentials() == false) { return null; } String url = HOST + "/project_observations.json"; ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("project_observation[observation_id]", String.valueOf(observationId))); params.add(new BasicNameValuePair("project_observation[project_id]", String.valueOf(projectId))); JSONArray json = post(url, params); try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { e.printStackTrace(); return new BetterJSONObject(); } } private SerializableJSONArray getCheckList(int id) throws AuthenticationException { String url = String.format("%s/lists/%d.json", HOST, id); JSONArray json = get(url); if (json == null) { return null; } try { return new SerializableJSONArray(json.getJSONObject(0).getJSONArray("listed_taxa")); } catch (JSONException e) { e.printStackTrace(); return new SerializableJSONArray(); } } private SerializableJSONArray getJoinedProjectsOffline() { JSONArray projects = new JSONArray(); Cursor c = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, null, null, Project.DEFAULT_SORT_ORDER); c.moveToFirst(); int index = 0; while (c.isAfterLast() == false) { Project project = new Project(c); JSONObject jsonProject = project.toJSONObject(); try { jsonProject.put("joined", true); projects.put(index, jsonProject); } catch (JSONException e) { e.printStackTrace(); } c.moveToNext(); index++; } c.close(); return new SerializableJSONArray(projects); } private SerializableJSONArray getJoinedProjects() throws AuthenticationException { if (ensureCredentials() == false) { return null; } String url = HOST + "/projects/user/" + mLogin + ".json"; JSONArray json = get(url, true); JSONArray finalJson = new JSONArray(); if (json == null) { return null; } for (int i = 0; i < json.length(); i++) { try { JSONObject obj = json.getJSONObject(i); JSONObject project = obj.getJSONObject("project"); project.put("joined", true); finalJson.put(project); // Save project fields addProjectFields(project.getJSONArray("project_observation_fields")); } catch (JSONException e) { e.printStackTrace(); } } return new SerializableJSONArray(finalJson); } private void getUserObservations(int maxCount) throws AuthenticationException { if (ensureCredentials() == false) { return; } String url = HOST + "/observations/" + mLogin + ".json"; long lastSync = mPreferences.getLong("last_sync_time", 0); Timestamp lastSyncTS = new Timestamp(lastSync); url += String.format("?updated_since=%s&order_by=date_added&order=desc&extra=projects,fields", URLEncoder.encode(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(lastSyncTS))); if (maxCount > 0) { // Retrieve only a certain number of observations url += String.format("&per_page=%d&page=1", maxCount); } mProjectObservations = new ArrayList<SerializableJSONArray>(); mProjectFieldValues = new Hashtable<Integer, Hashtable<Integer,ProjectFieldValue>>(); JSONArray json = get(url); if (json != null && json.length() > 0) { syncJson(json, true); } } private void syncObservationFields() throws AuthenticationException { // First, remotely update the observation fields which were modified Cursor c = getContentResolver().query(ProjectFieldValue.CONTENT_URI, ProjectFieldValue.PROJECTION, "_updated_at > _synced_at AND _synced_at IS NOT NULL", null, ProjectFieldValue.DEFAULT_SORT_ORDER); c.moveToFirst(); while (c.isAfterLast() == false) { ProjectFieldValue localField = new ProjectFieldValue(c); if (!mProjectFieldValues.containsKey(Integer.valueOf(localField.observation_id))) { // Need to retrieve remote observation fields to see how to sync the fields JSONArray jsonResult = get(HOST + "/observations/" + localField.observation_id + ".json"); Hashtable<Integer, ProjectFieldValue> fields = new Hashtable<Integer, ProjectFieldValue>(); try { JSONArray jsonFields = jsonResult.getJSONObject(0).getJSONArray("observation_field_values"); for (int j = 0; j < jsonFields.length(); j++) { JSONObject jsonField = jsonFields.getJSONObject(j); JSONObject observationField = jsonField.getJSONObject("observation_field"); int id = observationField.optInt("id", jsonField.getInt("observation_field_id")); fields.put(id, new ProjectFieldValue(new BetterJSONObject(jsonField))); } } catch (JSONException e) { e.printStackTrace(); } mProjectFieldValues.put(localField.observation_id, fields); } Hashtable<Integer, ProjectFieldValue> fields = mProjectFieldValues.get(Integer.valueOf(localField.observation_id)); boolean shouldOverwriteRemote = false; ProjectFieldValue remoteField = null; if (!fields.containsKey(Integer.valueOf(localField.field_id))) { // No remote field - add it shouldOverwriteRemote = true; } else { remoteField = fields.get(Integer.valueOf(localField.field_id)); if (remoteField.updated_at.before(localField._updated_at)) { shouldOverwriteRemote = true; } } if (shouldOverwriteRemote) { // Overwrite remote value ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("observation_field_value[observation_id]", Integer.valueOf(localField.observation_id).toString())); params.add(new BasicNameValuePair("observation_field_value[observation_field_id]", Integer.valueOf(localField.field_id).toString())); params.add(new BasicNameValuePair("observation_field_value[value]", localField.value)); post(HOST + "/observation_field_values.json", params); } else { // Overwrite local value localField.created_at = remoteField.created_at; localField.id = remoteField.id; localField.observation_id = remoteField.observation_id; localField.field_id = remoteField.field_id; localField.value = remoteField.value; localField.updated_at = remoteField.updated_at; } ContentValues cv = localField.getContentValues(); cv.put(ProjectFieldValue._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(localField.getUri(), cv, null, null); fields.remove(Integer.valueOf(localField.field_id)); c.moveToNext(); } c.close(); // Next, add any new observation fields for (Hashtable<Integer, ProjectFieldValue> fields : mProjectFieldValues.values()) { for (ProjectFieldValue field : fields.values()) { ContentValues cv = field.getContentValues(); cv.put(ProjectFieldValue._SYNCED_AT, System.currentTimeMillis()); getContentResolver().insert(ProjectFieldValue.CONTENT_URI, cv); c = getContentResolver().query(ProjectField.CONTENT_URI, ProjectField.PROJECTION, "field_id = " + field.field_id, null, Project.DEFAULT_SORT_ORDER); if (c.getCount() == 0) { // This observation has a non-project custom field - add it as well addProjectField(field.field_id); } c.close(); } } } private void addProjectField(int fieldId) throws AuthenticationException { try { JSONArray result = get(String.format("%s/observation_fields/%d.json", HOST, fieldId)); BetterJSONObject jsonObj; jsonObj = new BetterJSONObject(result.getJSONObject(0)); ProjectField field = new ProjectField(jsonObj); getContentResolver().insert(ProjectField.CONTENT_URI, field.getContentValues()); } catch (JSONException e) { e.printStackTrace(); } } private void getNearbyObservations(Intent intent) throws AuthenticationException { Bundle extras = intent.getExtras(); Double minx = extras.getDouble("minx"); Double maxx = extras.getDouble("maxx"); Double miny = extras.getDouble("miny"); Double maxy = extras.getDouble("maxy"); String url = HOST + "/observations.json?"; url += "swlat="+miny; url += "&nelat="+maxy; url += "&swlng="+minx; url += "&nelng="+maxx; JSONArray json = get(url, app.loggedIn()); Intent reply = new Intent(ACTION_NEARBY); reply.putExtra("minx", minx); reply.putExtra("maxx", maxx); reply.putExtra("miny", miny); reply.putExtra("maxy", maxy); if (json == null) { reply.putExtra("error", getString(R.string.couldnt_load_nearby_observations)); } else { syncJson(json, false); } sendBroadcast(reply); } private JSONArray put(String url, ArrayList<NameValuePair> params) throws AuthenticationException { params.add(new BasicNameValuePair("_method", "PUT")); return request(url, "put", params, true); } private JSONArray delete(String url, ArrayList<NameValuePair> params) throws AuthenticationException { return request(url, "delete", params, true); } private JSONArray post(String url, ArrayList<NameValuePair> params) throws AuthenticationException { return request(url, "post", params, true); } private JSONArray get(String url) throws AuthenticationException { return get(url, false); } private JSONArray get(String url, boolean authenticated) throws AuthenticationException { return request(url, "get", null, authenticated); } private JSONArray request(String url, String method, ArrayList<NameValuePair> params, boolean authenticated) throws AuthenticationException { DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT); // Log.d(TAG, String.format("%s (%b - %s): %s", method, authenticated, // authenticated ? mCredentials : "<null>", // url)); HttpRequestBase request; if (method.equalsIgnoreCase("post")) { request = new HttpPost(url); } else if (method.equalsIgnoreCase("delete")) { request = new HttpDelete(url); } else if (method.equalsIgnoreCase("put")) { request = new HttpPut(url); } else { request = new HttpGet(url); } // POST params if (params != null) { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (int i = 0; i < params.size(); i++) { if (params.get(i).getName().equalsIgnoreCase("image") || params.get(i).getName().equalsIgnoreCase("file")) { // If the key equals to "image", we use FileBody to transfer the data entity.addPart(params.get(i).getName(), new FileBody(new File (params.get(i).getValue()))); } else { // Normal string data try { entity.addPart(params.get(i).getName(), new StringBody(params.get(i).getValue())); } catch (UnsupportedEncodingException e) { Log.e(TAG, "failed to add " + params.get(i).getName() + " to entity for a " + method + " request: " + e); } } } if (method.equalsIgnoreCase("put")) { ((HttpPut) request).setEntity(entity); } else { ((HttpPost) request).setEntity(entity); } } // auth if (authenticated) { ensureCredentials(); if (mLoginType == LoginType.PASSWORD) { request.setHeader("Authorization", "Basic " + mCredentials); } else { request.setHeader("Authorization", "Bearer " + mCredentials); } } try { /* com.google.api.client.http.HttpResponse response = request.execute(); String content = response.parseAsString(); */ HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); Log.d(TAG, String.format("RESP: %s", content)); JSONArray json = null; switch (response.getStatusLine().getStatusCode()) { //switch (response.getStatusCode()) { case HttpStatus.SC_UNPROCESSABLE_ENTITY: // Validation error - still need to return response Log.e(TAG, response.getStatusLine().toString()); case HttpStatus.SC_OK: try { json = new JSONArray(content); } catch (JSONException e) { Log.e(TAG, "Failed to create JSONArray, JSONException: " + e.toString()); try { JSONObject jo = new JSONObject(content); json = new JSONArray(); json.put(jo); } catch (JSONException e2) { Log.e(TAG, "Failed to create JSONObject, JSONException: " + e2.toString()); } } mResponseHeaders = response.getAllHeaders(); return json; case HttpStatus.SC_UNAUTHORIZED: throw new AuthenticationException(); case HttpStatus.SC_GONE: // TODO create notification that informs user some observations have been deleted on the server, // click should take them to an activity that lets them decide whether to delete them locally // or post them as new observations default: Log.e(TAG, response.getStatusLine().toString()); //Log.e(TAG, response.getStatusMessage()); } } catch (IOException e) { //request.abort(); Log.w(TAG, "Error for URL " + url, e); } return null; } private boolean ensureCredentials() throws AuthenticationException { if (mCredentials != null) { return true; } // request login unless passive if (!mPassive) { throw new AuthenticationException(); } stopSelf(); return false; } private void requestCredentials() { stopSelf(); Intent intent = new Intent( mLogin == null ? "signin" : INaturalistPrefsActivity.REAUTHENTICATE_ACTION, null, getBaseContext(), INaturalistPrefsActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); app.sweepingNotify(AUTH_NOTIFICATION, getString(R.string.please_sign_in), getString(R.string.please_sign_in_description), null, intent); } public static boolean verifyCredentials(String credentials) { DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT); String url = HOST + "/observations/new.json"; HttpRequestBase request = new HttpGet(url); request.setHeader("Authorization", "Basic "+credentials); request.setHeader("Content-Type", "application/json"); try { HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return true; } else { Log.e(TAG, "Authentication failed: " + content); return false; } } catch (IOException e) { request.abort(); Log.w(TAG, "Error for URL " + url, e); } return false; } public static boolean verifyCredentials(String username, String password) { String credentials = Base64.encodeToString( (username + ":" + password).getBytes(), Base64.URL_SAFE|Base64.NO_WRAP ); return verifyCredentials(credentials); } // Returns an array of two strings: access token + iNat username public static String[] verifyCredentials(String oauth2Token, LoginType authType) { String grantType; DefaultHttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT); String url = HOST + "/oauth/assertion_token"; HttpRequestBase request = new HttpPost(url); ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>(); postParams.add(new BasicNameValuePair("format", "json")); postParams.add(new BasicNameValuePair("client_id", INaturalistApp.getAppContext().getString(R.string.oauth_client_id))); if (authType == LoginType.FACEBOOK) { grantType = "facebook"; } else { grantType = "google"; } postParams.add(new BasicNameValuePair("grant_type", grantType)); postParams.add(new BasicNameValuePair("assertion", oauth2Token)); try { ((HttpPost)request).setEntity(new UrlEncodedFormEntity(postParams)); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); return null; } try { HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Upgrade to an access token // Log.d(TAG, "Authorization Response: " + content); JSONObject json = new JSONObject(content); String accessToken = json.getString("access_token"); // Next, find the iNat username (since we currently only have the FB/Google email) request = new HttpGet(HOST + "/users/edit.json"); request.setHeader("Authorization", "Bearer " + accessToken); response = client.execute(request); entity = response.getEntity(); content = EntityUtils.toString(entity); Log.d(TAG, String.format("RESP2: %s", content)); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { return null; } json = new JSONObject(content); if (!json.has("login")) { return null; } String username = json.getString("login"); return new String[] { accessToken, username }; } else { Log.e(TAG, "Authentication failed: " + content); return null; } } catch (IOException e) { request.abort(); Log.w(TAG, "Error for URL " + url, e); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** Create a file Uri for saving an image or video */ private Uri getOutputMediaFileUri(Observation observation){ ContentValues values = new ContentValues(); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String name = "observation_" + observation.created_at.getTime() + "_" + timeStamp; values.put(android.provider.MediaStore.Images.Media.TITLE, name); return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } private Uri createObservationPhotoForPhoto(Uri photoUri, Observation observation) { ObservationPhoto op = new ObservationPhoto(); Long photoId = ContentUris.parseId(photoUri); ContentValues cv = op.getContentValues(); cv.put(ObservationPhoto._OBSERVATION_ID, observation._id); cv.put(ObservationPhoto.OBSERVATION_ID, observation.id); cv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); // So we won't re-add this photo as though it was a local photo if (photoId > -1) { cv.put(ObservationPhoto._PHOTO_ID, photoId.intValue()); } return getContentResolver().insert(ObservationPhoto.CONTENT_URI, cv); } public void syncJson(JSONArray json, boolean isUser) { ArrayList<Integer> ids = new ArrayList<Integer>(); ArrayList<Integer> existingIds = new ArrayList<Integer>(); ArrayList<Integer> newIds = new ArrayList<Integer>(); HashMap<Integer,Observation> jsonObservationsById = new HashMap<Integer,Observation>(); Observation observation; Observation jsonObservation; BetterJSONObject o; for (int i = 0; i < json.length(); i++) { try { o = new BetterJSONObject(json.getJSONObject(i)); ids.add(o.getInt("id")); jsonObservationsById.put(o.getInt("id"), new Observation(o)); if (isUser) { // Save the project observations aside (will be later used in the syncing of project observations) mProjectObservations.add(o.getJSONArray("project_observations")); // Save project field values Hashtable<Integer, ProjectFieldValue> fields = new Hashtable<Integer, ProjectFieldValue>(); JSONArray jsonFields = o.getJSONArray("observation_field_values").getJSONArray(); for (int j = 0; j < jsonFields.length(); j++) { BetterJSONObject field = new BetterJSONObject(jsonFields.getJSONObject(j)); fields.put(field.getJSONObject("observation_field").getInt("id"), new ProjectFieldValue(field)); } mProjectFieldValues.put(o.getInt("id"), fields); } } catch (JSONException e) { Log.e(TAG, "JSONException: " + e.toString()); } } // find obs with existing ids String joinedIds = StringUtils.join(ids, ","); // TODO why doesn't selectionArgs work for id IN (?) Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id IN ("+joinedIds+")", null, Observation.DEFAULT_SORT_ORDER); // update existing c.moveToFirst(); ContentValues cv; while (c.isAfterLast() == false) { observation = new Observation(c); jsonObservation = jsonObservationsById.get(observation.id); boolean isModified = observation.merge(jsonObservation); cv = observation.getContentValues(); if (observation._updated_at.before(jsonObservation.updated_at)) { // Remote observation is newer (and thus has overwritten the local one) - update its // sync at time so we won't update the remote servers later on (since we won't // accidently consider this an updated record) cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); } if (isModified) { // Only update the DB if needed getContentResolver().update(observation.getUri(), cv, null, null); } existingIds.add(observation.id); c.moveToNext(); } c.close(); // insert new List<Observation> newObservations = new ArrayList<Observation>(); newIds = (ArrayList<Integer>) CollectionUtils.subtract(ids, existingIds); Collections.sort(newIds); for (int i = 0; i < newIds.size(); i++) { jsonObservation = jsonObservationsById.get(newIds.get(i)); cv = jsonObservation.getContentValues(); cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); cv.put(Observation.LAST_COMMENTS_COUNT, jsonObservation.comments_count); cv.put(Observation.LAST_IDENTIFICATIONS_COUNT, jsonObservation.identifications_count); Uri newObs = getContentResolver().insert(Observation.CONTENT_URI, cv); Long newObsId = ContentUris.parseId(newObs); jsonObservation._id = Integer.valueOf(newObsId.toString()); newObservations.add(jsonObservation); } if (isUser) { for (int i = 0; i < newObservations.size(); i++) { jsonObservation = newObservations.get(i); // Save the new observation's photos for (int j = 0; j < jsonObservation.photos.size(); j++) { ObservationPhoto photo = jsonObservation.photos.get(j); photo._observation_id = jsonObservation._id; ContentValues opcv = photo.getContentValues(); opcv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); // So we won't re-add this photo as though it was a local photo opcv.put(ObservationPhoto._OBSERVATION_ID, photo._observation_id); opcv.put(ObservationPhoto._PHOTO_ID, photo._photo_id); opcv.put(ObservationPhoto._ID, photo.id); getContentResolver().insert(ObservationPhoto.CONTENT_URI, opcv); - getContentResolver().insert(ObservationPhoto.CONTENT_URI, opcv); } } } if (isUser) { if (mResponseHeaders != null) { // Delete any local observations which were deleted remotely by the user for (Header header : mResponseHeaders) { if (!header.getName().equalsIgnoreCase("X-Deleted-Observations")) continue; String deletedIds = header.getValue().trim(); getContentResolver().delete(Observation.CONTENT_URI, "(id IN ("+deletedIds+"))", null); break; } mResponseHeaders = null; } } } private ArrayList<NameValuePair> paramsForObservation(Observation observation) { ArrayList<NameValuePair> params = observation.getParams(); params.add(new BasicNameValuePair("ignore_photos", "true")); return params; } private void handleObservationResponse(Observation observation, JSONArray response) { try { if (response == null || response.length() != 1) { return; } JSONObject json = response.getJSONObject(0); BetterJSONObject o = new BetterJSONObject(json); Observation jsonObservation = new Observation(o); observation.merge(jsonObservation); ContentValues cv = observation.getContentValues(); cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(observation.getUri(), cv, null, null); } catch (JSONException e) { // Log.d(TAG, "JSONException: " + e.toString()); } } private class AuthenticationException extends Exception { private static final long serialVersionUID = 1L; } @Override public void onConnectionFailed(ConnectionResult arg0) { Log.e(TAG, "onConnectionFailed: " + (arg0 != null ? arg0.toString() : "null")); // Try using the GPS for the location Thread thread = new Thread(new Runnable() { @Override public void run() { SerializableJSONArray projects; try { projects = getNearByProjects(false); } catch (AuthenticationException e) { projects = new SerializableJSONArray(); e.printStackTrace(); } Intent reply = new Intent(ACTION_PROJECTS_RESULT); reply.putExtra(PROJECTS_RESULT, projects); sendBroadcast(reply); } }); thread.start(); } @Override public void onConnected(Bundle arg0) { Log.i(TAG, "onConnected: " + (arg0 != null ? arg0.toString() : "null")); Thread thread = new Thread(new Runnable() { @Override public void run() { SerializableJSONArray projects; try { projects = getNearByProjects(true); } catch (AuthenticationException e) { projects = new SerializableJSONArray(); e.printStackTrace(); } Intent reply = new Intent(ACTION_PROJECTS_RESULT); reply.putExtra(PROJECTS_RESULT, projects); sendBroadcast(reply); } }); thread.start(); } @Override public void onDisconnected() { Log.e(TAG, "onDisconnected"); } }
true
false
null
null
diff --git a/src/org/mrpdaemon/android/encdroid/GoogleDriveAccount.java b/src/org/mrpdaemon/android/encdroid/GoogleDriveAccount.java index 91987c9..f0916f5 100644 --- a/src/org/mrpdaemon/android/encdroid/GoogleDriveAccount.java +++ b/src/org/mrpdaemon/android/encdroid/GoogleDriveAccount.java @@ -1,279 +1,286 @@ /* * encdroid - EncFS client application for Android * Copyright (C) 2013 Mark R. Pariente * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mrpdaemon.android.encdroid; import java.io.IOException; import java.util.Arrays; import org.mrpdaemon.sec.encfs.EncFSFileProvider; import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import android.accounts.AccountManager; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; import android.widget.Toast; public class GoogleDriveAccount extends Account { // Activity request codes public static final int REQUEST_ACCOUNT_PICKER = 31; public static final int REQUEST_AUTH_TOKEN = 32; // Preference keys private final static String PREFS_KEY = "google_drive_prefs"; private final static String PREF_LINKED = "is_linked"; private final static String PREF_ACCOUNT_NAME = "user_name"; // Login toast type private static enum LoginResult { OK, FAILED }; // Logger tag private final static String TAG = "GoogleDriveAccount"; // Whether we're linked to an account private boolean linked; // Whether link is in progress private boolean linkInProgress; // Whether we're authenticated private boolean authenticated; // Saved preferences private SharedPreferences mPrefs; // Account name private String accountName = null; // Credential object private GoogleAccountCredential credential = null; // Drive API object private Drive driveService = null; // Create drive service private void createDriveService(String accountName) { credential.setSelectedAccountName(accountName); driveService = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build(); Log.v(TAG, "Drive service created: " + driveService.toString()); } // Show toast when logged in private void showLoginToast(final Activity activity, final LoginResult result) { if (activity != null) { activity.runOnUiThread(new Runnable() { @Override public void run() { int stringId = 0; switch (result) { case OK: stringId = R.string.google_drive_login; + break; case FAILED: stringId = R.string.google_drive_login_failed; + break; default: stringId = 0; + break; } Toast.makeText(activity, activity.getString(stringId), Toast.LENGTH_SHORT).show(); } }); } } // Kick off authentication thread private void startAuthThread(final Activity activity) { Thread thread = new Thread(new Runnable() { @Override public void run() { try { credential.getToken(); + + // Do an about request to test if the API works + driveService.about().get().execute(); + Log.v(TAG, "Already authenticated to Google API"); showLoginToast(activity, LoginResult.OK); authenticated = true; } catch (UserRecoverableAuthException e) { Logger.logException(TAG, e); if (activity != null) { activity.startActivityForResult(e.getIntent(), REQUEST_AUTH_TOKEN); } } catch (IOException e) { if (activity != null) { showLoginToast(activity, LoginResult.FAILED); } Logger.logException(TAG, e); } catch (GoogleAuthException e) { if (activity != null) { showLoginToast(activity, LoginResult.FAILED); } Logger.logException(TAG, e); } } }); thread.start(); } public GoogleDriveAccount(EDApplication app) { mPrefs = app.getSharedPreferences(PREFS_KEY, 0); linkInProgress = false; authenticated = false; credential = GoogleAccountCredential.usingOAuth2( app.getApplicationContext(), Arrays.asList(DriveScopes.DRIVE)); // Figure out whether we're linked to an account linked = mPrefs.getBoolean(PREF_LINKED, false); if (linked) { accountName = mPrefs.getString(PREF_ACCOUNT_NAME, null); // Kick off authentication thread createDriveService(accountName); startAuthThread(null); } } @Override public String getName() { return "Google Drive"; } @Override public int getIconResId() { return R.drawable.ic_google_drive; } @Override public boolean isLinked() { return linked; } @Override public boolean isAuthenticated() { return authenticated; } @Override public void startLinkOrAuth(Context context) { Activity activity = (Activity) context; // Select account to link if (linked == false) { linkInProgress = true; activity.startActivityForResult( credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER); } else { createDriveService(accountName); startAuthThread(activity); } } @Override public boolean isLinkOrAuthInProgress() { return linkInProgress; } @Override public boolean resumeLinkOrAuth() { return true; } @Override public void unLink() { // Clear preferences Editor edit = mPrefs.edit(); edit.clear(); edit.commit(); // Clear data linkInProgress = false; authenticated = false; linked = false; accountName = null; driveService = null; Log.d(TAG, "Google Drive account unlinked"); } @Override public String getUserName() { return accountName; } @Override public EncFSFileProvider getFileProvider(String path) { return new GoogleDriveFileProvider(driveService, path); } @Override public boolean forwardActivityResult(Activity origin, int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_ACCOUNT_PICKER: if (resultCode == Activity.RESULT_OK && data != null && data.getExtras() != null) { accountName = data .getStringExtra(AccountManager.KEY_ACCOUNT_NAME); if (accountName != null) { linked = true; // write account name / linked to database Editor edit = mPrefs.edit(); edit.putBoolean(PREF_LINKED, true); edit.putString(PREF_ACCOUNT_NAME, accountName); edit.commit(); createDriveService(accountName); startAuthThread(origin); return true; } } break; case REQUEST_AUTH_TOKEN: if (resultCode == Activity.RESULT_OK) { Log.v(TAG, "Successfully authenticated to Google API"); showLoginToast(origin, LoginResult.OK); authenticated = true; return true; } break; } return false; } }
false
false
null
null
diff --git a/src/core/org/pathvisio/data/SimpleGex.java b/src/core/org/pathvisio/data/SimpleGex.java index 2f833679..dfefe5f7 100644 --- a/src/core/org/pathvisio/data/SimpleGex.java +++ b/src/core/org/pathvisio/data/SimpleGex.java @@ -1,497 +1,499 @@ // PathVisio, // a tool for data visualization and analysis using Biological Pathways // Copyright 2006-2007 BiGCaT Bioinformatics // // 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.pathvisio.data; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import org.pathvisio.data.CachedData.Data; import org.pathvisio.debug.Logger; import org.pathvisio.debug.StopWatch; import org.pathvisio.model.DataSource; import org.pathvisio.model.Xref; import org.pathvisio.util.ProgressKeeper; /** * Responsible for creating and querying a pgex database. * SimpleGex wraps SQL statements in methods, * so the rest of the apps don't need to know the * details of the Database schema. * For this, SimpleGex uses the generic JDBC interface. * * It delegates dealing with the differences between Derby, Hsqldb etc. * to a DBConnector instance. * You need to pass a correct DBConnector instance at creation of * SimpleGex. * * In the PathVisio GUI environment, use GexManager * to create and connect to a centralized Gex. * This will also automatically * find the right DBConnector from the preferences. * * In a head-less or test environment, you can bypass GexManager * to create or connect to one or more databases of any type. */ +//TODO: add function to query # of samples public class SimpleGex { private static final int GEX_COMPAT_VERSION = 1; //Preferred schema version private Connection con; private DBConnector dbConnector; private static CachedData cachedData; /** * Get the {@link Connection} to the Expression-data database * @deprecated Shouldn't be exposed */ public Connection getCon() { return con; } /** * Check whether a connection to the database exists * @return true is a connection exists, false if not */ public boolean isConnected() { return con != null; } private String dbName; /** * Get the database name of the expression data currently loaded */ public String getDbName() { return dbName; } /** * Set the database name of the expression data currently loaded * (Connection is not reset) */ public void setDbName(String name) { dbName = name; } private HashMap<Integer, Sample> samples; /** * Loads the samples used in the expression data (Sample table) in memory */ public void setSamples() { try { ResultSet r = con.createStatement().executeQuery( "SELECT idSample, name, dataType FROM samples" ); samples = new HashMap<Integer, Sample>(); while(r.next()) { int id = r.getInt(1); samples.put(id, new Sample(id, r.getString(2), r.getInt(3))); } } catch (Exception e) { Logger.log.error("while loading data from the 'samples' table: " + e.getMessage(), e); } } PreparedStatement pstSample = null; PreparedStatement pstExpr = null; public void prepare() throws SQLException { pstSample = con.prepareStatement( " INSERT INTO SAMPLES " + " (idSample, name, dataType) " + " VALUES (?, ?, ?) "); pstExpr = con.prepareStatement( "INSERT INTO expression " + " (id, code, ensId, " + " idSample, data, groupId) " + "VALUES (?, ?, ?, ?, ?, ?) "); } /** * add a Sample to the db. * Must call preprare() before. */ public void addSample(int sampleId, String value, int type) throws SQLException { assert (pstSample != null); pstSample.setInt(1, sampleId); pstSample.setString(2, value); pstSample.setInt(3, type); pstSample.execute(); } /** * Add an expression row to the db. Must call prepare() before. */ public void addExpr(Xref ref, String link, String idSample, String value, int group) throws SQLException { assert (pstExpr != null); pstExpr.setString(1, ref.getId()); pstExpr.setString(2, ref.getDataSource().getSystemCode()); pstExpr.setString(3, link); pstExpr.setString(4, idSample); pstExpr.setString(5, value); pstExpr.setInt(6, group); pstExpr.execute(); } public Sample getSample(int id) { return getSamples().get(id); } public HashMap<Integer, Sample> getSamples() { if(samples == null) setSamples(); return samples; } public List<String> getSampleNames() { return getSampleNames(-1); } public List<String> getSampleNames(int dataType) { List<String> names = new ArrayList<String>(); List<Sample> sorted = new ArrayList<Sample>(samples.values()); Collections.sort(sorted); for(Sample s : sorted) { if(dataType == s.dataType || dataType == -1) names.add(s.getName()); } return names; } public List<Sample> getSamples(int dataType) { List<Sample> smps = new ArrayList<Sample>(); List<Sample> sorted = new ArrayList<Sample>(samples.values()); Collections.sort(sorted); for(Sample s : sorted) { if(dataType == s.dataType || dataType == -1) smps.add(s); } return smps; } public List<Data> getCachedData(Xref idc) { if(cachedData != null) { return cachedData.getData(idc); } else { return null; } } public CachedData getCachedData() { return cachedData; } /** * Gets all available expression data for the given gene id and returns a string * containing this data in a HTML table * @param idc the {@link Xref} containing the id and code of the geneproduct to look for * @return String containing the expression data in HTML format or a string displaying a * 'no expression data found' message in HTML format */ public String getDataString(Xref idc) { String noDataFound = "<P><I>No expression data found"; String exprInfo = "<P><B>Gene id on mapp: " + idc.getId() + "</B><TABLE border='1'>"; String colNames = "<TR><TH>Sample name"; if( con == null //Need a connection to the expression data || !GdbManager.isConnected() //and to the gene database ) return noDataFound; List<Data> pwData = cachedData.getData(idc); if(pwData == null) return noDataFound; for(Data d : pwData){ colNames += "<TH>" + d.getXref().getId(); } String dataString = ""; for(Sample s : getSamples().values()) { dataString += "<TR><TH>" + s.name; for(Data d : pwData) { dataString += "<TH>" + d.getSampleData(s.idSample); } } return exprInfo + colNames + dataString + "</TABLE>"; } /** * Loads expression data for all the given gene ids into memory * @param refs Genes to cache the expression data for * (typically all genes in a pathway) */ protected void cacheData(List<Xref> refs, ProgressKeeper p) { cachedData = new CachedData(); StopWatch timer = new StopWatch(); timer.start(); for(Xref pwIdc : refs) { String id = pwIdc.getId(); String code = pwIdc.getDataSource().getSystemCode(); if(cachedData.hasData(pwIdc)) continue; List<String> ensIds = GdbManager.getCurrentGdb().ref2EnsIds(pwIdc); //Get all Ensembl genes for this id HashMap<Integer, Data> groupData = new HashMap<Integer, Data>(); if(ensIds.size() > 0) //Only create a Data object if the id maps to an Ensembl gene { StopWatch tt = new StopWatch(); StopWatch ts = new StopWatch(); tt.start(); groupData.clear(); for(String ensId : ensIds) { try { ts.start(); ResultSet r = con.createStatement().executeQuery( "SELECT id, code, data, idSample, groupId FROM expression " + " WHERE ensId = '" + ensId + "'"); //r contains all genes and data mapping to the Ensembl id while(r.next()) { int group = r.getInt("groupId"); Xref ref = new Xref( r.getString("id"), DataSource.getBySystemCode(r.getString("code")) ); Data data = groupData.get(group); if(data == null) { groupData.put(group, data = new Data(ref, group)); cachedData.addData(pwIdc, data); } int idSample = r.getInt("idSample"); data.setSampleData(idSample, r.getString("data")); } ts.stopToLog("Fetching data for ens id: " + ensId + "\t"); } catch (Exception e) { Logger.log.error("while caching expression data: " + e.getMessage(), e); } } tt.stopToLog(id + ", " + code + ": adding data to cache\t\t"); } if(p.isCancelled()) //Check if the process is interrupted { return; } p.worked(p.getTotalWork() / refs.size()); //Update the progress } p.finished(); timer.stopToLog("Caching expression data\t\t\t"); Logger.log.trace("> Nr of ids queried:\t" + refs.size()); } /** * Connects to the Expression database with * option to remove the old database * @param create true if the old database has to be removed, false for just connecting */ public SimpleGex(String dbName, boolean create, DBConnector connector) throws DataException { dbConnector = connector; + dbConnector.setDbType(DBConnector.TYPE_GEX); if(create) { createNewGex(dbName); } else { con = dbConnector.createConnection(dbName, DBConnector.PROP_NONE); setSamples(); } // try // { // con.setReadOnly( !create ); // } // catch (SQLException e) // { // throw new DataException (e); // } } /** * Connects to the Expression database */ // public static void connect() throws Exception // { // connect(null, false, true); // } // // public static void connect(String dbName) throws Exception // { // connect(dbName, false, true); // } /** * Close the connection to the Expression database, with option to execute the 'SHUTDOWN COMPACT' * statement before calling {@link Connection#close()} */ public void close() throws DataException { if(con != null) { dbConnector.closeConnection(con); con = null; } } /** * Create a new database with the given name. This includes creating tables. * @param dbName The name of the database to create * @return A connection to the newly created database * @throws Exception * @throws Exception */ public final void createNewGex(String dbName) throws DataException { con = dbConnector.createConnection(dbName, DBConnector.PROP_RECREATE); this.dbName = dbName; createGexTables(); } /** * Excecutes several SQL statements to create the tables and indexes for storing * the expression data */ protected void createGexTables() throws DataException { try { con.setReadOnly(false); Statement sh = con.createStatement(); try { sh.execute("DROP TABLE info"); } catch(SQLException e) { Logger.log.warn("Warning: unable to drop expression data tables: "+e.getMessage()); } try { sh.execute("DROP TABLE samples"); } catch(SQLException e) { Logger.log.warn("Warning: unable to drop expression data tables: "+e.getMessage()); } try { sh.execute("DROP TABLE expression"); } catch(SQLException e) { Logger.log.warn("Warning: unable to drop expression data tables: "+e.getMessage()); } sh.execute( "CREATE TABLE " + " info " + "( version INTEGER PRIMARY KEY " + ")"); sh.execute( //Add compatibility version of GEX "INSERT INTO info VALUES ( " + GEX_COMPAT_VERSION + ")"); sh.execute( "CREATE TABLE " + " samples " + " ( idSample INTEGER PRIMARY KEY, " + " name VARCHAR(50), " + " dataType INTEGER " + " ) "); sh.execute( "CREATE TABLE " + " expression " + " ( id VARCHAR(50), " + " code VARCHAR(50), " + " ensId VARCHAR(50), " + " idSample INTEGER, " + " data VARCHAR(50), " + " groupId INTEGER " + // " PRIMARY KEY (id, code, idSample, data) " + ") "); } catch (SQLException e) { throw new DataException (e); } } /** * Creates indices for a newly created expression database. * @param con The connection to the expression database * @throws SQLException */ public void createGexIndices() throws DataException { try { con.setReadOnly(false); Statement sh = con.createStatement(); sh.execute( "CREATE INDEX i_expression_id " + "ON expression(id) "); sh.execute( "CREATE INDEX i_expression_ensId " + "ON expression(ensId) "); sh.execute( "CREATE INDEX i_expression_idSample " + "ON expression(idSample) "); sh.execute( "CREATE INDEX i_expression_data " + "ON expression(data) "); sh.execute( "CREATE INDEX i_expression_code " + "ON expression(code) "); sh.execute( "CREATE INDEX i_expression_groupId" + " ON expression(groupId) "); } catch (SQLException e) { // wrap up the sql exception throw new DataException (e); } } /** * Run this after insterting all sample / expression data * once, to defragment the db and create indices */ public void finalize() throws DataException { dbConnector.compact(con); createGexIndices(); //TODO: why newDb? String newDb = dbConnector.finalizeNewDatabase(dbName); setDbName(newDb); } /** commit inserted data */ public void commit() throws DataException { try { con.commit(); } catch (SQLException e) { throw new DataException (e); } } }
false
false
null
null
diff --git a/src/net/slipcor/pvparena/arena/Arena.java b/src/net/slipcor/pvparena/arena/Arena.java index 4991a3e5..2740515f 100644 --- a/src/net/slipcor/pvparena/arena/Arena.java +++ b/src/net/slipcor/pvparena/arena/Arena.java @@ -1,1230 +1,1231 @@ package net.slipcor.pvparena.arena; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Random; import net.slipcor.pvparena.PVPArena; import net.slipcor.pvparena.arena.ArenaPlayer.Status; import net.slipcor.pvparena.classes.PAClassSign; import net.slipcor.pvparena.classes.PALocation; import net.slipcor.pvparena.classes.PARoundMap; import net.slipcor.pvparena.core.Config; import net.slipcor.pvparena.core.Config.CFG; import net.slipcor.pvparena.core.Debug; import net.slipcor.pvparena.core.Language; import net.slipcor.pvparena.core.Language.MSG; import net.slipcor.pvparena.core.StringParser; import net.slipcor.pvparena.events.PAEndEvent; import net.slipcor.pvparena.events.PAExitEvent; import net.slipcor.pvparena.events.PALeaveEvent; import net.slipcor.pvparena.events.PALoseEvent; import net.slipcor.pvparena.events.PAStartEvent; import net.slipcor.pvparena.events.PAWinEvent; import net.slipcor.pvparena.loadables.ArenaGoal; import net.slipcor.pvparena.loadables.ArenaRegionShape; import net.slipcor.pvparena.loadables.ArenaRegionShape.RegionType; import net.slipcor.pvparena.managers.ConfigurationManager; import net.slipcor.pvparena.managers.ArenaManager; import net.slipcor.pvparena.managers.InventoryManager; import net.slipcor.pvparena.managers.SpawnManager; import net.slipcor.pvparena.managers.TeamManager; import net.slipcor.pvparena.runnables.PlayerDestroyRunnable; import net.slipcor.pvparena.runnables.PlayerStateCreateRunnable; import net.slipcor.pvparena.runnables.SpawnCampRunnable; import net.slipcor.pvparena.runnables.StartRunnable; import net.slipcor.pvparena.runnables.TeleportRunnable; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; /** * <pre>Arena class</pre> * * contains >general< arena methods and variables * * @author slipcor * * @version v0.9.1 */ public class Arena { private Debug db = new Debug(3); private final HashSet<ArenaClass> classes = new HashSet<ArenaClass>(); private final HashSet<ArenaGoal> goals = new HashSet<ArenaGoal>(); private final HashSet<ArenaRegionShape> regions = new HashSet<ArenaRegionShape>(); private final HashSet<PAClassSign> signs = new HashSet<PAClassSign>(); private final HashSet<ArenaTeam> teams = new HashSet<ArenaTeam>(); private PARoundMap rounds; private static String globalprefix = "PVP Arena"; private String name = "default"; private String prefix = "PVP Arena"; private String owner = "%server%"; // arena status private boolean fightInProgress = false; private boolean locked = false; private boolean free = false; private int startCount = 0; private int round = 0; // Runnable IDs public int END_ID = -1; public int REALEND_ID = -1; public int START_ID = -1; public int SPAWNCAMP_ID = -1; private Config cfg; public Arena(String name) { this.name = name; db.i("loading Arena " + name); File file = new File(PVPArena.instance.getDataFolder().getPath() + "/arenas/" + name + ".yml"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } cfg = new Config(file); ConfigurationManager.configParse(this, cfg); } public void addClass(String className, ItemStack[] items) { classes.add(new ArenaClass(className, items)); } public void addRegion(ArenaRegionShape region) { this.regions.add(region); } public void broadcast(String msg) { db.i("@all: " + msg); HashSet<ArenaPlayer> players = getEveryone(); for (ArenaPlayer p : players) { if (p.getArena() == null || !p.getArena().equals(this)) { continue; } this.msg(p.get(), msg); } } /** * send a message to every player, prefix player name and ChatColor * * @param player * the team to send to * @param msg * the message to send * @param player */ public synchronized void broadcastColored(String msg, ChatColor c, Player player) { broadcast(c + player.getName() + ChatColor.WHITE + ": " + msg); } /** * send a message to every player except the given one * * @param sender * the player to exclude * @param msg * the message to send */ public void broadcastExcept(CommandSender sender, String msg) { db.i("@all/" + sender.getName() + ": " + msg); HashSet<ArenaPlayer> players = getEveryone(); for (ArenaPlayer p : players) { if (p.getArena() == null || !p.getArena().equals(this)) { continue; } if (p.getName().equals(sender.getName())) continue; msg(p.get(), msg); } } public void chooseClass(Player player, Sign sign, String className) { db.i("choosing player class"); if (sign != null) { if (getArenaConfig().getBoolean(CFG.PERMS_EXPLICITCLASS)) { db.i("checking class perms"); if (!(player.hasPermission("pvparena.class." + className))) { this.msg(player, Language.parse(MSG.ERROR_NOPERM_CLASS, className)); return; // class permission desired and failed => // announce and OUT } } if (getArenaConfig().getBoolean(CFG.USES_CLASSSIGNSDISPLAY)) { PAClassSign.remove(signs, player); Block block = sign.getBlock(); PAClassSign as = PAClassSign.used(block.getLocation(), signs); if (as == null) { as = new PAClassSign(block.getLocation()); } signs.add(as); if (!as.add(player)) { this.msg(player, Language.parse(MSG.ERROR_CLASS_FULL)); return; } } } InventoryManager.clearInventory(player); ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); if (ap.getArena() == null) { PVPArena.instance.getLogger().warning("failed to set class " + className + " to player " + player.getName()); return; } ap.setArenaClass(className); if (className.equalsIgnoreCase("custom")) { // if custom, give stuff back ArenaPlayer.reloadInventory(this, player); } else { ArenaPlayer.givePlayerFightItems(this, player); } } public void clearRegions() { for (ArenaRegionShape region : regions) { region.reset(); } } /** * initiate the arena start countdown */ public void countDown() { if (START_ID != -1 || this.isFightInProgress()) { Bukkit.getScheduler().cancelTask(START_ID); START_ID = -1; if (!this.isFightInProgress()) { broadcast(Language.parse(MSG.TIMER_COUNTDOWN_INTERRUPTED)); } return; } new StartRunnable(this, getArenaConfig().getInt(CFG.TIME_STARTCOUNTDOWN)); } /** * count all players being ready * * @param arena * the arena to count * @return the number of ready players */ public int countReadyPlayers() { int sum = 0; for (ArenaTeam team : getTeams()) { for (ArenaPlayer p : team.getTeamMembers()) { if (p.getStatus() == Status.READY) { sum++; } } } db.i("counting ready players: " + sum); return sum; } public Config getArenaConfig() { return cfg; } public ArenaClass getClass(String className) { for (ArenaClass ac : classes) { if (ac.getName().equalsIgnoreCase(className)) { return ac; } } return null; } public HashSet<ArenaClass> getClasses() { return classes; } /** * hand over everyone being part of the arena * */ public HashSet<ArenaPlayer> getEveryone() { HashSet<ArenaPlayer> players = new HashSet<ArenaPlayer>(); for (ArenaPlayer ap : ArenaPlayer.getAllArenaPlayers()) { if (this.equals(ap.getArena())) { players.add(ap); } } return players; } /** * hand over all players being member of a team * */ public HashSet<ArenaPlayer> getFighters() { HashSet<ArenaPlayer> players = new HashSet<ArenaPlayer>(); for (ArenaTeam team : getTeams()) { for (ArenaPlayer ap : team.getTeamMembers()) { players.add(ap); } } return players; } public HashSet<ArenaGoal> getGoals() { return round == 0 ? goals : rounds.getGoals(round); } public String getName() { return name; } public String getOwner() { return owner; } public String getPrefix() { return prefix; } public ArenaRegionShape getRegion(String name) { for (ArenaRegionShape region : regions) { if (region.getRegionName().equalsIgnoreCase(name)) { return region; } } return null; } public HashSet<ArenaRegionShape> getRegions() { return regions; } public ArenaTeam getTeam(String name) { for (ArenaTeam team : getTeams()) { if (team.getName().equalsIgnoreCase(name)) { return team; } } return null; } /** * hand over all teams * * @return the arena teams */ public HashSet<ArenaTeam> getTeams() { return teams; } /** * hand over all teams * * @return the arena teams */ public HashSet<String> getTeamNames() { HashSet<String> result = new HashSet<String>(); for (ArenaTeam team : teams) { result.add(team.getName()); } return result; } /** * hand over all teams * * @return the arena teams */ public HashSet<String> getTeamNamesColored() { HashSet<String> result = new HashSet<String>(); for (ArenaTeam team : teams) { result.add(team.getColoredName()); } return result; } /** * return the arena world * * @return the world name */ public String getWorld() { return getArenaConfig().getString(CFG.LOCATION_WORLD); } /** * give customized rewards to players * * @param player * the player to give the reward */ public void giveRewards(Player player) { db.i("giving rewards to " + player.getName()); PVPArena.instance.getAmm().giveRewards(this, player); String sItems = getArenaConfig().getString(CFG.ITEMS_REWARDS, "none"); String[] items = sItems.split(","); if (sItems.equals("none")) { items = null; } boolean random = getArenaConfig().getBoolean(CFG.ITEMS_RANDOM); Random r = new Random(); PAWinEvent dEvent = new PAWinEvent(this, player, items); Bukkit.getPluginManager().callEvent(dEvent); items = dEvent.getItems(); if (items == null || items.length < 1 || cfg.getInt(CFG.ITEMS_MINPLAYERS) > startCount) { return; } int randomItem = r.nextInt(items.length); for (int i = 0; i < items.length; ++i) { ItemStack stack = StringParser.getItemStackFromString(items[i]); if (stack == null) { db.w("unrecognized item: " + items[i]); continue; } if (random && i != randomItem) { continue; } try { player.getInventory().setItem( player.getInventory().firstEmpty(), stack); } catch (Exception e) { this.msg(player, Language.parse(MSG.ERROR_INVENTORY_FULL)); return; } } } public void goalAdd(ArenaGoal goal) { ArenaGoal nugoal = (ArenaGoal) goal.clone(); nugoal.setArena(this); goals.add(nugoal); updateGoals(); } public void goalRemove(ArenaGoal goal) { ArenaGoal nugoal = (ArenaGoal) goal.clone(); nugoal.setArena(this); goals.remove(nugoal); updateGoals(); } public boolean goalToggle(ArenaGoal goal) { ArenaGoal nugoal = (ArenaGoal) goal.clone(); nugoal.setArena(this); boolean contains = false; ArenaGoal removeGoal = nugoal; for (ArenaGoal g : goals) { if (g.getName().equals(goal.getName())) { contains = true; removeGoal = g; break; } } if (contains) { goals.remove(removeGoal); updateGoals(); return false; } else { goals.add(nugoal); updateGoals(); } return true; } /** * check if a custom class player is alive * * @return true if there is a custom class player alive, false otherwise */ public boolean isCustomClassAlive() { for (ArenaPlayer p : getFighters()) { if (p.getStatus().equals(Status.FIGHT) && p.getClass().equals("custom")) { db.i("custom class active: true"); return true; } } db.i("custom class active: false"); return false; } public boolean hasPlayer(Player p) { for (ArenaTeam team : teams) { if (team.hasPlayer(p)) { return true; } } return this.equals(ArenaPlayer.parsePlayer(p.getName()).getArena()); } public void increasePlayerCount() { startCount++; } public boolean isFightInProgress() { return fightInProgress; } public boolean isFreeForAll() { return free; } public boolean isLocked() { return locked; } public void msg(CommandSender sender, String msg) { if (sender == null) { return; } db.i("@" + sender.getName() + ": " + msg); sender.sendMessage(ChatColor.YELLOW + "[" + prefix + "] " + ChatColor.WHITE + msg); } /** * return an understandable representation of a player's death cause * * @param player * the dying player * @param cause * the cause * @param damager * an eventual damager entity * @return a colored string */ public String parseDeathCause(Player player, DamageCause cause, Entity damager) { db.i("return a damage name for : " + cause.toString()); ArenaPlayer ap = null; ArenaTeam team = null; db.i("damager: " + damager); if (damager instanceof Player) { ap = ArenaPlayer.parsePlayer(((Player) damager).getName()); team = ap.getArenaTeam(); } switch (cause) { case ENTITY_ATTACK: if ((damager instanceof Player) && (team != null)) { return team.colorizePlayer(ap.get()) + ChatColor.YELLOW; } return Language.parse(MSG.DEATHCAUSE_CUSTOM); case PROJECTILE: if ((damager instanceof Player) && (team != null)) { return team.colorizePlayer(ap.get()) + ChatColor.YELLOW; } return Language.parse(MSG.getByName("DEATHCAUSE_" + cause.toString())); default: return Language.parse(MSG.getByName("DEATHCAUSE_" + cause.toString())); } } public static void pmsg(CommandSender sender, String msg) { ArenaManager.db.i("@" + sender.getName() + ": " + msg); sender.sendMessage(ChatColor.YELLOW + "[" + globalprefix + "] " + ChatColor.WHITE + msg); } /** * a player leaves from the arena * * @param arena * the arena where this happens * @param player * the leaving player * @param b */ public void playerLeave(Player player, CFG location, boolean silent) { if (!fightInProgress) { startCount--; } db.i("fully removing player from arena"); ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); if (!silent) { ArenaTeam team = ap.getArenaTeam(); if (team != null) { PVPArena.instance.getAmm().playerLeave(this, player, team); broadcastExcept( player, Language.parse(MSG.FIGHT_PLAYER_LEFT, team.colorizePlayer(player) + ChatColor.YELLOW)); } else { broadcastExcept( player, Language.parse(MSG.FIGHT_PLAYER_LEFT, player.getName() + ChatColor.YELLOW)); } this.msg(player, Language.parse(MSG.NOTICE_YOU_LEFT)); } removePlayer(player, getArenaConfig().getString(location), false, silent); if (START_ID != -1) { Bukkit.getScheduler().cancelTask(START_ID); broadcast(Language.parse(MSG.TIMER_COUNTDOWN_INTERRUPTED)); START_ID = -1; } PlayerDestroyRunnable pdr = new PlayerDestroyRunnable(ap); int i = Bukkit.getScheduler().scheduleSyncRepeatingTask(PVPArena.instance, pdr, 5L, 5L); pdr.setId(i); if (ap.getStatus().equals(Status.FIGHT) && isFightInProgress()) { ArenaManager.checkAndCommit(this, silent); } } /** * check if an arena is ready * * @param arena * the arena to check * @return null if ok, error message otherwise */ public String ready() { + db.i("ready check !!"); int players = TeamManager.countPlayersInTeams(this); if (players < 2) { return Language.parse(MSG.ERROR_READY_1_ALONE); } if (players < getArenaConfig().getInt(CFG.READY_MINPLAYERS)) { return Language.parse(MSG.ERROR_READY_4_MISSING_PLAYERS); } if (getArenaConfig().getBoolean(CFG.READY_CHECKEACHPLAYER)) { for (ArenaTeam team : getTeams()) { for (ArenaPlayer ap : team.getTeamMembers()) if (!ap.getStatus().equals(Status.READY)) { return Language.parse(MSG.ERROR_READY_0_ONE_PLAYER_NOT_READY); } } } if (!free) { HashSet<String> activeTeams = new HashSet<String>(); for (ArenaTeam team : getTeams()) { for (ArenaPlayer ap : team.getTeamMembers()) if (!getArenaConfig().getBoolean(CFG.READY_CHECKEACHTEAM) || ap.getStatus().equals(Status.READY)) { activeTeams.add(team.getName()); } } if (activeTeams.size() < 2) { return Language.parse(MSG.ERROR_READY_2_TEAM_ALONE); } } String error = PVPArena.instance.getAgm().ready(this); if (error != null) { return error; } for (ArenaTeam team : getTeams()) { for (ArenaPlayer p : team.getTeamMembers()) { db.i("checking class: " + p.get().getName()); if (p.getArenaClass() == null) { db.i("player has no class"); // player no class! return Language.parse(MSG.ERROR_READY_5_ONE_PLAYER_NO_CLASS); } } } int readyPlayers = countReadyPlayers(); if (players > readyPlayers) { double ratio = getArenaConfig().getDouble(CFG.READY_NEEDEDRATIO); db.i("ratio: " + String.valueOf(ratio)); if (ratio > 0) { double aRatio = Float.valueOf(readyPlayers) / Float.valueOf(players); if ((players > 0) && (aRatio >= ratio)) { return ""; } } return Language.parse(MSG.ERROR_READY_0_ONE_PLAYER_NOT_READY); } return null; } /** * remove a player from the arena * * @param player * the player to remove */ public void remove(Player player) { ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); PALeaveEvent event = new PALeaveEvent(this, player, ap.getStatus() .equals(Status.FIGHT)); Bukkit.getPluginManager().callEvent(event); PAExitEvent exitEvent = new PAExitEvent(this, player); Bukkit.getPluginManager().callEvent(exitEvent); } public void removeClass(String string) { for (ArenaClass ac : classes) { if (ac.equals(string)) { classes.remove(ac); return; } } } /** * remove a player from the arena * * @param player * the player to reset * @param tploc * the coord string to teleport the player to */ public void removePlayer(Player player, String tploc, boolean soft, boolean force) { db.i("removing player " + player.getName() + (soft ? " (soft)" : "") + ", tp to " + tploc); resetPlayer(player, tploc, soft, force); ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); if (!soft && ap.getArenaTeam() != null) { ap.getArenaTeam().remove(ap); } remove(player); if (getArenaConfig().getBoolean(CFG.USES_CLASSSIGNSDISPLAY)) { PAClassSign.remove(signs, player); } } /** * reset an arena * * @param force */ public void reset_players(boolean force) { db.i("resetting player manager"); HashSet<ArenaPlayer> pa = new HashSet<ArenaPlayer>(); for (ArenaTeam team : this.getTeams()) { for (ArenaPlayer p : team.getTeamMembers()) { db.i("player: " + p.getName()); if (p.getArena() == null || !p.getArena().equals(this)) { continue; } else { pa.add(p); } } } for (ArenaPlayer p : pa) { if (p.getStatus() != null && p.getStatus().equals(Status.FIGHT)) { Player z = p.get(); if (!force) { p.addWins(); } resetPlayer(z, getArenaConfig().getString(CFG.TP_WIN, "old"), false, force); if (!force && p.getStatus().equals(Status.FIGHT) && isFightInProgress()) { giveRewards(z); // if we are the winning team, give // reward! } PlayerDestroyRunnable pdr = new PlayerDestroyRunnable(p); int i = Bukkit.getScheduler().scheduleSyncRepeatingTask(PVPArena.instance, pdr, 5L, 5L); pdr.setId(i); } else if (p.getStatus() != null && (p.getStatus().equals(Status.DEAD) || p.getStatus() .equals(Status.LOST))) { PALoseEvent e = new PALoseEvent(this, p.get()); Bukkit.getPluginManager().callEvent(e); Player z = p.get(); if (!force) { p.addLosses(); } resetPlayer(z, getArenaConfig().getString(CFG.TP_LOSE, "old"), false, force); PlayerDestroyRunnable pdr = new PlayerDestroyRunnable(p); int i = Bukkit.getScheduler().scheduleSyncRepeatingTask(PVPArena.instance, pdr, 5L, 5L); pdr.setId(i); } else { resetPlayer(p.get(), getArenaConfig().getString(CFG.TP_LOSE, "old"), false, force); } } } /** * reset an arena */ public void reset(boolean force) { PAEndEvent event = new PAEndEvent(this); Bukkit.getPluginManager().callEvent(event); db.i("resetting arena; force: " + String.valueOf(force)); for (PAClassSign as : signs) { as.clear(); } signs.clear(); reset_players(force); setFightInProgress(false); if (END_ID > -1) Bukkit.getScheduler().cancelTask(END_ID); END_ID = -1; if (REALEND_ID > -1) Bukkit.getScheduler().cancelTask(REALEND_ID); REALEND_ID = -1; PVPArena.instance.getAmm().reset(this, force); clearRegions(); PVPArena.instance.getAgm().reset(this, force); } /** * reset a player to his pre-join values * * @param player * @param string * @param soft */ private void resetPlayer(Player player, String string, boolean soft, boolean force) { if (player == null) { return; } db.i("resetting player: " + player.getName() + (soft ? "(soft)" : "")); ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); if (ap.getState() != null) { ap.getState().unload(); } PVPArena.instance.getAmm().resetPlayer(this, player, force); String sClass = ""; if (ap.getArenaClass() != null) { sClass = ap.getArenaClass().getName(); } if (!sClass.equalsIgnoreCase("custom")) { InventoryManager.clearInventory(player); ArenaPlayer.reloadInventory(this, player); } db.i("string = " + string); ap.setTelePass(true); Bukkit.getScheduler().scheduleSyncDelayedTask(PVPArena.instance, new TeleportRunnable(this, ap, string), 2L); } /** * reset player variables * * @param player * the player to access */ public void unKillPlayer(Player player, DamageCause cause, Entity damager) { db.i("respawning player " + player.getName()); PlayerState.playersetHealth(player, getArenaConfig().getInt(CFG.PLAYER_HEALTH, 20)); player.setFoodLevel(getArenaConfig().getInt(CFG.PLAYER_FOODLEVEL, 20)); player.setSaturation(getArenaConfig().getInt(CFG.PLAYER_SATURATION, 20)); player.setExhaustion((float) getArenaConfig().getDouble(CFG.PLAYER_EXHAUSTION, 0.0)); player.setVelocity(new Vector()); ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); ArenaTeam team = ap.getArenaTeam(); if (team == null) { return; } PlayerState.removeEffects(player); PVPArena.instance.getAmm().parseRespawn(this, player, team, cause, damager); player.setFireTicks(0); player.setNoDamageTicks(60); } public void selectClass(ArenaPlayer ap, String cName) { for (ArenaClass c : classes) { if (c.getName().equalsIgnoreCase(cName)) { ap.setArenaClass(c); ArenaClass.equip(ap.get(), c.getItems()); msg(ap.get(), Language.parse(MSG.CLASS_PREVIEW, c.getName())); } } msg(ap.get(), Language.parse(MSG.ERROR_CLASS_NOT_FOUND, cName)); } public void setArenaConfig(Config cfg) { this.cfg = cfg; } public void setFightInProgress(boolean fightInProgress) { this.fightInProgress = fightInProgress; } public void setFree(boolean b) { free = b; } public void setOwner(String owner) { this.owner = owner; } public void setLocked(boolean locked) { this.locked = locked; } public void setPrefix(String prefix) { this.prefix = prefix; } /** * set the arena world * * @param sWorld * the world name */ public void setWorld(String sWorld) { getArenaConfig().set(CFG.LOCATION_WORLD, sWorld); getArenaConfig().save(); } /** * damage every actively fighting player for being near a spawn */ public void spawnCampPunish() { HashMap<Location, ArenaPlayer> players = new HashMap<Location, ArenaPlayer>(); for (ArenaPlayer ap : getFighters()) { if (!ap.getStatus().equals(Status.FIGHT)) { continue; } players.put(ap.get().getLocation(), ap); } for (ArenaTeam team : teams) { if (team.getTeamMembers().size() < 1) { continue; } String sTeam = team.getName(); for (PALocation spawnLoc : SpawnManager.getSpawns(this, sTeam)) { for (Location playerLoc : players.keySet()) { if (spawnLoc.getDistance(new PALocation(playerLoc)) < 3) { players.get(playerLoc) .get() .damage(getArenaConfig().getInt(CFG.DAMAGE_SPAWNCAMP)); } } } } } public void spawnSet(String node, PALocation paLocation) { cfg.setManually("spawns." + node, Config.parseToString(paLocation)); cfg.save(); } public void spawnUnset(String node) { cfg.setManually("spawns." + node, null); cfg.save(); } /** * initiate the arena start */ public void start() { START_ID = -1; if (isFightInProgress()) { return; } int sum = 0; for (ArenaTeam team : getTeams()) { for (ArenaPlayer ap : team.getTeamMembers()) { if (ap.getStatus().equals(Status.LOUNGE) || ap.getStatus().equals(Status.READY)) { sum++; } } } if (sum < 2) { for (ArenaPlayer ap : getFighters()) { playerLeave(ap.get(), CFG.TP_EXIT, false); } } else { teleportAllToSpawn(); setFightInProgress(true); } } public void stop(boolean force) { for (ArenaPlayer p : getFighters()) { this.playerLeave(p.get(), CFG.TP_EXIT, true); } reset(force); } /** * teleport all players to their respective spawn */ public void teleportAllToSpawn() { PAStartEvent event = new PAStartEvent(this); Bukkit.getPluginManager().callEvent(event); db.i("teleporting all players to their spawns"); if (!isFreeForAll()) { for (ArenaTeam team : teams) { for (ArenaPlayer ap : team.getTeamMembers()) { tpPlayerToCoordName(ap.get(), team.getName() + "spawn"); ap.setStatus(Status.FIGHT); } } } PVPArena.instance.getAgm().teleportAllToSpawn(this); broadcast(Language.parse(MSG.FIGHT_BEGINS)); PVPArena.instance.getAmm().teleportAllToSpawn(this); db.i("teleported everyone!"); SpawnCampRunnable scr = new SpawnCampRunnable(this, 0); SPAWNCAMP_ID = Bukkit.getScheduler().scheduleSyncRepeatingTask( PVPArena.instance, scr, 100L, getArenaConfig().getInt(CFG.TIME_REGIONTIMER)); scr.setId(SPAWNCAMP_ID); for (ArenaRegionShape region : regions) { if (region.getFlags().size() > 0) { region.initTimer(); } else if (region.getType().equals(RegionType.BATTLE)) { region.initTimer(); } } } /** * send a message to every player of a given team * * @param player * the team to send to * @param msg * the message to send * @param player */ public synchronized void tellTeam(String sTeam, String msg, ChatColor c, Player player) { ArenaTeam team = this.getTeam(sTeam); if (team == null) { return; } sTeam = team.getName(); db.i("@" + sTeam + ": " + msg); for (ArenaPlayer p : team.getTeamMembers()) { p.get().sendMessage( c + "[" + sTeam + "] " + player.getName() + ChatColor.WHITE + ": " + msg); } } /** * teleport a given player to the given coord string * * @param player * the player to teleport * @param place * the coord string */ public void tpPlayerToCoordName(Player player, String place) { db.i("teleporting " + player + " to coord " + place); if (player.isInsideVehicle()) { player.getVehicle().eject(); } if (place.endsWith("lounge")) { // at the start of the match if (getArenaConfig().getBoolean(CFG.CHAT_DEFAULTTEAM) && getArenaConfig().getBoolean(CFG.CHAT_ENABLED)) { ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); ap.setPublicChatting(true); } } PVPArena.instance.getAmm().tpPlayerToCoordName(this, player, place); ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); if (place.equals("spectator")) { if (getFighters().contains(ap)) { ap.setStatus(Status.LOST); } else { ap.setStatus(Status.WATCH); } } PALocation loc = SpawnManager.getCoords(this, place); if (loc == null) { PVPArena.instance.getLogger().warning("Spawn null : " + place); return; } ap.setTelePass(true); player.teleport(loc.toLocation()); player.setNoDamageTicks(60); ap.setTelePass(false); } public boolean tryJoin(Player player, ArenaTeam team) { ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); db.i("trying to join player " + player.getName()); if (ap.getStatus().equals(Status.NULL)) { // joining DIRECTLY - save loc !! ap.setLocation(new PALocation(player.getLocation())); } if (ap.getArenaClass() == null) { String autoClass = cfg.getString(CFG.READY_AUTOCLASS); if (autoClass != null && !autoClass.equals("none")) { if (getClass(autoClass) == null) { msg(player, Language.parse(MSG.ERROR_CLASS_NOT_FOUND, "autoClass")); return false; } } } ap.setArena(this); team.add(ap); ap.setStatus(Status.FIGHT); tpPlayerToCoordName(player, (isFreeForAll()?"":team.getName()) + "spawn"); Bukkit.getScheduler().scheduleAsyncDelayedTask(PVPArena.instance, new PlayerStateCreateRunnable(ap, player), 2L); return true; } private void updateGoals() { List<String> list = new ArrayList<String>(); for (ArenaGoal goal : goals) { list.add(goal.getName()); } cfg.set(CFG.LISTS_GOALS, list); cfg.save(); } /** * Setup an arena based on legacy goals: * <pre> * teams - team lives arena * teamdm - team deathmatch arena * dm - deathmatch arena * free - deathmatch arena * ctf - capture the flag arena * ctp - capture the pumpkin arena * spleef - free for all with teamkill off * </pre> * @param string legacy goal */ public void getLegacyGoals(String string) { setFree(false); string = string.toLowerCase(); if (string.equals("teams")) { goalAdd(PVPArena.instance.getAgm().getType("TeamLives")); } else if (string.equals("teamdm")) { goalAdd(PVPArena.instance.getAgm().getType("TeamDeathMatch")); } else if (string.equals("dm")) { goalAdd(PVPArena.instance.getAgm().getType("PlayerDeathMatch")); this.setFree(true); } else if (string.equals("free")) { goalAdd(PVPArena.instance.getAgm().getType("PlayerLives")); this.setFree(true); } else if (string.equals("spleef")) { goalAdd(PVPArena.instance.getAgm().getType("PlayerLives")); this.setFree(true); this.getArenaConfig().set(CFG.PERMS_TEAMKILL, false); } else if (string.equals("ctf")) { goalAdd(PVPArena.instance.getAgm().getType("Flags")); } else if (string.equals("ctp")) { goalAdd(PVPArena.instance.getAgm().getType("Flags")); cfg.set(CFG.GOAL_FLAGS_FLAGTYPE, "PUMPKIN"); cfg.save(); } updateGoals(); } public HashSet<ArenaRegionShape> getRegionsByType(RegionType battle) { HashSet<ArenaRegionShape> result = new HashSet<ArenaRegionShape>(); for (ArenaRegionShape rs : regions) { if (rs.getType().equals(battle)) result.add(rs); } return result; } public void setRoundMap(ConfigurationSection cs) { // TODO Auto-generated method stub String seriously = "fix this"; rounds = new PARoundMap(this, new HashSet<HashSet<String>>()); } public void setRound(int i) { round = i; } } diff --git a/src/net/slipcor/pvparena/listeners/PlayerListener.java b/src/net/slipcor/pvparena/listeners/PlayerListener.java index 8b6897fe..f5be9c12 100644 --- a/src/net/slipcor/pvparena/listeners/PlayerListener.java +++ b/src/net/slipcor/pvparena/listeners/PlayerListener.java @@ -1,519 +1,519 @@ package net.slipcor.pvparena.listeners; import java.util.ArrayList; import java.util.List; import net.slipcor.pvparena.PVPArena; import net.slipcor.pvparena.arena.Arena; import net.slipcor.pvparena.arena.ArenaPlayer; import net.slipcor.pvparena.arena.ArenaPlayer.Status; import net.slipcor.pvparena.arena.ArenaTeam; import net.slipcor.pvparena.arena.PlayerState; import net.slipcor.pvparena.classes.PABlockLocation; import net.slipcor.pvparena.classes.PACheck; import net.slipcor.pvparena.core.Config.CFG; import net.slipcor.pvparena.core.Debug; import net.slipcor.pvparena.core.Language; import net.slipcor.pvparena.core.Language.MSG; import net.slipcor.pvparena.core.Update; import net.slipcor.pvparena.loadables.ArenaRegionShape; import net.slipcor.pvparena.loadables.ArenaRegionShape.RegionProtection; import net.slipcor.pvparena.managers.ArenaManager; import net.slipcor.pvparena.managers.InventoryManager; import net.slipcor.pvparena.managers.TeamManager; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerVelocityEvent; /** * <pre>Player Listener class</pre> * * @author slipcor * * @version v0.9.3 */ public class PlayerListener implements Listener { private static Debug db = new Debug(23); @EventHandler(priority = EventPriority.LOWEST) public void onPlayerChat(AsyncPlayerChatEvent event) { Player player = event.getPlayer(); Arena arena = ArenaPlayer.parsePlayer(player.getName()).getArena(); ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); if (arena == null) { return; // no fighting player => OUT } ArenaTeam team = ap.getArenaTeam(); if (team == null) { return; // no fighting player => OUT } db.i("fighting player chatting!"); String sTeam = team.getName(); if (!arena.getArenaConfig().getBoolean(CFG.CHAT_ONLYPRIVATE)) { if (!arena.getArenaConfig().getBoolean(CFG.CHAT_ENABLED)) { return; // no chat editing } if (ap.isPublicChatting()) { return; // player not privately chatting } arena.tellTeam(sTeam, event.getMessage(), team.getColor(), event.getPlayer()); event.setCancelled(true); return; } if (arena.getArenaConfig().getBoolean(CFG.CHAT_ENABLED) && !ap.isPublicChatting()) { arena.tellTeam(sTeam, event.getMessage(), team.getColor(), event.getPlayer()); event.setCancelled(true); return; } arena.broadcastColored(event.getMessage(), team.getColor(), event.getPlayer()); // event.setCancelled(true); } @EventHandler(priority = EventPriority.LOWEST) public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { Player player = event.getPlayer(); Arena arena = ArenaPlayer.parsePlayer(player.getName()).getArena(); if (arena == null || player.isOp()) { return; // no fighting player => OUT } List<String> list = PVPArena.instance.getConfig().getStringList( "whitelist"); list.add("pa"); list.add("pvparena"); db.i("checking command whitelist"); for (String s : list) { if (event.getMessage().startsWith("/" + s)) { db.i("command allowed: " + s); return; } } list = arena.getArenaConfig().getStringList(CFG.LISTS_CMDWHITELIST.getNode(), new ArrayList<String>()); if (list == null || list.size() < 1) { list = new ArrayList<String>(); list.add("ungod"); arena.getArenaConfig().set(CFG.LISTS_CMDWHITELIST, list); arena.getArenaConfig().save(); } list.add("pa"); list.add("pvparena"); db.i("checking command whitelist"); for (String s : list) { if (event.getMessage().startsWith("/" + s)) { db.i("command allowed: " + s); return; } } db.i("command blocked: " + event.getMessage()); arena.msg(player, Language.parse(MSG.ERROR_COMMAND_BLOCKED, event.getMessage())); event.setCancelled(true); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerDropItem(PlayerDropItemEvent event) { Player player = event.getPlayer(); ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); Arena arena = ap.getArena(); if (arena == null) return; // no fighting player => OUT if (ap.getStatus().equals(Status.READY) || ap.getStatus().equals(Status.LOUNGE)) { event.setCancelled(true); arena.msg(player, (Language.parse(MSG.NOTICE_NO_DROP_ITEM))); return; } if (!BlockListener.isProtected(player.getLocation(), event, RegionProtection.DROP)) { return; // no drop protection } db.i("onPlayerDropItem: fighting player"); arena.msg(player, (Language.parse(MSG.NOTICE_NO_DROP_ITEM))); event.setCancelled(true); // cancel the drop event for fighting players, with message } @EventHandler(priority = EventPriority.LOW) public void onPlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); Arena arena = ArenaPlayer.parsePlayer(player.getName()).getArena(); if (arena == null) return; PACheck.handlePlayerDeath(arena, player, event); } /** * pretend a player death * * @param arena * the arena the player is playing in * @param player * the player to kill * @param eEvent * the event triggering the death */ public static void finallyKillPlayer(Arena arena, Player player, Event eEvent) { EntityDamageEvent cause = null; if (eEvent instanceof EntityDeathEvent) { cause = player.getLastDamageCause(); } else if (eEvent instanceof EntityDamageEvent) { cause = ((EntityDamageEvent) eEvent); } ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); ArenaTeam team = ap.getArenaTeam(); String playerName = (team != null) ? team.colorizePlayer(player) : player.getName(); PVPArena.instance.getAmm().commitPlayerDeath(arena, player, cause); arena.broadcast(Language.parse( MSG.FIGHT_KILLED_BY, playerName + ChatColor.YELLOW, arena.parseDeathCause(player, cause.getCause(), ArenaPlayer.getLastDamagingPlayer(cause)))); if (arena.isCustomClassAlive() || arena.getArenaConfig().getBoolean(CFG.PLAYER_DROPSINVENTORY)) { InventoryManager.drop(player); } if (ArenaPlayer.parsePlayer(player.getName()).getArenaClass() == null || !ArenaPlayer.parsePlayer(player.getName()).getArenaClass().getName().equalsIgnoreCase("custom")) { InventoryManager.clearInventory(player); } arena.removePlayer(player, CFG.TP_DEATH.toString(), true, false); ap.setStatus(Status.LOST); ap.addDeath(); PlayerState.fullReset(arena, player); if (ArenaManager.checkAndCommit(arena, false)) return; } @EventHandler(priority = EventPriority.LOW) public void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); db.i("onPlayerInteract"); if (event.getAction().equals(Action.PHYSICAL)) { db.i("returning: physical"); return; } Arena arena = null; if (event.hasBlock()) { arena = ArenaManager.getArenaByRegionLocation(new PABlockLocation(event.getClickedBlock().getLocation())); } if (arena != null && PVPArena.instance.getAmm().onPlayerInteract(arena, event)) { db.i("returning: #1"); return; } if (PACheck.handleSetFlag(player, event.getClickedBlock())) { db.i("returning: #2"); return; } if (ArenaRegionShape.checkRegionSetPosition(event, player)) { db.i("returning: #3"); return; } arena = ArenaPlayer.parsePlayer(player.getName()).getArena(); if (arena == null) { db.i("returning: #4"); ArenaManager.trySignJoin(event, player); return; } PACheck.handleInteract(arena, player, event.getClickedBlock()); if (arena.isFightInProgress() && !PVPArena.instance.getAgm().allowsJoinInBattle(arena)) { db.i("exiting! fight in progress AND no INBATTLEJOIN arena!"); return; } ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); ArenaTeam team = ap.getArenaTeam(); if (!ap.getStatus().equals(Status.FIGHT)) { db.i("cancelling: no class"); // fighting player inside the lobby! event.setCancelled(true); } if (team == null) { db.i("returning: no team"); return; } if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { Block block = event.getClickedBlock(); db.i("player team: " + team.getName()); if (block.getState() instanceof Sign) { db.i("sign click!"); Sign sign = (Sign) block.getState(); if (((sign.getLine(0).equalsIgnoreCase("custom")) || (arena.getClass(sign.getLine(0)) != null)) && (team != null)) { arena.chooseClass(player, sign, sign.getLine(0)); } return; } db.i("block click!"); Material mMat = Material.IRON_BLOCK; db.i("reading ready block"); try { mMat = Material .getMaterial(arena.getArenaConfig().getInt(CFG.READY_BLOCK)); if (mMat == Material.AIR) mMat = Material.getMaterial(arena.getArenaConfig() .getString(CFG.READY_BLOCK)); db.i("mMat now is " + mMat.name()); } catch (Exception e) { db.i("exception reading ready block"); String sMat = arena.getArenaConfig().getString(CFG.READY_BLOCK); try { mMat = Material.getMaterial(sMat); db.i("mMat now is " + mMat.name()); } catch (Exception e2) { Language.log_warning(MSG.ERROR_MAT_NOT_FOUND, sMat); } } db.i("clicked " + block.getType().name() + ", is it " + mMat.name() + "?"); if (block.getTypeId() == mMat.getId()) { db.i("clicked ready block!"); if (ap.getClass().equals("")) { return; // not chosen class => OUT } if (arena.START_ID != -1) { return; // counting down => OUT } db.i("==============="); db.i("===== class: " + ap.getClass() + " ====="); db.i("==============="); - if (!arena.isFightInProgress() && arena.START_ID == -1) { + if (!arena.isFightInProgress()) { if (!ap.getStatus().equals(Status.READY)) arena.msg(player, Language.parse(MSG.READY_DONE)); ap.setStatus(Status.READY); if (arena.getArenaConfig().getBoolean(CFG.USES_EVENTEAMS)) { if (!TeamManager.checkEven(arena)) { arena.msg(player, Language.parse(MSG.NOTICE_WAITING_EQUAL)); return; // even teams desired, not done => announce } } if (!ArenaRegionShape.checkRegions(arena)) { arena.msg(player, Language.parse(MSG.NOTICE_WAITING_FOR_ARENA)); return; } String error = arena.ready(); if (error == null) { arena.start(); } else if (error.equals("")) { arena.countDown(); } else { arena.msg(player, error); } return; } if (arena.isFreeForAll()) { arena.tpPlayerToCoordName(player, "spawn"); } else { arena.tpPlayerToCoordName(player, team.getName() + "spawn"); } ArenaPlayer.parsePlayer(player.getName()).setStatus(Status.FIGHT); PVPArena.instance.getAmm().lateJoin(arena, player); } } } @EventHandler(priority = EventPriority.LOWEST) public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (player.isDead()) { return; } ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); ap.setArena(null); // instantiate and/or reset a player. This fixes issues with leaving // players // and makes sure every player is an arenaplayer ^^ ap.readDump(); Arena a = ap.getArena(); if (a != null) { a.playerLeave(player, CFG.TP_EXIT, true); } if (!player.isOp()) { return; // no OP => OUT } db.i("OP joins the game"); Update.message(player); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerKicked(PlayerKickEvent event) { Player player = event.getPlayer(); Arena arena = ArenaPlayer.parsePlayer(player.getName()).getArena(); if (arena == null) return; // no fighting player => OUT arena.playerLeave(player, CFG.TP_EXIT, false); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerRespawn(PlayerRespawnEvent event) { Player player = event.getPlayer(); ArenaPlayer ap = ArenaPlayer.parsePlayer(player.getName()); ap.setArena(null); // instantiate and/or reset a player. This fixes issues with leaving // players and makes sure every player is an arenaplayer ^^ ap.readDump(); Arena a = ap.getArena(); if (a != null) { a.playerLeave(player, CFG.TP_EXIT, true); } } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerPickupItem(PlayerPickupItemEvent event) { if (event.isCancelled()) return; Player player = event.getPlayer(); Arena arena = ArenaPlayer.parsePlayer(player.getName()).getArena(); if (arena == null || BlockListener.isProtected(player.getLocation(), event, RegionProtection.PICKUP)) return; // no fighting player or no powerups => OUT PVPArena.instance.getAmm().onPlayerPickupItem(arena, event); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); Arena arena = ArenaPlayer.parsePlayer(player.getName()).getArena(); if (arena == null) return; // no fighting player => OUT arena.playerLeave(player, CFG.TP_EXIT, false); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerTeleport(PlayerTeleportEvent event) { Player player = event.getPlayer(); Arena arena = ArenaPlayer.parsePlayer(player.getName()).getArena(); if (arena == null) { arena = ArenaManager.getArenaByRegionLocation(new PABlockLocation(event.getTo())); if (arena == null) { return; // no fighting player and no arena location => OUT } } db.i("onPlayerTeleport: fighting player '"+event.getPlayer().getName()+"' (uncancel)"); event.setCancelled(false); // fighting player - first recon NOT to // cancel! PVPArena.instance.getAmm().onPlayerTeleport(arena, event); db.i("aimed location: " + event.getTo().toString()); if (ArenaPlayer.parsePlayer(player.getName()).getTelePass() || player.hasPermission("pvparena.telepass")) return; // if allowed => OUT db.i("telepass: no!!"); if (arena.getRegion("battlefield") != null) { if (arena.getRegion("battlefield").contains(new PABlockLocation(event.getFrom())) && arena.getRegion("battlefield").contains(new PABlockLocation(event.getTo()))) { return; // teleporting inside the arena: allowed! } } db.i("onPlayerTeleport: no tele pass, cancelling!"); event.setCancelled(true); // cancel and tell arena.msg(player, Language.parse(MSG.NOTICE_NO_TELEPORT)); } @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerVelocity(PlayerVelocityEvent event) { if (event.isCancelled()) return; Player player = event.getPlayer(); Arena arena = ArenaPlayer.parsePlayer(player.getName()).getArena(); if (arena == null) return; // no fighting player or no powerups => OUT PVPArena.instance.getAmm().onPlayerVelocity(arena, event); } } \ No newline at end of file diff --git a/src/net/slipcor/pvparena/modules/StandardLounge.java b/src/net/slipcor/pvparena/modules/StandardLounge.java index be5cf030..f775e73d 100644 --- a/src/net/slipcor/pvparena/modules/StandardLounge.java +++ b/src/net/slipcor/pvparena/modules/StandardLounge.java @@ -1,175 +1,181 @@ package net.slipcor.pvparena.modules; import java.util.Iterator; import java.util.Set; import net.slipcor.pvparena.PVPArena; import net.slipcor.pvparena.arena.Arena; import net.slipcor.pvparena.arena.ArenaPlayer; import net.slipcor.pvparena.arena.ArenaTeam; import net.slipcor.pvparena.arena.ArenaPlayer.Status; import net.slipcor.pvparena.classes.PACheck; import net.slipcor.pvparena.classes.PALocation; import net.slipcor.pvparena.core.Debug; import net.slipcor.pvparena.core.Language; import net.slipcor.pvparena.core.Config.CFG; import net.slipcor.pvparena.core.Language.MSG; import net.slipcor.pvparena.loadables.ArenaModule; import net.slipcor.pvparena.runnables.PlayerStateCreateRunnable; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * <pre>Arena Module class "StandardLounge"</pre> * * Enables joining to lounges instead of the battlefield * * @author slipcor * * @version v0.9.3 */ public class StandardLounge extends ArenaModule { private int priority = 1; public StandardLounge() { super("StandardLounge"); db = new Debug(300); } @Override public String version() { return "v0.9.3.0"; } @Override public String checkForMissingSpawns(Arena arena, Set<String> list) { // not random! we need teams * 2 (lounge + spawn) + exit + spectator db.i("parsing not random"); Iterator<String> iter = list.iterator(); int lounges = 0; while (iter.hasNext()) { String s = iter.next(); db.i("parsing '" + s + "'"); if (s.endsWith("lounge") && (!s.equals("lounge"))) { lounges++; } } if (lounges == arena.getTeams().size()) { return null; } return lounges + "/" + arena.getTeams().size() + "x lounge"; } public PACheck checkJoin(Arena arena, CommandSender sender, PACheck result, boolean join) { if (!join) return result; // we only care about joining, ignore spectators if (result.getPriority() > this.priority) { return result; // Something already is of higher priority, ignore! } Player p = (Player) sender; if (arena == null) { return result; // arena is null - maybe some other mod wants to handle that? ignore! } if (arena.isLocked() && !p.hasPermission("pvparena.admin") && !(p.hasPermission("pvparena.create") && arena.getOwner().equals(p.getName()))) { result.setError(this, Language.parse(MSG.ERROR_NOPERM, Language.parse(MSG.ERROR_NOPERM_X_JOIN))); return result; } if (arena.isFightInProgress() && !arena.getArenaConfig().getBoolean(CFG.PERMS_JOININBATTLE)) { result.setError(this, Language.parse(MSG.ERROR_FIGHT_IN_PROGRESS)); return result; } ArenaPlayer ap = ArenaPlayer.parsePlayer(sender.getName()); if (ap.getArena() != null) { result.setError(this, Language.parse(MSG.ERROR_ARENA_ALREADY_PART_OF, ap.getArena().getName())); return result; } if (ap.getArenaClass() == null) { String autoClass = arena.getArenaConfig().getString(CFG.READY_AUTOCLASS); if (autoClass != null && !autoClass.equals("none")) { if (arena.getClass(autoClass) == null) { result.setError(this, Language.parse(MSG.ERROR_CLASS_NOT_FOUND, "autoClass")); return result; } } } result.setPriority(this, priority); return result; } public PACheck checkStart(Arena arena, PACheck result) { if (result.getPriority() > this.priority) { return result; // Something already is of higher priority, ignore! } if (arena == null) { return result; // arena is null - maybe some other mod wants to handle that? ignore! } String error = String.valueOf(arena.ready()); if (error != null) { result.setError(this, error); return result; } result.setPriority(this, priority); return result; } @Override public boolean hasSpawn(Arena arena, String s) { if (arena.isFreeForAll()) { return s.startsWith("lounge"); } for (ArenaTeam team : arena.getTeams()) { if (s.startsWith(team.getName() + "lounge")) { return true; } } return false; } @Override public boolean isActive(Arena arena) { return arena.getArenaConfig().getBoolean(CFG.MODULES_STANDARDLOUNGE_ACTIVE); } @Override public void commitJoin(Arena arena, Player sender, ArenaTeam team) { // standard join --> lounge ArenaPlayer ap = ArenaPlayer.parsePlayer(sender.getName()); Bukkit.getScheduler().scheduleAsyncDelayedTask(PVPArena.instance, new PlayerStateCreateRunnable(ap, ap.get()), 2L); //ArenaPlayer.prepareInventory(arena, ap.get()); ap.setLocation(new PALocation(ap.get().getLocation())); ap.setArena(arena); team.add(ap); if (arena.isFreeForAll()) { arena.tpPlayerToCoordName(ap.get(), "lounge"); } else { arena.tpPlayerToCoordName(ap.get(), team.getName() + "lounge"); } ap.setStatus(Status.LOUNGE); arena.msg(sender, Language.parse(arena, CFG.MSG_LOUNGE)); if (arena.isFreeForAll()) { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINED)); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINED, sender.getName())); } else { arena.msg(sender, arena.getArenaConfig().getString(CFG.MSG_YOUJOINEDTEAM).replace("%1%", team.getColoredName() + "�r")); arena.broadcastExcept(sender, Language.parse(arena, CFG.MSG_PLAYERJOINEDTEAM, sender.getName(), team.getColoredName() + "�r")); } } + + @Override + public void parseJoin(Arena arena, CommandSender player, ArenaTeam team) { + if (arena.START_ID != -1) + arena.countDown(); + } } \ No newline at end of file diff --git a/src/net/slipcor/pvparena/runnables/StartRunnable.java b/src/net/slipcor/pvparena/runnables/StartRunnable.java index 30ddb4fd..b93a4123 100644 --- a/src/net/slipcor/pvparena/runnables/StartRunnable.java +++ b/src/net/slipcor/pvparena/runnables/StartRunnable.java @@ -1,41 +1,40 @@ package net.slipcor.pvparena.runnables; import org.bukkit.Bukkit; import net.slipcor.pvparena.arena.Arena; import net.slipcor.pvparena.core.Debug; import net.slipcor.pvparena.core.Language.MSG; /** * <pre>Arena Runnable class "Start"</pre> * * An arena timer to start the arena * * @author slipcor * * @version v0.9.3 */ public class StartRunnable extends ArenaRunnable { private Debug db = new Debug(43); /** * create a timed arena start runnable * * @param a * the arena we are running in */ public StartRunnable(Arena a, int i) { super(MSG.ARENA_STARTING_IN.getNode(), i, null, a, false); db.i("StartRunnable constructor: " + id); a.START_ID = id; } @Override protected void commit() { Bukkit.getScheduler().cancelTask(arena.START_ID); db.i("StartRunnable commiting"); - Bukkit.getScheduler().cancelTask(id); arena.start(); } }
false
false
null
null
diff --git a/src/java/org/apache/log4j/PatternLayout.java b/src/java/org/apache/log4j/PatternLayout.java index bfa3ef2e..e2f0dd22 100644 --- a/src/java/org/apache/log4j/PatternLayout.java +++ b/src/java/org/apache/log4j/PatternLayout.java @@ -1,554 +1,554 @@ /* * Copyright (C) The Apache Software Foundation. All rights reserved. * * This software is published under the terms of the Apache Software License * version 1.1, a copy of which has been included with this distribution in * the LICENSE file. */ package org.apache.log4j; import org.apache.log4j.Category; import org.apache.log4j.Priority; import org.apache.log4j.Layout; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.NDC; import org.apache.log4j.helpers.PatternParser; import org.apache.log4j.helpers.PatternConverter; import org.apache.log4j.helpers.OptionConverter; import java.io.PrintWriter; import java.io.StringWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.Vector; import java.text.FieldPosition; // Contributors: Nelson Minar <nelson@monkey.org> // Anders Kristensen <akristensen@dynamicsoft.com> /** A flexible layout configurable with pattern string. <p>The goal of this class is to {@link #format format} a {@link LoggingEvent} and return the results as a String. The results depend on the <em>conversion pattern</em>. <p>The conversion pattern is closely related to the conversion pattern of the printf function in C. A conversion pattern is composed of literal text and format control expressions called <em>conversion specifiers</em>. <p><i>You are free to insert any literal text within the conversion pattern.</i> <p>Each conversion specifier starts with a percent sign (%) and is followed by optional <em>format modifiers</em> and a <em>conversion character</em>. The conversion character specifies the type of data, e.g. category, priority, date, thread name. The format modifiers control such things as field width, padding, left and right justification. The following is a simple example. <p>Let the conversion pattern be <b>"%-5p [%t]: %m%n"</b> and assume that the log4j environment was set to use a PatternLayout. Then the statements <pre> Category root = Category.getRoot(); root.debug("Message 1"); root.warn("Message 2"); </pre> would yield the output <pre> DEBUG [main]: Message 1 WARN [main]: Message 2 </pre> <p>Note that there is no explicit separator between text and conversion specifiers. The pattern parser knows when it has reached the end of a conversion specifier when it reads a conversion character. In the example above the conversion specifier <b>%-5p</b> means the priority of the logging event should be left justfied to a with of five characters. The recognized conversion characters are <p> <table border=1 CELLPADDING=8> <th>Conversion Character</th> <th>Effect</th> <tr> <td align=center><b>c</b></td> <td>Used to output the category of the logging event. The category conversion specifier can be optionally followed by <em>precision specifier</em>, that is a decimal constant in brackets. <p>If a precision specifier is given, then only the corresponding number of right most components of the category name will be printed. By default the category name is printed in full. <p>For example, for the category name "a.b.c" the pattern <b>%c{2}</b> will output "b.c". </td> </tr> <tr> <td align=center><b>C</b></td> <td>Used to output the fully qualified class name of the caller issuing the logging request. This conversion specifier can be optionally followed by <em>precision specifier</em>, that is a decimal constant in brackets. <p>If a precision specifier is given, then only the corresponding number of right most components of the class name will be printed. By default the class name is output in fullly qualified form. <p>For example, for the class name "org.apache.xyz.SomeClass", the pattern <b>%C{1}</b> will output "SomeClass". <p><b>WARNING</b> Generating the caller class information is slow. Thus, it's use should be avoided unless execution speed is not an issue. </td> </tr> <tr> <td align=center><b>d</b></td> <td>Used to output the date of the logging event. The date conversion specifier may be followed by a <em>date format specifier</em> enclosed between braces. For example, <b>%d{HH:mm:ss,SSS}</b> or <b>%d{dd&nbsp;MMM&nbsp;yyyy&nbsp;HH:mm:ss,SSS}</b>. If no date format specifier is given then ISO8601 format is assumed. <p>The date format specifier admits the same syntax as the time pattern string of the {@link java.text.SimpleDateFormat}. Altough part of the standard JDK, the performance of <code>SimpleDateFormat</code> is quite poor. <p>For better results it is recommended to use the log4j date formatters. These can be specified using one of the strings "ABSOLUTE", "DATE" and "ISO8601" for specifying {@link org.apache.log4j.helpers.AbsoluteTimeDateFormat AbsoluteTimeDateFormat}, {@link org.apache.log4j.helpers.DateTimeDateFormat DateTimeDateFormat} and respectively {@link org.apache.log4j.helpers.ISO8601DateFormat ISO8601DateFormat}. For example, <b>%d{ISO8601}</b> or <b>%d{ABSOLUTE}</b>. <p>These dedicated date formatters perform significantly better than {@link java.text.SimpleDateFormat}. </td> </tr> <tr> <td align=center><b>F</b></td> <td>Used to output the file name where the logging request was issued. <p><b>WARNING</b> Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue. </tr> <tr> <td align=center><b>l</b></td> <td>Used to output location information of the caller which generated the logging event. <p>The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses. <p>The location information can be very useful. However, it's generation is <em>extremely</em> slow. It's use should be avoided unless execution speed is not an issue. </td> </tr> <tr> <td align=center><b>L</b></td> <td>Used to output the line number from where the logging request was issued. <p><b>WARNING</b> Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue. </tr> <tr> <td align=center><b>m</b></td> <td>Used to output the application supplied message associated with the logging event.</td> </tr> <tr> <td align=center><b>M</b></td> <td>Used to output the method name where the logging request was issued. <p><b>WARNING</b> Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue. </tr> <tr> <td align=center><b>n</b></td> <td>Outputs the platform dependent line separator character or characters. <p>This conversion character offers practically the same performance as using non-portable line separator strings such as "\n", or "\r\n". Thus, it is the preferred way of specifying a line separator. </tr> <tr> <td align=center><b>p</b></td> <td>Used to output the priority of the logging event.</td> </tr> <tr> <td align=center><b>r</b></td> <td>Used to output the number of milliseconds elapsed since the start of the application until the creation of the logging event.</td> </tr> <tr> <td align=center><b>t</b></td> <td>Used to output the name of the thread that generated the logging event.</td> </tr> <tr> <td align=center><b>x</b></td> <td>Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event. </td> </tr> <tr> <td align=center><b>%</b></td> <td>The sequence %% outputs a single percent sign. </td> </tr> </table> <p>By default the relevant infromation is output as is. However, with the aid of format modifiers it is possible to change the minimum field width, the maximum field width and justification. <p>The optional format modifier is placed between the percent sign and the conversion character. <p>The first optional format modifier is the <em>left justification flag</em> which is just the minus (-) character. Then comes the optional <em>minimum field width</em> modifier. This is a decimal constant that represents the minimum number of characters to output. If the data item requires fewer characters, it is padded on either the left or the right until the minimum width is reached. The default is to pad on the left (right justify) but you can specify right padding with the left justification flag. The padding character is space. If the data item is larger than the minimum field width, the field is expanded to accomodate the data. The value is never truncated. <p>This behavior can be changed using the <em>maximum field width</em> modifier which is desginated by a period followed by a decimal constant. If the data item is longer than the maximum field, then the extra characters are removed from the <em>beginning</em> of the data item and not from the end. For example, it the maximum field width is eight and the data item is ten characters long, then the first two characters of the data item are dropped. This behaviour deviates from the printf function in C where truncation is done from the end. <p>Below are various format modifier examples for the category conversion specifier. <p> <TABLE BORDER=1 CELLPADDING=8> <th>Format modifier <th>left justify <th>minimim width <th>maximum width <th>comment <tr> <td align=center>%20c</td> <td align=center>false</td> <td align=center>20</td> <td align=center>none</td> <td>Left pad with spaces if the category name is less than 20 characters long. <tr> <td align=center>%-20c</td> <td align=center>true</td> <td align=center>20</td> <td align=center>none</td> <td>Right pad with spaces if the category name is less than 20 characters long. <tr> <td align=center>%.30c</td> <td align=center>NA</td> <td align=center>none</td> <td align=center>30</td> <td>Truncate from the beginning if the category name is longer than 30 characters. <tr> <td align=center>%20.30c</td> <td align=center>false</td> <td align=center>20</td> <td align=center>30</td> <td>Left pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. <tr> <td align=center>%-20.30c</td> <td align=center>true</td> <td align=center>20</td> <td align=center>30</td> <td>Right pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. </table> <p>Below are some examples of conversion patterns. <dl> <p><dt><b>%r [%t] %-5p %c %x - %m\n</b> <p><dd>This is essentially the TTCC layout. <p><dt><b>%-6r [%15.15t] %-5p %30.30c %x - %m\n</b> <p><dd>Similar to the TTCC layout except that the rlative time is right padded if less than 6 digits, thread name is right padded if less than 15 characters and truncated if longer and the category name is left padded if shorter than 30 characters and truncated if longer. </dl> <p>The above text is largely inspired from Peter A. Darnell and Philip E. Margolis' higly recommended book "C -- a Software Engineering Approach", ISBN 0-387-97389-3. @author <a href="mailto:cakalijp@Maritz.com">James P. Cakalic</a> @author Ceki G&uuml;lc&uuml; @since 0.8.2 */ public class PatternLayout extends Layout { /** A string constant used in naming the option for setting the layout pattern. Current value of this string constant is <b>ConversionPattern</b>. <p>Note that the search for all option keys is case sensitive. */ final static public String CONVERSION_PATTERN_OPTION = "ConversionPattern"; /** Default pattern string for log output. Currently set to the - string <b>"%m\n"</b> which just prints the application supplied + string <b>"%m%n"</b> which just prints the application supplied message. */ - public final static String DEFAULT_CONVERSION_PATTERN ="%m\n"; + public final static String DEFAULT_CONVERSION_PATTERN ="%m%n"; /* A string constant used in naming the option for setting the time zone for date output. Current value of this string constant is <b>TimeZone</b>. */ //final static public String TIMEZONE_OPTION = "TimeZone"; /** A conversion pattern equivalent to the TTCCCLayout. Current value is <b>%r [%t] %p %c %x - %m%n</b>. */ public final static String TTCC_CONVERSION_PATTERN = "%r [%t] %p %c %x - %m%n"; protected final int BUF_SIZE = 256; protected final int MAX_CAPACITY = 1024; // output buffer appended to when format() is invoked private StringBuffer sbuf = new StringBuffer(BUF_SIZE); private String pattern; private PatternConverter head; private String timezone; /** Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN. The default pattern just produces the application supplied message. */ public PatternLayout() { this(DEFAULT_CONVERSION_PATTERN); } /** Constructs a PatternLayout using the supplied conversion pattern. */ public PatternLayout(String pattern) { this.pattern = pattern; head = createPatternParser((pattern == null) ? DEFAULT_CONVERSION_PATTERN : pattern).parse(); } /** Does not do anything as options become effective immediately. See {@link #setOption} method. */ public void activateOptions() { // nothing to do. } /** Returns PatternParser used to parse the conversion string. Subclasses may override this to return a subclass of PatternParser which recognize custom conversion characters. @since 0.9.0 */ protected PatternParser createPatternParser(String pattern) { return new PatternParser(pattern); } /** Produces a formatted string as specified by the conversion pattern. */ public String format(LoggingEvent event) { // Reset working stringbuffer if(sbuf.capacity() > MAX_CAPACITY) { sbuf = new StringBuffer(BUF_SIZE); } else { sbuf.setLength(0); } PatternConverter c = head; while(c != null) { c.format(sbuf, event); c = c.next; } return sbuf.toString(); } /** Returns the the array of option strings that {@link PatternLayout} recognizes. The only recognized option string is the value of {@link #CONVERSION_PATTERN_OPTION}. */ public String[] getOptionStrings() { return new String[] {CONVERSION_PATTERN_OPTION}; } /** The PatternLayout does not handle the throwable contained within {@link LoggingEvent LoggingEvents}. Thus, it returns <code>true</code>. @since 0.8.4 */ public boolean ignoresThrowable() { return true; } /** Set the conversion pattern. */ public void setConversionPattern(String conversionPattern) { setOption(CONVERSION_PATTERN_OPTION, conversionPattern); } /** The PatternLayout specific options are: <p> <dl> <dt><b>ConversionPattern</b> <p><dd>The value determines the conversion pattern used. </dl> */ public void setOption(String option, String value) { if(value == null) return; if(option.equalsIgnoreCase(CONVERSION_PATTERN_OPTION)) { pattern = value; head = createPatternParser(value).parse(); } //else if(option.equals(TIMEZONE_OPTION)) { //try { //timezone = OptionConverter.substituteVars(value); //} //catch(IllegalArgumentException e) { //LogLog.error("Could not substitute variables." , e); //} //} } /** Returns the current value of the named option, or null if the option name is unkown. The PatternLayout recognizes only the "ConversionPattern" option. */ public String getOption(String option) { if (option.equalsIgnoreCase(CONVERSION_PATTERN_OPTION)) { return pattern; } else { return null; } } } diff --git a/src/java/org/apache/log4j/helpers/CyclicBuffer.java b/src/java/org/apache/log4j/helpers/CyclicBuffer.java index 2969c462..eb9c89a0 100644 --- a/src/java/org/apache/log4j/helpers/CyclicBuffer.java +++ b/src/java/org/apache/log4j/helpers/CyclicBuffer.java @@ -1,142 +1,150 @@ /* * Copyright (C) The Apache Software Foundation. All rights reserved. * * This software is published under the terms of the Apache Software License * version 1.1, a copy of which has been included with this distribution in * the LICENSE.APL file. */ package org.apache.log4j.helpers; import org.apache.log4j.spi.LoggingEvent; /** CyclicBuffer is used by other appenders to hold {@link LoggingEvent LoggingEvents} for immediate or differed display. <p>This buffer gives read access to any element in the buffer not just the first or last element. @author Ceki G&uuml;lc&uuml; @since 0.9.0 */ public class CyclicBuffer { LoggingEvent[] ea; int first; int last; int numElems; int maxSize; /** Instantiate a new CyclicBuffer of at most <code>maxSize</code> events. The <code>maxSize</code> argument must a positive integer. @param maxSize The maximum number of elements in the buffer. */ public CyclicBuffer(int maxSize) throws IllegalArgumentException { if(maxSize < 1) { throw new IllegalArgumentException("The maxSize argument ("+maxSize+ ") is not a positive integer."); } this.maxSize = maxSize; ea = new LoggingEvent[maxSize]; first = 0; last = 0; numElems = 0; } /** Add an <code>event</code> as the last event in the buffer. */ public void add(LoggingEvent event) { ea[last] = event; if(++last == maxSize) last = 0; if(numElems < maxSize) numElems++; else if(++first == maxSize) first = 0; } /** Get the <i>i</i>th oldest event currently in the buffer. If <em>i</em> is outside the range 0 to the number of elements currently in the buffer, then <code>null</code> is returned. */ public LoggingEvent get(int i) { if(i < 0 || i >= numElems) return null; return ea[(first + i) % maxSize]; } public int getMaxSize() { return maxSize; } + /** + Get the oldest (first) element in the buffer. The oldest element + is removed from the buffer. + */ public LoggingEvent get() { LoggingEvent r = null; if(numElems > 0) { numElems--; r = ea[first]; ea[first] = null; if(++first == maxSize) first = 0; } return r; } /** Get the number of elements in the buffer. This number is guaranteed to be in the range 0 to <code>maxSize</code> (inclusive). - */ public int length() { return numElems; } /** Resize the cyclic buffer to <code>newSize</code>. @throws IllegalArgumentException if <code>newSize</code> is negative. */ public void resize(int newSize) { if(newSize < 0) { throw new IllegalArgumentException("Negative array size ["+newSize+ "] not allowed."); } if(newSize == numElems) return; // nothing to do LoggingEvent[] temp = new LoggingEvent[newSize]; int loopLen = newSize < numElems ? newSize : numElems; for(int i = 0; i < loopLen; i++) { temp[i] = ea[first]; ea[first] = null; if(++first == numElems) first = 0; } ea = temp; first = 0; numElems = loopLen; maxSize = newSize; + if (loopLen == newSize) { + last = 0; + } else { + last = loopLen; + } } }
false
false
null
null
diff --git a/src/main/java/me/prettyprint/cassandra/examples/ExampleDao.java b/src/main/java/me/prettyprint/cassandra/examples/ExampleDao.java index 1642bf61..c1d6e14d 100644 --- a/src/main/java/me/prettyprint/cassandra/examples/ExampleDao.java +++ b/src/main/java/me/prettyprint/cassandra/examples/ExampleDao.java @@ -1,101 +1,101 @@ package me.prettyprint.cassandra.examples; import static me.prettyprint.cassandra.utils.StringUtils.bytes; import static me.prettyprint.cassandra.utils.StringUtils.string; import me.prettyprint.cassandra.dao.Command; import me.prettyprint.cassandra.model.HectorException; import me.prettyprint.cassandra.model.NotFoundException; import me.prettyprint.cassandra.service.Keyspace; import org.apache.cassandra.thrift.ColumnPath; /** * An example DAO (data access object) which uses the Command pattern. * <p/> - * This DAO is simple, it provides a get/insert/delte API for String values. + * This DAO is simple, it provides a get/insert/delete API for String values. * The underlying cassandra implementation stores the values under Keyspace1.key.Standard1.v * where key is the value's key, Standard1 is the name of the column family and "v" is just a column * name that's used to hold the value. * <p/> * what's interesting to notice here is that ease of operation that the command pattern provides. * The pattern assumes only one keyspace is required to perform the operation (get/insert/remove) * and injects it to the {@link Command#execute(Keyspace)} abstract method which is implemented * by all the dao methods. * The {@link Command#execute(String, int, String)} which is then invoked, takes care of creating * the {@link Keyspace} instance and releasing it after the operation completes. * * @author Ran Tavory (rantav@gmail.com) */ public class ExampleDao { private final static String CASSANDRA_KEYSPACE = "Keyspace1"; private final static int CASSANDRA_PORT = 9170; private final static String CASSANDRA_HOST = "localhost"; private final static String CF_NAME = "Standard1"; /** Column name where values are stored */ private final static String COLUMN_NAME = "v"; public static void main(String[] args) throws HectorException { ExampleDao ed = new ExampleDao(); ed.insert("key1", "value1"); System.out.println(ed.get("key1")); } /** * Insert a new value keyed by key * * @param key Key for the value * @param value the String value to insert */ public void insert(final String key, final String value) throws HectorException { execute(new Command<Void>() { @Override public Void execute(final Keyspace ks) throws HectorException { ks.insert(key, createColumnPath(COLUMN_NAME), bytes(value)); return null; } }); } /** * Get a string value. * * @return The string value; null if no value exists for the given key. */ public String get(final String key) throws HectorException { return execute(new Command<String>() { @Override public String execute(final Keyspace ks) throws HectorException { try { return string(ks.getColumn(key, createColumnPath(COLUMN_NAME)).getValue()); } catch (NotFoundException e) { return null; } } }); } /** * Delete a key from cassandra */ public void delete(final String key) throws HectorException { execute(new Command<Void>() { @Override public Void execute(final Keyspace ks) throws HectorException { ks.remove(key, createColumnPath(COLUMN_NAME)); return null; } }); } protected static <T> T execute(Command<T> command) throws HectorException { return command.execute(CASSANDRA_HOST, CASSANDRA_PORT, CASSANDRA_KEYSPACE); } protected ColumnPath createColumnPath(String columnName) { ColumnPath columnPath = new ColumnPath(CF_NAME); columnPath.setColumn(columnName.getBytes()); return columnPath; } }
true
false
null
null
diff --git a/src/org/htmlcleaner/DefaultTagProvider.java b/src/org/htmlcleaner/DefaultTagProvider.java index 81180a5..3d25d12 100644 --- a/src/org/htmlcleaner/DefaultTagProvider.java +++ b/src/org/htmlcleaner/DefaultTagProvider.java @@ -1,470 +1,470 @@ /* Copyright (c) 2006-2007, Vladimir Nikic All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name of HtmlCleaner may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You can contact Vladimir Nikic by sending e-mail to nikic_vladimir@yahoo.com. Please include the word "HtmlCleaner" in the subject line. */ package org.htmlcleaner; import java.util.HashMap; /** * This class is automatically created from ConfigFileTagProvider which reads * default XML configuration file with tag descriptions. * It is used as default tag info provider. * Class is created for performance purposes - parsing XML file requires some * processing time. * * Created by: Vladimir Nikic<br/> * Date: April, 2008. */ public class DefaultTagProvider extends HashMap implements ITagInfoProvider { // singleton instance, used if no other TagInfoProvider is specified private static DefaultTagProvider _instance; /** * Returns singleton instance of this class. */ public static synchronized DefaultTagProvider getInstance() { if (_instance == null) { _instance = new DefaultTagProvider(); } return _instance; } public DefaultTagProvider() { TagInfo tagInfo; tagInfo = new TagInfo("div", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("div", tagInfo); tagInfo = new TagInfo("span", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("span", tagInfo); tagInfo = new TagInfo("meta", TagInfo.CONTENT_NONE, TagInfo.HEAD, false, false, false); this.put("meta", tagInfo); tagInfo = new TagInfo("link", TagInfo.CONTENT_NONE, TagInfo.HEAD, false, false, false); this.put("link", tagInfo); tagInfo = new TagInfo("title", TagInfo.CONTENT_TEXT, TagInfo.HEAD, false, true, false); this.put("title", tagInfo); tagInfo = new TagInfo("style", TagInfo.CONTENT_TEXT, TagInfo.HEAD, false, false, false); this.put("style", tagInfo); tagInfo = new TagInfo("bgsound", TagInfo.CONTENT_NONE, TagInfo.HEAD, false, false, false); this.put("bgsound", tagInfo); tagInfo = new TagInfo("h1", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("h1,h2,h3,h4,h5,h6,p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("h1", tagInfo); tagInfo = new TagInfo("h2", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("h1,h2,h3,h4,h5,h6,p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("h2", tagInfo); tagInfo = new TagInfo("h3", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("h1,h2,h3,h4,h5,h6,p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("h3", tagInfo); tagInfo = new TagInfo("h4", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("h1,h2,h3,h4,h5,h6,p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("h4", tagInfo); tagInfo = new TagInfo("h5", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("h1,h2,h3,h4,h5,h6,p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("h5", tagInfo); tagInfo = new TagInfo("h6", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("h1,h2,h3,h4,h5,h6,p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("h6", tagInfo); tagInfo = new TagInfo("p", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("p", tagInfo); tagInfo = new TagInfo("strong", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("strong", tagInfo); tagInfo = new TagInfo("em", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("em", tagInfo); tagInfo = new TagInfo("abbr", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("abbr", tagInfo); tagInfo = new TagInfo("acronym", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("acronym", tagInfo); tagInfo = new TagInfo("address", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("address", tagInfo); tagInfo = new TagInfo("bdo", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("bdo", tagInfo); tagInfo = new TagInfo("blockquote", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("blockquote", tagInfo); tagInfo = new TagInfo("cite", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("cite", tagInfo); tagInfo = new TagInfo("q", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("q", tagInfo); tagInfo = new TagInfo("code", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("code", tagInfo); tagInfo = new TagInfo("ins", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("ins", tagInfo); tagInfo = new TagInfo("del", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("del", tagInfo); tagInfo = new TagInfo("dfn", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("dfn", tagInfo); tagInfo = new TagInfo("kbd", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("kbd", tagInfo); tagInfo = new TagInfo("pre", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("pre", tagInfo); tagInfo = new TagInfo("samp", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("samp", tagInfo); tagInfo = new TagInfo("listing", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("listing", tagInfo); tagInfo = new TagInfo("var", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("var", tagInfo); tagInfo = new TagInfo("br", TagInfo.CONTENT_NONE, TagInfo.BODY, false, false, false); this.put("br", tagInfo); tagInfo = new TagInfo("wbr", TagInfo.CONTENT_NONE, TagInfo.BODY, false, false, false); this.put("wbr", tagInfo); tagInfo = new TagInfo("nobr", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeTags("nobr"); this.put("nobr", tagInfo); tagInfo = new TagInfo("xmp", TagInfo.CONTENT_TEXT, TagInfo.BODY, false, false, false); this.put("xmp", tagInfo); tagInfo = new TagInfo("a", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeTags("a"); this.put("a", tagInfo); tagInfo = new TagInfo("base", TagInfo.CONTENT_NONE, TagInfo.HEAD, false, false, false); this.put("base", tagInfo); tagInfo = new TagInfo("img", TagInfo.CONTENT_NONE, TagInfo.BODY, false, false, false); this.put("img", tagInfo); tagInfo = new TagInfo("area", TagInfo.CONTENT_NONE, TagInfo.BODY, false, false, false); tagInfo.defineFatalTags("map"); tagInfo.defineCloseBeforeTags("area"); this.put("area", tagInfo); tagInfo = new TagInfo("map", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeTags("map"); this.put("map", tagInfo); tagInfo = new TagInfo("object", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("object", tagInfo); tagInfo = new TagInfo("param", TagInfo.CONTENT_NONE, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("param", tagInfo); tagInfo = new TagInfo("applet", TagInfo.CONTENT_ALL, TagInfo.BODY, true, false, false); this.put("applet", tagInfo); tagInfo = new TagInfo("xml", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("xml", tagInfo); tagInfo = new TagInfo("ul", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("ul", tagInfo); tagInfo = new TagInfo("ol", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("ol", tagInfo); tagInfo = new TagInfo("li", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("li,p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("li", tagInfo); tagInfo = new TagInfo("dl", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("dl", tagInfo); tagInfo = new TagInfo("dt", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeTags("dt,dd"); this.put("dt", tagInfo); tagInfo = new TagInfo("dd", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeTags("dt,dd"); this.put("dd", tagInfo); tagInfo = new TagInfo("menu", TagInfo.CONTENT_ALL, TagInfo.BODY, true, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("menu", tagInfo); tagInfo = new TagInfo("dir", TagInfo.CONTENT_ALL, TagInfo.BODY, true, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("dir", tagInfo); tagInfo = new TagInfo("table", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); - tagInfo.defineAllowedChildrenTags("tr,tbody,thead,tfoot,colgroup,caption,tr"); + tagInfo.defineAllowedChildrenTags("tr,tbody,thead,tfoot,colgroup,col,caption,tr"); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("tr,thead,tbody,tfoot,caption,colgroup,table,p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("table", tagInfo); tagInfo = new TagInfo("tr", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineFatalTags("table"); tagInfo.defineRequiredEnclosingTags("tbody"); tagInfo.defineAllowedChildrenTags("td,th"); tagInfo.defineHigherLevelTags("thead,tfoot"); tagInfo.defineCloseBeforeTags("tr,td,th,caption,colgroup"); this.put("tr", tagInfo); tagInfo = new TagInfo("td", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineFatalTags("table"); tagInfo.defineRequiredEnclosingTags("tr"); tagInfo.defineCloseBeforeTags("td,th,caption,colgroup"); this.put("td", tagInfo); tagInfo = new TagInfo("th", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineFatalTags("table"); tagInfo.defineRequiredEnclosingTags("tr"); tagInfo.defineCloseBeforeTags("td,th,caption,colgroup"); this.put("th", tagInfo); tagInfo = new TagInfo("tbody", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineFatalTags("table"); tagInfo.defineAllowedChildrenTags("tr,form"); tagInfo.defineCloseBeforeTags("td,th,tr,tbody,thead,tfoot,caption,colgroup"); this.put("tbody", tagInfo); tagInfo = new TagInfo("thead", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineFatalTags("table"); tagInfo.defineAllowedChildrenTags("tr,form"); tagInfo.defineCloseBeforeTags("td,th,tr,tbody,thead,tfoot,caption,colgroup"); this.put("thead", tagInfo); tagInfo = new TagInfo("tfoot", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineFatalTags("table"); tagInfo.defineAllowedChildrenTags("tr,form"); tagInfo.defineCloseBeforeTags("td,th,tr,tbody,thead,tfoot,caption,colgroup"); this.put("tfoot", tagInfo); tagInfo = new TagInfo("col", TagInfo.CONTENT_NONE, TagInfo.BODY, false, false, false); - tagInfo.defineFatalTags("colgroup"); + tagInfo.defineFatalTags("table"); this.put("col", tagInfo); tagInfo = new TagInfo("colgroup", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineFatalTags("table"); tagInfo.defineAllowedChildrenTags("col"); tagInfo.defineCloseBeforeTags("td,th,tr,tbody,thead,tfoot,caption,colgroup"); this.put("colgroup", tagInfo); tagInfo = new TagInfo("caption", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineFatalTags("table"); tagInfo.defineCloseBeforeTags("td,th,tr,tbody,thead,tfoot,caption,colgroup"); this.put("caption", tagInfo); tagInfo = new TagInfo("form", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, true); tagInfo.defineForbiddenTags("form"); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("option,optgroup,textarea,select,fieldset,p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("form", tagInfo); tagInfo = new TagInfo("input", TagInfo.CONTENT_NONE, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeTags("select,optgroup,option"); this.put("input", tagInfo); tagInfo = new TagInfo("textarea", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeTags("select,optgroup,option"); this.put("textarea", tagInfo); tagInfo = new TagInfo("select", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, true); tagInfo.defineAllowedChildrenTags("option,optgroup"); tagInfo.defineCloseBeforeTags("option,optgroup,select"); this.put("select", tagInfo); tagInfo = new TagInfo("option", TagInfo.CONTENT_TEXT, TagInfo.BODY, false, false, true); tagInfo.defineFatalTags("select"); tagInfo.defineCloseBeforeTags("option"); this.put("option", tagInfo); tagInfo = new TagInfo("optgroup", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, true); tagInfo.defineFatalTags("select"); tagInfo.defineAllowedChildrenTags("option"); tagInfo.defineCloseBeforeTags("optgroup"); this.put("optgroup", tagInfo); tagInfo = new TagInfo("button", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeTags("select,optgroup,option"); this.put("button", tagInfo); tagInfo = new TagInfo("label", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("label", tagInfo); tagInfo = new TagInfo("fieldset", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("fieldset", tagInfo); tagInfo = new TagInfo("isindex", TagInfo.CONTENT_NONE, TagInfo.BODY, true, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("isindex", tagInfo); tagInfo = new TagInfo("script", TagInfo.CONTENT_ALL, TagInfo.HEAD_AND_BODY, false, false, false); this.put("script", tagInfo); tagInfo = new TagInfo("noscript", TagInfo.CONTENT_ALL, TagInfo.HEAD_AND_BODY, false, false, false); this.put("noscript", tagInfo); tagInfo = new TagInfo("b", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseInsideCopyAfterTags("u,i,tt,sub,sup,big,small,strike,blink,s"); this.put("b", tagInfo); tagInfo = new TagInfo("i", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseInsideCopyAfterTags("b,u,tt,sub,sup,big,small,strike,blink,s"); this.put("i", tagInfo); tagInfo = new TagInfo("u", TagInfo.CONTENT_ALL, TagInfo.BODY, true, false, false); tagInfo.defineCloseInsideCopyAfterTags("b,i,tt,sub,sup,big,small,strike,blink,s"); this.put("u", tagInfo); tagInfo = new TagInfo("tt", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseInsideCopyAfterTags("b,u,i,sub,sup,big,small,strike,blink,s"); this.put("tt", tagInfo); tagInfo = new TagInfo("sub", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseInsideCopyAfterTags("b,u,i,tt,sup,big,small,strike,blink,s"); this.put("sub", tagInfo); tagInfo = new TagInfo("sup", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseInsideCopyAfterTags("b,u,i,tt,sub,big,small,strike,blink,s"); this.put("sup", tagInfo); tagInfo = new TagInfo("big", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseInsideCopyAfterTags("b,u,i,tt,sub,sup,small,strike,blink,s"); this.put("big", tagInfo); tagInfo = new TagInfo("small", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseInsideCopyAfterTags("b,u,i,tt,sub,sup,big,strike,blink,s"); this.put("small", tagInfo); tagInfo = new TagInfo("strike", TagInfo.CONTENT_ALL, TagInfo.BODY, true, false, false); tagInfo.defineCloseInsideCopyAfterTags("b,u,i,tt,sub,sup,big,small,blink,s"); this.put("strike", tagInfo); tagInfo = new TagInfo("blink", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseInsideCopyAfterTags("b,u,i,tt,sub,sup,big,small,strike,s"); this.put("blink", tagInfo); tagInfo = new TagInfo("marquee", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("marquee", tagInfo); tagInfo = new TagInfo("s", TagInfo.CONTENT_ALL, TagInfo.BODY, true, false, false); tagInfo.defineCloseInsideCopyAfterTags("b,u,i,tt,sub,sup,big,small,strike,blink"); this.put("s", tagInfo); tagInfo = new TagInfo("hr", TagInfo.CONTENT_NONE, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("hr", tagInfo); tagInfo = new TagInfo("font", TagInfo.CONTENT_ALL, TagInfo.BODY, true, false, false); this.put("font", tagInfo); tagInfo = new TagInfo("basefont", TagInfo.CONTENT_NONE, TagInfo.BODY, true, false, false); this.put("basefont", tagInfo); tagInfo = new TagInfo("center", TagInfo.CONTENT_ALL, TagInfo.BODY, true, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("center", tagInfo); tagInfo = new TagInfo("comment", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("comment", tagInfo); tagInfo = new TagInfo("server", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("server", tagInfo); tagInfo = new TagInfo("iframe", TagInfo.CONTENT_ALL, TagInfo.BODY, false, false, false); this.put("iframe", tagInfo); tagInfo = new TagInfo("embed", TagInfo.CONTENT_NONE, TagInfo.BODY, false, false, false); tagInfo.defineCloseBeforeCopyInsideTags("a,bdo,strong,em,q,b,i,u,tt,sub,sup,big,small,strike,s,font"); tagInfo.defineCloseBeforeTags("p,address,label,abbr,acronym,dfn,kbd,samp,var,cite,code,param,xml"); this.put("embed", tagInfo); } public TagInfo getTagInfo(String tagName) { return (TagInfo) get(tagName); } } \ No newline at end of file
false
false
null
null
diff --git a/src/main/java/org/apacheextras/camel/examples/rcode/CalendarAgregationStrategy.java b/src/main/java/org/apacheextras/camel/examples/rcode/CalendarAgregationStrategy.java index 12814b2..694a259 100644 --- a/src/main/java/org/apacheextras/camel/examples/rcode/CalendarAgregationStrategy.java +++ b/src/main/java/org/apacheextras/camel/examples/rcode/CalendarAgregationStrategy.java @@ -1,49 +1,48 @@ /* * Copyright 2013 Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apacheextras.camel.examples.rcode; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import org.apache.camel.Exchange; import org.apache.camel.processor.aggregate.AggregationStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author cemmersb */ public class CalendarAgregationStrategy implements AggregationStrategy { private static final Logger LOGGER = LoggerFactory.getLogger(CalendarAgregationStrategy.class); @Override public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { List<LinkedHashMap> holidays = new LinkedList<LinkedHashMap>(); - try { + + if(null != oldExchange) { holidays = oldExchange.getIn().getBody(List.class); - } catch(NullPointerException ex) { - LOGGER.info("Holidays do not exist, using new instance!"); } - + holidays.add(newExchange.getIn().getBody(LinkedHashMap.class)); - oldExchange.getIn().setBody(holidays); - return oldExchange; + newExchange.getIn().setBody(holidays); + return newExchange; } } diff --git a/src/main/java/org/apacheextras/camel/examples/rcode/RCodeRouteBuilder.java b/src/main/java/org/apacheextras/camel/examples/rcode/RCodeRouteBuilder.java index fc757cf..5a1ade4 100644 --- a/src/main/java/org/apacheextras/camel/examples/rcode/RCodeRouteBuilder.java +++ b/src/main/java/org/apacheextras/camel/examples/rcode/RCodeRouteBuilder.java @@ -1,130 +1,130 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.apacheextras.camel.examples.rcode; import org.apache.camel.Exchange; import org.apache.camel.LoggingLevel; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.dataformat.csv.CsvDataFormat; import java.io.File; import org.apache.camel.Processor; import org.apache.camel.model.dataformat.JsonLibrary; import org.apache.commons.lang3.StringUtils; /** * @author cemmersb, Sebastian Rühl */ public class RCodeRouteBuilder extends RouteBuilder { private final static String DEVICE_COMMAND = "jpeg('${exchangeId}.jpg',quality=90);"; private final static String PLOT_COMMAND = "plot(quantity, type=\"l\");"; private final static String RETRIEVE_PLOT_COMMAND = "r=readBin('${exchangeId}.jpg','raw',1024*1024); unlink('${exchangeId}.jpg'); r"; private final static String FINAL_COMMAND = DEVICE_COMMAND + PLOT_COMMAND + "dev.off();" + RETRIEVE_PLOT_COMMAND; private final static String HTTP4_RS_CAL_ENDPOINT = "http4://kayaposoft.com/enrico/json/v1.0/"; private File basePath; public RCodeRouteBuilder(File basePath) { this.basePath = basePath; } @Override public void configure() throws Exception { configureCsvRoute(); - configureRsCalRoute(); + configureRestCalendarRoute(); configureRCodeRoute(); configureGraphRoute(); wireRoutes(); } /** * Takes an input as bytes and writes it as an jpeg file. */ private void configureGraphRoute() { from("direct:graph") .setHeader(Exchange.FILE_NAME, simple("graph${exchangeId}.jpeg")) .to("file://" + basePath.getParent() + "/output") .log("Generated graph file: " + basePath.getParent() + "/graph${exchangeId}.jpeg"); } /** * Takes an incoming string argument containing monthly quantities and * generates an output graph. */ private void configureRCodeRoute() { from("direct:rcode") //.setBody(simple("calendar <- c(${});\n")) .setBody(simple("quantity <- c(${body});\n" + FINAL_COMMAND)) .to("log://command?level=DEBUG") .to("rcode://localhost:6311/parse_and_eval?bufferSize=4194304") .to("log://r_output?level=INFO") .setBody(simple("${body.asBytes}")); } /** * Configures a CSV route that reads the quantity values from the route and * sends the result to the RCode route. */ private void configureCsvRoute() { // Configure CSV data format with ';' as separator and skipping of the header final CsvDataFormat csv = new CsvDataFormat(); csv.setDelimiter(";"); csv.setSkipFirstLine(true); // Route takes a CSV file, splits the body and reads the actual values from(basePath.toURI() + "?noop=TRUE") .log("Unmarshalling CSV file.") .unmarshal(csv) .to("log://CSV?level=DEBUG") .setHeader("id", simple("${exchangeId}")) .split().body() .to("log://CSV?level=DEBUG") // TODO: Create monthly based output instead of taking the yearly figures .setBody(simple("${body[1]}")) .to("log://CSV?level=DEBUG") // Now we aggregate the retrived contents in a big string .aggregate(header("id"), new ConcatenateAggregationStrategy()).completionTimeout(3000) .log(LoggingLevel.INFO, "Finished the unmarshaling") .to("direct:CSV_sink"); } - private void configureRsCalRoute() { + private void configureRestCalendarRoute() { from("direct:RS_CAL") // Configure Query Parameters .setHeader(Exchange.HTTP_QUERY, constant("action=getPublicHolidaysForYear&year=2012&country=ger&region=Bavaria")) .to(HTTP4_RS_CAL_ENDPOINT) .convertBodyTo(String.class) .to("log://calendar?level=INFO") .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); String[] bodies = StringUtils.substringsBetween(body, "{\"date\":{\"", "\"},"); for (int i = 0; i < bodies.length; i++) { StringBuilder sb = new StringBuilder(); bodies[i] = sb.append("{\"date\":{\"").append(bodies[i]).append("\"}").toString(); } exchange.getIn().setBody(bodies); } }) .split(body()) .unmarshal().json(JsonLibrary.Gson) - //.aggregate(new CalendarAgregationStrategy()).body().completionTimeout(3000) + .aggregate(new CalendarAgregationStrategy()).body().completionTimeout(3000) .to("log://calendar?level=INFO"); } /** * Wires together the routes. */ private void wireRoutes() { from("direct:CSV_sink") .enrich("direct:RS_CAL", new EnrichServiceResponseAggregationStrategy()) .to("direct:rcode") .to("direct:graph"); } }
false
false
null
null
diff --git a/src/main/ed/appserver/jxp/JxpServlet.java b/src/main/ed/appserver/jxp/JxpServlet.java index 126e60267..2c71ff32c 100644 --- a/src/main/ed/appserver/jxp/JxpServlet.java +++ b/src/main/ed/appserver/jxp/JxpServlet.java @@ -1,380 +1,383 @@ // JxpServlet.java package ed.appserver.jxp; import java.io.*; import java.util.regex.*; import ed.js.*; import ed.util.*; import ed.js.engine.*; import ed.js.func.*; import ed.lang.*; import ed.appserver.*; import ed.net.httpserver.*; public class JxpServlet { public static final int MAX_WRITTEN_LENGTH = 1024 * 1024 * 15; JxpServlet( AppContext context , JxpSource source , JSFunction func ){ _context = context; _source = source; _theFunction = func; } public void handle( HttpRequest request , HttpResponse response , AppRequest ar ){ final Scope scope = ar.getScope(); if ( scope.get( "request" ) == null ) scope.put( "request" , request , true ); if ( scope.get( "response" ) == null ) scope.put( "response" , response , true ); Object cdnFromScope = scope.get( "CDN" ); final String cdnPrefix = cdnFromScope != null ? cdnFromScope.toString() : getStaticPrefix( request , ar ); scope.put( "CDN" , cdnPrefix , true ); MyWriter writer = new MyWriter( response.getWriter() , cdnPrefix , ar.getContext() , ar); scope.put( "print" , writer , true ); try { _theFunction.call( scope ); if ( writer._writer.hasSpot() ){ writer._writer.backToSpot(); if ( ar.getContext() != null ) for ( Object foo : ar.getContext().getGlobalHead() ) { writer.print( foo.toString() ); writer.print( "\n" ); } if ( ar != null ) for ( Object foo : ar.getHeadToPrint() ) { writer.print( foo.toString() ); writer.print( "\n" ); } writer._writer.backToEnd(); } else { if ( ( ar.getContext() != null && ar.getContext().getGlobalHead().size() > 0 ) || ( ar != null && ar.getHeadToPrint().size() > 0 ) ){ // this is interesting // maybe i should do it only for html files // so i have to know that //throw new RuntimeException( "have head to print but no </head>" ); } } } catch ( RuntimeException re ){ if ( re instanceof JSException ){ if ( re.getCause() != null && re.getCause() instanceof RuntimeException ) re = (RuntimeException)re.getCause(); } StackTraceHolder.getInstance().fix( re ); throw re; } } String getStaticPrefix( HttpRequest request , AppRequest ar ){ String host = request.getHost(); if ( host == null ) return ""; if ( host.indexOf( "." ) < 0 ) return ""; - + if ( request.getPort() > 0 ) return ""; + if ( request.getHeader( "X-SSL" ) != null ) + return ""; + String prefix= "http://static"; if ( host.indexOf( "local." ) >= 0 ) prefix += "-local"; prefix += ".10gen.com/" + host; return prefix; } public static class MyWriter extends JSFunctionCalls1 { public MyWriter( JxpWriter writer , String cdnPrefix , AppContext context , AppRequest ar ){ _writer = writer; _cdnPrefix = cdnPrefix; _context = context; _request = ar; if ( _writer == null ) throw new NullPointerException( "writer can't be null" ); set( "setFormObject" , new JSFunctionCalls1(){ public Object call( Scope scope , Object o , Object extra[] ){ if ( o == null ){ _formInput = null; return null; } if ( ! ( o instanceof JSObject ) ) throw new RuntimeException( "must be a JSObject" ); _formInput = (JSObject)o; _formInputPrefix = null; if ( extra != null && extra.length > 0 ) _formInputPrefix = extra[0].toString(); return o; } } ); } public Object get( Object n ){ if ( "cdnPrefix".equals( n ) ) return _cdnPrefix; return super.get( n ); } public Object set( Object n , Object v ){ if ( "cdnPrefix".equals( n ) ){ _cdnPrefix = v.toString(); return _cdnPrefix; } return super.set( n , v ); } public Object call( Scope scope , Object o , Object extra[] ){ if ( o == null ) print( "null" ); else print( JSInternalFunctions.JS_toString( o ) ); return null; } public void print( String s ){ if ( ( _writtenLength += s.length() ) > MAX_WRITTEN_LENGTH ) throw new RuntimeException( "trying to write a dynamic page more than " + MAX_WRITTEN_LENGTH + " chars long" ); if ( _writer.closed() ) throw new RuntimeException( "output closed. are you using an old print function" ); while ( s.length() > 0 ){ if ( _extra.length() > 0 ){ _extra.append( s ); s = _extra.toString(); _extra.setLength( 0 ); } _matcher.reset( s ); if ( ! _matcher.find() ){ _writer.print( s ); return; } _writer.print( s.substring( 0 , _matcher.start() ) ); s = s.substring( _matcher.start() ); int end = endOfTag( s ); if ( end == -1 ){ _extra.append( s ); return; } String wholeTag = s.substring( 0 , end + 1 ); if ( ! printTag( _matcher.group(1) , wholeTag ) ) _writer.print( wholeTag ); s = s.substring( end + 1 ); } } /** * @return true if i printed tag so you should not */ boolean printTag( String tag , String s ){ if ( tag == null ) throw new NullPointerException( "tag can't be null" ); if ( s == null ) throw new NullPointerException( "show tag can't be null" ); if ( tag.equalsIgnoreCase( "/head" ) && ! _writer.hasSpot() ){ _writer.saveSpot(); return false; } { // CDN stuff String srcName = null; if ( tag.equalsIgnoreCase( "img" ) || tag.equalsIgnoreCase( "script" ) ) srcName = "src"; else if ( tag.equalsIgnoreCase( "link" ) ) srcName = "href"; if ( srcName != null ){ s = s.substring( 2 + tag.length() ); // TODO: cache pattern or something Matcher m = Pattern.compile( srcName + " *= *['\"](.+?)['\"]" , Pattern.CASE_INSENSITIVE ).matcher( s ); if ( ! m.find() ) return false; _writer.print( "<" ); _writer.print( tag ); _writer.print( " " ); _writer.print( s.substring( 0 , m.start(1) ) ); String src = m.group(1); printSRC( src ); _writer.print( s.substring( m.end(1) ) ); return true; } } if ( _formInput != null && tag.equalsIgnoreCase( "input" ) ){ Matcher m = Pattern.compile( "\\bname *= *['\"](.+?)[\"']" ).matcher( s ); if ( ! m.find() ) return false; String name = m.group(1); if ( name.length() == 0 ) return false; if ( _formInputPrefix != null ) name = name.substring( _formInputPrefix.length() ); Object val = _formInput.get( name ); if ( val == null ) return false; if ( s.toString().matches( "value *=" ) ) return false; _writer.print( s.substring( 0 , s.length() - 1 ) ); _writer.print( " value=\"" ); _writer.print( HtmlEscape.escape( val.toString() ) ); _writer.print( "\" >" ); return true; } return false; } /** * takes the actual src of the asset and fixes and prints * i.e. /foo -> static.com/foo */ void printSRC( String src ){ if ( src == null || src.length() == 0 ) return; // parse out options boolean nocdn = false; boolean forcecdn = false; if ( src.startsWith( "NOCDN/" ) ){ nocdn = true; src = src.substring( 5 ); } else if ( src.startsWith( "CDN/" ) ){ forcecdn = true; src = src.substring( 3 ); } // weird special case if ( ! src.startsWith( "/" ) ){ // i'm not smart enough to handle local file case yet _writer.print( src ); return; } // setup String uri = src; int questionIndex = src.indexOf( "?" ); if ( questionIndex >= 0 ) uri = uri.substring( 0 , questionIndex ); String cdnTags = null; if ( uri.equals( "/~f" ) || uri.equals( "/~~/f" ) ){ cdnTags = ""; // TODO: should i put a version or timestamp here? } else { if ( _context != null ){ File f = _context.getFileSafe( uri ); if ( f != null && f.exists() ){ cdnTags = "lm=" + f.lastModified(); } } } // print if ( forcecdn || ( ! nocdn && cdnTags != null ) ) _writer.print( _cdnPrefix ); _writer.print( src ); if ( cdnTags != null && cdnTags.length() > 0 ){ if ( questionIndex < 0 ) _writer.print( "?" ); else _writer.print( "&" ); _writer.print( cdnTags ); } } int endOfTag( String s ){ for ( int i=0; i<s.length(); i++ ){ char c = s.charAt( i ); if ( c == '>' ) return i; if ( c == '"' || c == '\'' ){ for ( ; i<s.length(); i++) if ( c == s.charAt( i ) ) break; } } return -1; } static final Pattern _tagPattern = Pattern.compile( "<(/?\\w+)[ >]" , Pattern.CASE_INSENSITIVE ); final Matcher _matcher = _tagPattern.matcher(""); final StringBuilder _extra = new StringBuilder(); final JxpWriter _writer; final AppContext _context; final AppRequest _request; String _cdnPrefix; JSObject _formInput = null; String _formInputPrefix = null; int _writtenLength = 0; } final AppContext _context; final JxpSource _source; final JSFunction _theFunction; }
false
false
null
null
diff --git a/src/edu/calpoly/csc/pulseman/StartMenu.java b/src/edu/calpoly/csc/pulseman/StartMenu.java index 38fbeb6..d2259ee 100644 --- a/src/edu/calpoly/csc/pulseman/StartMenu.java +++ b/src/edu/calpoly/csc/pulseman/StartMenu.java @@ -1,102 +1,102 @@ package edu.calpoly.csc.pulseman; import java.util.Timer; import java.util.TimerTask; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; public class StartMenu implements GameInterface { private Image menuButton; private Image menuBackground; private Image connectButton, connectingButton, connectedButton; private volatile int countdown = 0; private final float[] buttonLoc = { 200, 400 }, connectLoc = { 850, 30 }; @Override public void render(GameContainer gc, Graphics g) { g.drawImage(menuBackground, 0, 0); g.drawImage(menuButton, buttonLoc[0], buttonLoc[1]); if(Main.getAndroidState() == Main.AndroidStates.NOT_CONNECTED) { g.drawImage(connectButton, connectLoc[0], connectLoc[1]); } else if(Main.getAndroidState() == Main.AndroidStates.CONNECTING) { g.drawImage(connectingButton, connectLoc[0], connectLoc[1]); g.drawString(String.valueOf(countdown), connectLoc[0] + connectingButton.getWidth(), connectLoc[1] + connectingButton.getHeight() / 2); } else { g.drawImage(connectedButton, connectLoc[0], connectLoc[1]); } g.drawString("You are a meditating monk. Head towards the light.\n" + "Use the beat to control nature's speed.", Main.getScreenWidth() / 2, Main.getScreenHeight() / 2); } @Override public void init(GameContainer gc) throws SlickException { menuButton = new Image("res/subtitle.png"); connectButton = new Image("res/connect.png"); connectingButton = new Image("res/connecting.png"); connectedButton = new Image("res/connected.png"); menuBackground = new Image("res/mainscreen.png"); } @Override public void update(GameContainer gc, int dt) { Input input = gc.getInput(); if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) { int x = input.getMouseX(); int y = input.getMouseY(); if(x >= buttonLoc[0] && x <= buttonLoc[0] + menuButton.getWidth() && y >= buttonLoc[1] && y <= buttonLoc[1] + menuButton.getHeight()) { Main.setState(Main.GameState.GAME); } - if(Main.getAndroidState() == Main.AndroidStates.NOT_CONNECTED || (x >= connectLoc[0] && x <= connectLoc[0] + connectButton.getWidth() && y >= connectLoc[1] && y <= connectLoc[1] + connectButton.getHeight())) + if(Main.getAndroidState() == Main.AndroidStates.NOT_CONNECTED && (x >= connectLoc[0] && x <= connectLoc[0] + connectButton.getWidth() && y >= connectLoc[1] && y <= connectLoc[1] + connectButton.getHeight())) { listenForConnection(); countdown = MessageHandler.SOCKET_TIMEOUT / 1000 + 1; new Timer("Countdown Timer").schedule(new TimerTask() { @Override public void run() { if(--countdown < 0) { cancel(); } } }, 0, 1000); } } } public static void listenForConnection() { new Thread(new Runnable() { @Override public void run() { Main.setAndroidConnecting(); MessageHandler.listenForConnection(); } }).start(); } }
true
true
public void update(GameContainer gc, int dt) { Input input = gc.getInput(); if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) { int x = input.getMouseX(); int y = input.getMouseY(); if(x >= buttonLoc[0] && x <= buttonLoc[0] + menuButton.getWidth() && y >= buttonLoc[1] && y <= buttonLoc[1] + menuButton.getHeight()) { Main.setState(Main.GameState.GAME); } if(Main.getAndroidState() == Main.AndroidStates.NOT_CONNECTED || (x >= connectLoc[0] && x <= connectLoc[0] + connectButton.getWidth() && y >= connectLoc[1] && y <= connectLoc[1] + connectButton.getHeight())) { listenForConnection(); countdown = MessageHandler.SOCKET_TIMEOUT / 1000 + 1; new Timer("Countdown Timer").schedule(new TimerTask() { @Override public void run() { if(--countdown < 0) { cancel(); } } }, 0, 1000); } } }
public void update(GameContainer gc, int dt) { Input input = gc.getInput(); if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) { int x = input.getMouseX(); int y = input.getMouseY(); if(x >= buttonLoc[0] && x <= buttonLoc[0] + menuButton.getWidth() && y >= buttonLoc[1] && y <= buttonLoc[1] + menuButton.getHeight()) { Main.setState(Main.GameState.GAME); } if(Main.getAndroidState() == Main.AndroidStates.NOT_CONNECTED && (x >= connectLoc[0] && x <= connectLoc[0] + connectButton.getWidth() && y >= connectLoc[1] && y <= connectLoc[1] + connectButton.getHeight())) { listenForConnection(); countdown = MessageHandler.SOCKET_TIMEOUT / 1000 + 1; new Timer("Countdown Timer").schedule(new TimerTask() { @Override public void run() { if(--countdown < 0) { cancel(); } } }, 0, 1000); } } }
diff --git a/src/se/anyro/nfc_reader/TagViewer.java b/src/se/anyro/nfc_reader/TagViewer.java index db7fc52..e4ef089 100644 --- a/src/se/anyro/nfc_reader/TagViewer.java +++ b/src/se/anyro/nfc_reader/TagViewer.java @@ -1,275 +1,269 @@ /* * Copyright (C) 2010 The Android Open Source Project * Copyright (C) 2011 Adam Nyb�ck * * 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 se.anyro.nfc_reader; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import se.anyro.nfc_reader.record.ParsedNdefRecord; import android.app.Activity; import android.app.AlertDialog; import android.app.PendingIntent; import android.content.Intent; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.MifareClassic; import android.nfc.tech.MifareUltralight; import android.os.Bundle; import android.os.Parcelable; import android.view.LayoutInflater; import android.widget.LinearLayout; import android.widget.TextView; /** * An {@link Activity} which handles a broadcast of a new tag that the device just discovered. */ public class TagViewer extends Activity { private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat(); private LinearLayout mTagContent; private NfcAdapter mAdapter; private PendingIntent mPendingIntent; private NdefMessage mNdefPushMessage; private AlertDialog mDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tag_viewer); mTagContent = (LinearLayout) findViewById(R.id.list); resolveIntent(getIntent()); mDialog = new AlertDialog.Builder(this).setNeutralButton("Ok", null).create(); mAdapter = NfcAdapter.getDefaultAdapter(this); if (mAdapter == null) { showMessage(R.string.error, R.string.no_nfc); } mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); mNdefPushMessage = new NdefMessage(new NdefRecord[] { newTextRecord( "Message from NFC Reader :-)", Locale.ENGLISH, true) }); } private void showMessage(int title, int message) { mDialog.setTitle(title); mDialog.setMessage(getText(message)); mDialog.show(); } private NdefRecord newTextRecord(String text, Locale locale, boolean encodeInUtf8) { byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII")); Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16"); byte[] textBytes = text.getBytes(utfEncoding); int utfBit = encodeInUtf8 ? 0 : (1 << 7); char status = (char) (utfBit + langBytes.length); byte[] data = new byte[1 + langBytes.length + textBytes.length]; data[0] = (byte) status; System.arraycopy(langBytes, 0, data, 1, langBytes.length); System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length); return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data); } @Override protected void onResume() { super.onResume(); if (mAdapter != null) { if (!mAdapter.isEnabled()) { showMessage(R.string.error, R.string.nfc_disabled); } mAdapter.enableForegroundDispatch(this, mPendingIntent, null, null); mAdapter.enableForegroundNdefPush(this, mNdefPushMessage); } } @Override protected void onPause() { super.onPause(); if (mAdapter != null) { mAdapter.disableForegroundDispatch(this); mAdapter.disableForegroundNdefPush(this); } } private void resolveIntent(Intent intent) { String action = intent.getAction(); if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); NdefMessage[] msgs; if (rawMsgs != null) { msgs = new NdefMessage[rawMsgs.length]; for (int i = 0; i < rawMsgs.length; i++) { msgs[i] = (NdefMessage) rawMsgs[i]; } } else { // Unknown tag type byte[] empty = new byte[0]; byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID); Parcelable tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); byte[] payload = null; try { payload = dumpTagData(tag).getBytes(); } catch (Exception e) { throw new RuntimeException(e); } NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload); NdefMessage msg = new NdefMessage(new NdefRecord[] { record }); msgs = new NdefMessage[] { msg }; } // Setup the views buildTagViews(msgs); } } - /** - * The reflection stuff in this method is copied from some Japanies site for backwards compatibility with Android - * 2.3-2.3.2. - */ - private String dumpTagData(Parcelable p) throws SecurityException, IllegalArgumentException, - IllegalAccessException { + private String dumpTagData(Parcelable p) { StringBuilder sb = new StringBuilder(); Tag tag = (Tag) p; byte[] id = tag.getId(); sb.append("Tag ID (hex): ").append(getHex(id)).append("\n"); sb.append("Tag ID (dec): ").append(getDec(id)).append("\n"); String prefix = "android.nfc.tech."; sb.append("Technologies: "); for (String tech : tag.getTechList()) { sb.append(tech.substring(prefix.length())); sb.append(", "); } sb.delete(sb.length() - 2, sb.length()); - sb.append('\n'); for (String tech : tag.getTechList()) { if (tech.equals(MifareClassic.class.getName())) { + sb.append('\n'); MifareClassic mifareTag = MifareClassic.get(tag); String type = "Unknown"; switch (mifareTag.getType()) { case MifareClassic.TYPE_CLASSIC: type = "Classic"; break; case MifareClassic.TYPE_PLUS: type = "Plus"; break; case MifareClassic.TYPE_PRO: type = "Pro"; break; } sb.append("Mifare Classic type: "); sb.append(type); sb.append('\n'); sb.append("Mifare size: "); sb.append(mifareTag.getSize() + " bytes"); sb.append('\n'); sb.append("Mifare sectors: "); sb.append(mifareTag.getSectorCount()); sb.append('\n'); sb.append("Mifare blocks: "); sb.append(mifareTag.getBlockCount()); - sb.append('\n'); } if (tech.equals(MifareUltralight.class.getName())) { + sb.append('\n'); MifareUltralight mifareUlTag = MifareUltralight.get(tag); String type = "Unknown"; switch (mifareUlTag.getType()) { case MifareUltralight.TYPE_ULTRALIGHT: type = "Ultralight"; break; case MifareUltralight.TYPE_ULTRALIGHT_C: type = "Ultralight C"; break; } sb.append("Mifare Ultralight type: "); sb.append(type); - sb.append('\n'); } } return sb.toString(); } private String getHex(byte[] bytes) { StringBuilder sb = new StringBuilder(); - for (int i = 0; i < bytes.length; i++) { + for (int i = bytes.length - 1; i >= 0; --i) { int b = bytes[i] & 0xff; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); - if (i != bytes.length - 1) { + if (i > 0) { sb.append(" "); } } return sb.toString(); } private long getDec(byte[] bytes) { long result = 0; long factor = 1; for (int i = 0; i < bytes.length; ++i) { long value = bytes[i] & 0xffl; result += value * factor; factor *= 256l; } return result; } void buildTagViews(NdefMessage[] msgs) { if (msgs == null || msgs.length == 0) { return; } LayoutInflater inflater = LayoutInflater.from(this); LinearLayout content = mTagContent; // Parse the first message in the list // Build views for all of the sub records Date now = new Date(); List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]); final int size = records.size(); for (int i = 0; i < size; i++) { TextView timeView = new TextView(this); timeView.setText(TIME_FORMAT.format(now)); content.addView(timeView, 0); ParsedNdefRecord record = records.get(i); content.addView(record.getView(this, inflater, content, i), 1 + i); content.addView(inflater.inflate(R.layout.tag_divider, content, false), 2 + i); } } @Override public void onNewIntent(Intent intent) { setIntent(intent); resolveIntent(intent); } }
false
false
null
null
diff --git a/src-gwt/com/alkacon/acacia/client/widgets/StringWidget.java b/src-gwt/com/alkacon/acacia/client/widgets/StringWidget.java index 1508302..643c4fb 100644 --- a/src-gwt/com/alkacon/acacia/client/widgets/StringWidget.java +++ b/src-gwt/com/alkacon/acacia/client/widgets/StringWidget.java @@ -1,266 +1,272 @@ /* * This library is part of the Acacia Editor - * an open source inline and form based content editor for GWT. * * Copyright (c) Alkacon Software GmbH (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * 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 com.alkacon.acacia.client.widgets; import com.alkacon.acacia.client.css.I_LayoutBundle; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.Style.Position; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; +import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyPressEvent; import com.google.gwt.event.dom.client.KeyPressHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextArea; /** * The string edit widget.<p> */ public class StringWidget extends A_EditWidget { /** The value to know if the user want to paste something. */ protected boolean m_paste; /** Indicating if the widget is active. */ private boolean m_active; /** The value changed handler initialized flag. */ private boolean m_valueChangeHandlerInitialized; /** * Constructor.<p> */ public StringWidget() { this(DOM.createDiv()); } /** * Constructor wrapping a specific DOM element.<p> * * @param element the element to wrap */ public StringWidget(Element element) { super(element); init(); } /** * @see com.google.gwt.event.logical.shared.HasValueChangeHandlers#addValueChangeHandler(com.google.gwt.event.logical.shared.ValueChangeHandler) */ @Override public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) { // Initialization code if (!m_valueChangeHandlerInitialized) { m_valueChangeHandlerInitialized = true; addDomHandler(new KeyPressHandler() { /** The courser position. */ protected JavaScriptObject m_range; /** The Element of this widget. */ protected com.google.gwt.dom.client.Element m_element; /** Helper text area to store the text that should be pasted. */ protected TextArea m_helpfield; public void onKeyPress(KeyPressEvent event) { // check if something is paste to the field if (event.isShiftKeyDown() || event.isControlKeyDown()) { int charCode = event.getCharCode(); if ((charCode == 'v') || (charCode == 45)) { m_helpfield = new TextArea(); m_helpfield.getElement().getStyle().setPosition(Position.FIXED); m_range = getSelection(); m_element = event.getRelativeElement(); m_element.setAttribute("contentEditable", "false"); RootPanel.get().add(m_helpfield); m_helpfield.setFocus(true); } } + // prevent adding line breaks + if (KeyCodes.KEY_ENTER == event.getNativeEvent().getKeyCode()) { + event.preventDefault(); + event.stopPropagation(); + } // schedule the change event, so the key press can take effect Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { if (m_range != null) { String pasteValue = m_helpfield.getText(); m_helpfield.removeFromParent(); m_element.setAttribute("contentEditable", "true"); setFocus(true); setSelection(m_range, pasteValue); m_range = null; } fireValueChange(false); } }); } }, KeyPressEvent.getType()); addDomHandler(new ChangeHandler() { public void onChange(ChangeEvent event) { fireValueChange(false); } }, ChangeEvent.getType()); addDomHandler(new BlurHandler() { public void onBlur(BlurEvent event) { fireValueChange(false); } }, BlurEvent.getType()); } return addHandler(handler, ValueChangeEvent.getType()); } /** * @see com.google.gwt.user.client.ui.HasValue#getValue() */ @Override public String getValue() { return getElement().getInnerText(); } /** * @see com.alkacon.acacia.client.widgets.I_EditWidget#isActive() */ public boolean isActive() { return m_active; } /** * @see com.alkacon.acacia.client.widgets.I_EditWidget#setActive(boolean) */ public void setActive(boolean active) { if (m_active == active) { return; } m_active = active; if (m_active) { getElement().setAttribute("contentEditable", "true"); getElement().removeClassName(I_LayoutBundle.INSTANCE.form().inActive()); getElement().focus(); fireValueChange(true); } else { getElement().setAttribute("contentEditable", "false"); getElement().addClassName(I_LayoutBundle.INSTANCE.form().inActive()); } } /** * @see com.alkacon.acacia.client.widgets.I_EditWidget#setName(java.lang.String) */ public void setName(String name) { // nothing to do } /** * @see com.google.gwt.user.client.ui.HasValue#setValue(java.lang.Object) */ public void setValue(String value) { setValue(value, true); } /** * @see com.google.gwt.user.client.ui.HasValue#setValue(java.lang.Object, boolean) */ public void setValue(String value, boolean fireEvents) { getElement().setInnerText(value); if (fireEvents) { fireValueChange(false); } } /** * Returns the actual range of the courser.<p> * * @return the actual range of the courser */ protected native JavaScriptObject getSelection() /*-{ var range, sel; sel = $wnd.rangy.getSelection(); range = null; if (sel.rangeCount > 0) { range = sel.getRangeAt(0); } else { range = rangy.createRange(); } return range; }-*/; /** * Includes the new text into the text block.<p> * @param range the range where the text should be included * @param text the text that should be included */ protected native void setSelection(JavaScriptObject range, String text) /*-{ var sel; range.deleteContents(); var textNode = $wnd.document.createTextNode(text) range.insertNode(textNode); sel = $wnd.rangy.getSelection(); range.setStart(textNode, textNode.length); range.setEnd(textNode, textNode.length); sel.removeAllRanges(); sel.setSingleRange(range); }-*/; /** * Initializes the widget.<p> */ private void init() { getElement().setAttribute("contentEditable", "true"); addStyleName(I_LayoutBundle.INSTANCE.form().input()); m_active = true; } }
false
false
null
null
diff --git a/src/org/ohmage/activity/ResponseInfoActivity.java b/src/org/ohmage/activity/ResponseInfoActivity.java index 7422f6e..1e89ea5 100644 --- a/src/org/ohmage/activity/ResponseInfoActivity.java +++ b/src/org/ohmage/activity/ResponseInfoActivity.java @@ -1,581 +1,584 @@ /******************************************************************************* * Copyright 2011 The Regents of the University of California * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License 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.ohmage.activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; -import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.SimpleCursorAdapter; import android.support.v4.widget.SimpleCursorAdapter.ViewBinder; import android.text.Html; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.android.imageloader.ImageLoader; import com.google.android.imageloader.ImageLoader.BindResult; import com.google.android.imageloader.ImageLoader.Callback; import org.json.JSONArray; import org.json.JSONException; import org.ohmage.ConfigHelper; import org.ohmage.OhmageApi; import org.ohmage.OhmageApplication; import org.ohmage.OhmageMarkdown; import org.ohmage.R; +import org.ohmage.Utilities; import org.ohmage.db.DbContract; import org.ohmage.db.DbContract.Campaigns; import org.ohmage.db.DbContract.PromptResponses; import org.ohmage.db.DbContract.Responses; import org.ohmage.db.DbContract.SurveyPrompts; import org.ohmage.db.DbContract.Surveys; import org.ohmage.db.Models.Response; import org.ohmage.logprobe.Analytics; +import org.ohmage.logprobe.Log; import org.ohmage.prompt.AbstractPrompt; import org.ohmage.service.SurveyGeotagService; import org.ohmage.ui.BaseInfoActivity; import org.ohmage.ui.ResponseActivityHelper; import java.io.File; -import java.io.FileInputStream; import java.io.FileNotFoundException; +import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * This Activity is used to display Information for an individual response. It * is called with {@link Intent#ACTION_VIEW} on the URI specified by * {@link DbContract.Responses#getResponseUri(long)} * * @author cketcham * */ public class ResponseInfoActivity extends BaseInfoActivity implements LoaderManager.LoaderCallbacks<Cursor> { private ImageLoader mImageLoader; private TextView mapViewButton; private TextView uploadButton; private ResponseActivityHelper mResponseHelper; private int mStatus; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentFragment(new ResponsePromptsFragment()); mResponseHelper = new ResponseActivityHelper(this); mImageLoader = ImageLoader.get(this); // inflate the campaign-specific info page into the scrolling framelayout LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); // and inflate all the possible commands into the button tray inflater.inflate(R.layout.response_info_buttons, mButtonTray, true); // Prepare the loader. Either re-connect with an existing one, // or start a new one. getSupportLoaderManager().initLoader(0, null, this); mapViewButton = (TextView) findViewById(R.id.response_info_button_view_map); mapViewButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Analytics.widget(v); startActivity(new Intent(OhmageApplication.VIEW_MAP, getIntent().getData())); } }); uploadButton = (TextView) findViewById(R.id.response_info_button_upload); uploadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Analytics.widget(v); if(mStatus == Response.STATUS_STANDBY) mResponseHelper.queueForUpload(getIntent().getData()); else { Bundle bundle = new Bundle(); bundle.putParcelable(ResponseActivityHelper.KEY_URI, getIntent().getData()); showDialog(mStatus, bundle); } } }); } @Override public void onContentChanged() { super.onContentChanged(); mEntityHeader.setVisibility(View.GONE); } @Override protected void onPrepareDialog(int id, Dialog dialog, Bundle args) { mResponseHelper.onPrepareDialog(id, dialog, args); } @Override protected Dialog onCreateDialog(int id, Bundle args) { return mResponseHelper.onCreateDialog(id, args); } private interface ResponseQuery { String[] PROJECTION = { Campaigns.CAMPAIGN_NAME, Surveys.SURVEY_TITLE, Responses.RESPONSE_TIME, Campaigns.CAMPAIGN_ICON, Responses.RESPONSE_LOCATION_STATUS, Responses.RESPONSE_STATUS}; int CAMPAIGN_NAME = 0; int SURVEY_TITLE = 1; int TIME = 2; int CAMPAIGN_ICON = 3; int LOCATION_STATUS = 4; int STATUS = 5; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { return new CursorLoader(this, getIntent().getData(), ResponseQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (!data.moveToFirst()) { Toast.makeText(this, R.string.response_info_response_deleted, Toast.LENGTH_SHORT).show(); finish(); return; } final String surveyName = data.getString(ResponseQuery.SURVEY_TITLE); final Long completedDate = data.getLong(ResponseQuery.TIME); mStatus = data.getInt(ResponseQuery.STATUS); if(mStatus == Response.STATUS_STANDBY) uploadButton.setContentDescription(getString(R.string.response_info_entity_action_button_upload_description)); else if(mStatus == Response.STATUS_WAITING_FOR_LOCATION) uploadButton.setContentDescription(getString(R.string.response_info_entity_action_button_upload_force_description)); else uploadButton.setContentDescription(getString(R.string.response_info_entity_action_button_upload_error_description)); mHeadertext.setText(surveyName); mSubtext.setText(data.getString(ResponseQuery.CAMPAIGN_NAME)); // If we aren't in single campaign mode, show the campaign name mSubtext.setVisibility((ConfigHelper.isSingleCampaignMode()) ? View.GONE : View.VISIBLE); SimpleDateFormat df = new SimpleDateFormat(); mNotetext.setText(df.format(new Date(completedDate))); final String iconUrl = data.getString(ResponseQuery.CAMPAIGN_ICON); if(iconUrl == null || mImageLoader.bind(mIconView, iconUrl, null) != ImageLoader.BindResult.OK) { mIconView.setImageResource(R.drawable.apple_logo); } mEntityHeader.setVisibility(View.VISIBLE); // Make the map view button status aware so it can provide some useful info about the gps state if(mStatus == Response.STATUS_WAITING_FOR_LOCATION) { mapViewButton.setText(R.string.response_info_gps_wait); mapViewButton.setEnabled(false); } else if(!(SurveyGeotagService.LOCATION_VALID.equals(data.getString(ResponseQuery.LOCATION_STATUS)))) { mapViewButton.setText(R.string.response_info_no_location); mapViewButton.setEnabled(false); } else { mapViewButton.setText(R.string.response_info_view_map); mapViewButton.setEnabled(true); } // Make upload button visible if applicable uploadButton.setVisibility(View.VISIBLE); switch(mStatus) { case Response.STATUS_DOWNLOADED: case Response.STATUS_UPLOADED: uploadButton.setVisibility(View.GONE); break; case Response.STATUS_STANDBY: case Response.STATUS_WAITING_FOR_LOCATION: uploadButton.setText(R.string.response_info_upload); uploadButton.setEnabled(true); break; case Response.STATUS_QUEUED: case Response.STATUS_UPLOADING: uploadButton.setText(R.string.response_info_uploading); uploadButton.setEnabled(false); break; default: // Error uploadButton.setText(R.string.response_info_upload_error); uploadButton.setEnabled(true); } } @Override public void onLoaderReset(Loader<Cursor> loader) { mEntityHeader.setVisibility(View.GONE); } public static class ResponsePromptsFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = "ResponseInfoListFragment"; // This is the Adapter being used to display the list's data. PromptResponsesAdapter mAdapter; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // We have no menu items to show in action bar. setHasOptionsMenu(false); getListView().setDivider(null); // Create an empty adapter we will use to display the loaded data. mAdapter = new PromptResponsesAdapter(getActivity(), null, new String[] { SurveyPrompts.SURVEY_PROMPT_TEXT, PromptResponses.PROMPT_RESPONSE_VALUE }, new int[] { android.R.id.text1, R.id.prompt_value }, 0, getResponseId()); setListAdapter(mAdapter); // Start out with a progress indicator. setListShown(false); getLoaderManager().initLoader(0, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { return new CursorLoader(getActivity(), Responses.buildPromptResponsesUri(Long.valueOf(getResponseId())), null, PromptResponses.PROMPT_RESPONSE_VALUE + " !=?", new String[] { "NOT_DISPLAYED" }, null); } public String getResponseId() { return Responses.getResponseId(getActivity().getIntent().getData()); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mAdapter.swapCursor(data); // The list should now be shown. if (isResumed()) { setListShown(true); } else { setListShownNoAnimation(true); } } @Override public void onLoaderReset(Loader<Cursor> loader) { mAdapter.swapCursor(null); } private static class PromptResponsesAdapter extends SimpleCursorAdapter implements ViewBinder { public static final int UNKNOWN_RESPONSE = -1; public static final int TEXT_RESPONSE = 0; public static final int IMAGE_RESPONSE = 1; public static final int HOURSBEFORENOW_RESPONSE = 2; public static final int TIMESTAMP_RESPONSE = 3; public static final int MULTICHOICE_RESPONSE = 4; public static final int MULTICHOICE_CUSTOM_RESPONSE = 5; public static final int SINGLECHOICE_RESPONSE = 6; public static final int SINGLECHOICE_CUSTOM_RESPONSE = 7; public static final int NUMBER_RESPONSE = 8; public static final int REMOTE_RESPONSE = 9; public static final int VIDEO_RESPONSE = 10; private final String mResponseId; private final ImageLoader mImageLoader; public PromptResponsesAdapter(Context context, Cursor c, String[] from, int[] to, int flags, String responseId) { super(context, R.layout.response_prompt_list_item, c, from, to, flags); mImageLoader = ImageLoader.get(context); setViewBinder(this); mResponseId = responseId; } @Override public int getItemViewType(int position) { if(getCursor().moveToPosition(position)) return getItemViewType(getCursor()); return 0; } /** * Gets the view type for this item by the cursor. The cursor needs to be moved to the correct position prior to calling * this function * @param cursor * @return the view type */ public int getItemViewType(Cursor cursor) { String promptType = getItemPromptType(cursor); if("photo".equals(promptType)) return IMAGE_RESPONSE; else if ("video".equals(promptType)) return VIDEO_RESPONSE; else if ("text".equals(promptType)) return TEXT_RESPONSE; else if ("hours_before_now".equals(promptType)) return HOURSBEFORENOW_RESPONSE; else if ("timestamp".equals(promptType)) return TIMESTAMP_RESPONSE; else if ("single_choice".equals(promptType)) return SINGLECHOICE_RESPONSE; else if ("single_choice_custom".equals(promptType)) return SINGLECHOICE_CUSTOM_RESPONSE; else if ("multi_choice".equals(promptType)) return MULTICHOICE_RESPONSE; else if ("multi_choice_custom".equals(promptType)) return MULTICHOICE_CUSTOM_RESPONSE; else if ("number".equals(promptType)) return NUMBER_RESPONSE; else if ("remote_activity".equals(promptType)) return REMOTE_RESPONSE; else return UNKNOWN_RESPONSE; } /** * Gets the prompt type for this item by the cursor. The cursor needs to be moved to the correct position prior to calling * this function * @param cursor * @return */ public String getItemPromptType(Cursor cursor) { return cursor.getString(cursor.getColumnIndex(SurveyPrompts.SURVEY_PROMPT_TYPE)); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = super.newView(context, cursor, parent); View image = view.findViewById(R.id.prompt_image_value); View progress = view.findViewById(R.id.prompt_image_progress); View text = view.findViewById(R.id.prompt_text_value); View value = view.findViewById(R.id.prompt_value); ImageView icon = (ImageView) view.findViewById(R.id.prompt_icon); int itemViewType = getItemViewType(cursor); // set the icon for each prompt type switch(itemViewType) { case VIDEO_RESPONSE: case IMAGE_RESPONSE: icon.setImageResource(R.drawable.prompttype_photo); break; case HOURSBEFORENOW_RESPONSE: icon.setImageResource(R.drawable.prompttype_hoursbeforenow); break; case TIMESTAMP_RESPONSE: icon.setImageResource(R.drawable.prompttype_timestamp); break; case MULTICHOICE_RESPONSE: icon.setImageResource(R.drawable.prompttype_multichoice); break; case MULTICHOICE_CUSTOM_RESPONSE: icon.setImageResource(R.drawable.prompttype_multichoice_custom); break; case SINGLECHOICE_RESPONSE: icon.setImageResource(R.drawable.prompttype_singlechoice); break; case SINGLECHOICE_CUSTOM_RESPONSE: icon.setImageResource(R.drawable.prompttype_singlechoice_custom); break; case NUMBER_RESPONSE: icon.setImageResource(R.drawable.prompttype_number); break; case REMOTE_RESPONSE: icon.setImageResource(R.drawable.prompttype_remote); break; case TEXT_RESPONSE: icon.setImageResource(R.drawable.prompttype_text); break; } // now set up how they're actually displayed // there are only two categories: image and non-image (i.e. text) if (itemViewType != IMAGE_RESPONSE // also if the image was skipped we are showing the text view || AbstractPrompt.SKIPPED_VALUE.equals(cursor.getString(cursor.getColumnIndex(PromptResponses.PROMPT_RESPONSE_VALUE)))) { progress.setVisibility(View.GONE); image.setVisibility(View.GONE); text.setVisibility(View.VISIBLE); value.setTag(text); } else { progress.setVisibility(View.VISIBLE); image.setVisibility(View.VISIBLE); text.setVisibility(View.GONE); value.setTag(image); value.setBackgroundResource(R.drawable.prompt_response_image_item_bg); } return view; } @Override public int getViewTypeCount() { return 11; } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return false; } @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if(cursor.getColumnName(columnIndex).equals(PromptResponses.PROMPT_RESPONSE_VALUE)) { final String value = cursor.getString(columnIndex); if(view.getTag() instanceof ImageView) { String campaignUrn = cursor.getString(cursor.getColumnIndex(Responses.CAMPAIGN_URN)); final File file = Response.getTemporaryResponsesMedia(value); final ImageView imageView = (ImageView) view.getTag(); if(file != null && file.exists()) { try { - BitmapDrawable d = (BitmapDrawable) imageView.getDrawable(); - if(d!=null) d.getBitmap().recycle(); - Bitmap img = BitmapFactory.decodeStream(new FileInputStream(file)); + BitmapDrawable d = (BitmapDrawable) imageView.getDrawable(); + if(d!=null) d.getBitmap().recycle(); + Bitmap img = Utilities.decodeImage(file, 600); imageView.setImageBitmap(img); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Analytics.widget(v, "View Local Fullsize Image"); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "image/jpeg"); mContext.startActivity(intent); } }); return true; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); + } catch (IOException e) { + Log.e(TAG, "Error decoding image", e); } } String url = OhmageApi.defaultImageReadUrl(value, campaignUrn, "small"); final String largeUrl = OhmageApi.defaultImageReadUrl(value, campaignUrn, null); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Analytics.widget(v, "View Fullsize Image"); Intent intent = new Intent(OhmageApplication.ACTION_VIEW_REMOTE_IMAGE, Uri.parse(largeUrl)); mContext.startActivity(intent); } }); mImageLoader.clearErrors(); BindResult bindResult = mImageLoader.bind((ImageView)view.getTag(), url, new Callback() { @Override public void onImageLoaded(ImageView view, String url) { imageView.setVisibility(View.VISIBLE); imageView.setClickable(true); imageView.setFocusable(true); } @Override public void onImageError(ImageView view, String url, Throwable error) { imageView.setVisibility(View.VISIBLE); imageView.setImageResource(android.R.drawable.ic_dialog_alert); imageView.setClickable(false); imageView.setFocusable(false); } }); if(bindResult == ImageLoader.BindResult.ERROR) { imageView.setImageResource(android.R.drawable.ic_dialog_alert); imageView.setClickable(false); imageView.setFocusable(false); } else if(bindResult == ImageLoader.BindResult.LOADING){ imageView.setVisibility(View.GONE); } } else if(view.getTag() instanceof TextView) { String prompt_type = getItemPromptType(cursor); if("multi_choice_custom".equals(prompt_type) || "multi_choice".equals(prompt_type)) { try { JSONArray choices = new JSONArray(value); StringBuilder builder = new StringBuilder(); for(int i=0;i<choices.length();i++) { if(i != 0) builder.append("<br\\>"); builder.append("&bull; "); builder.append(OhmageMarkdown.parseHtml(choices.get(i).toString())); } ((TextView) view.getTag()).setText(Html.fromHtml(builder.toString())); return true; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if("single_choice_custom".equals(prompt_type) || "single_choice".equals(prompt_type)) { ((TextView) view.getTag()).setText(OhmageMarkdown.parse(value)); return true; } else if("timestamp".equals(prompt_type)) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); try { long time = format.parse(value).getTime(); StringBuilder timeDisplay = new StringBuilder(DateUtils.formatDateTime(mContext, time, DateUtils.FORMAT_SHOW_YEAR)); timeDisplay.append(" at "); timeDisplay.append(DateUtils.formatDateTime(mContext, time, DateUtils.FORMAT_SHOW_TIME)); ((TextView) view.getTag()).setText(timeDisplay); return true; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ((TextView) view.getTag()).setText(value); } return true; } return false; } } } } \ No newline at end of file
false
false
null
null
diff --git a/jsf-api/src/javax/faces/component/ValueHolder.java b/jsf-api/src/javax/faces/component/ValueHolder.java index e77de0c5a..f075c55a5 100644 --- a/jsf-api/src/javax/faces/component/ValueHolder.java +++ b/jsf-api/src/javax/faces/component/ValueHolder.java @@ -1,119 +1,137 @@ /* * $Id: ValueHolder.java,v 1.20.12.1 2008/04/21 20:31:24 edburns Exp $ */ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package javax.faces.component; import javax.faces.convert.Converter; import javax.el.ValueExpression; /** * <p><strong class="changed_modified_2_0">ValueHolder</strong> is an * interface that may be implemented by any concrete {@link UIComponent} * that wishes to support a local value, as well as access data in the * model tier via a <em>value expression</em>, and support conversion * between String and the model tier data's native data type. */ public interface ValueHolder { // -------------------------------------------------------------- Properties /** * <p>Return the local value of this {@link UIComponent} (if any), * without evaluating any associated {@link ValueExpression}.</p> */ public Object getLocalValue(); /** * <p>Gets the value of this {@link UIComponent}. First, consult * the local value property of this component. If * non-<code>null</code> return it. If <code>null</code>, see if we have a * {@link ValueExpression} for the <code>value</code> property. If * so, return the result of evaluating the property, otherwise * return <code>null</code>. Note that because the specification for {@link * UIComponent#setValueBinding} requires a * call through to {@link UIComponent#setValueExpression}, legacy * tags will continue to work.</p> */ public Object getValue(); + /* + * PENDING(rlubke) I suggest calling logic from the ctor that checks + * the init param and caches it on the ApplicationMap. Once the + * value of the pref has been discovered, I suggest caching it as a + * boolean ivar, which is saved as part of the UIOutput's state. + */ + /** - * <p>Set the value of this {@link UIComponent} (if any).</p> + * <p><span class="changed_modified_2_0">Set</span> the value of + * this {@link UIComponent} (if any). <span + * class="changed_added_2_0">If the + * <code>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</code> + * application configuration param is set, and calling + * <code>toLowerCase().equals("true")</code> on a <code>String + * representation of its value returns <code>true</code>, the + * following additional action must be taken.</p> + * + * <p class="changed_modified_2_0">If + * <code>this.getSubmittedValue()</code> is the empty string, set + * <code>null</code> as the value of this <code>ValueHolder</code> + * instance rather than setting the empty string as the value.</p> * * @param value The new local value */ public void setValue(Object value); - /** * <p>Return the {@link Converter} (if any) * that is registered for this {@link UIComponent}.</p> */ public Converter getConverter(); /** * <p><span class="changed_modified_2_0">Set</span> the {@link * Converter} (if any) that is registered for this {@link * UIComponent}.</p> * * <p class="changed_added_2_0">The argument * <code>converter</code> must be inspected for the presence of the * {@link javax.faces.application.ResourceDependency} annotation. * If the <code>ResourceDependency</code> annotation is present, * the action described in <code>ResourceDependency</code> must * be taken. If the <code>ResourceDependency</code> annotation is * not present, the argument <code>converter</code> must be inspected * for the presence of the {@link * javax.faces.application.ResourceDependencies} annotation. * If the <code>ResourceDependencies</code> annotation * is present, the action described in <code>ResourceDependencies</code> * must be taken.</p> * * @param converter New {@link Converter} (or <code>null</code>) */ public void setConverter(Converter converter); }
false
false
null
null
diff --git a/org/python/modules/sre/SRE_STATE.java b/org/python/modules/sre/SRE_STATE.java index 112a08e3..249cf4ba 100644 --- a/org/python/modules/sre/SRE_STATE.java +++ b/org/python/modules/sre/SRE_STATE.java @@ -1,1219 +1,1227 @@ /* * Copyright 2000 Finn Bock * * This program contains material copyrighted by: * Copyright (c) 1997-2000 by Secret Labs AB. All rights reserved. * * This version of the SRE library can be redistributed under CNRI's * Python 1.6 license. For any other use, please contact Secret Labs * AB (info@pythonware.com). * * Portions of this engine have been developed in cooperation with * CNRI. Hewlett-Packard provided funding for 1.6 integration and * other compatibility work. */ // Last updated to _sre.c: 2.52 package org.python.modules.sre; import java.util.*; public class SRE_STATE { /* illegal opcode */ public static final int SRE_ERROR_ILLEGAL = -1; /* illegal state */ public static final int SRE_ERROR_STATE = -2; /* runaway recursion */ public static final int SRE_ERROR_RECURSION_LIMIT = -3; public static final int SRE_OP_FAILURE = 0; public static final int SRE_OP_SUCCESS = 1; public static final int SRE_OP_ANY = 2; public static final int SRE_OP_ANY_ALL = 3; public static final int SRE_OP_ASSERT = 4; public static final int SRE_OP_ASSERT_NOT = 5; public static final int SRE_OP_AT = 6; public static final int SRE_OP_BRANCH = 7; public static final int SRE_OP_CALL = 8; public static final int SRE_OP_CATEGORY = 9; public static final int SRE_OP_CHARSET = 10; public static final int SRE_OP_BIGCHARSET = 11; public static final int SRE_OP_GROUPREF = 12; public static final int SRE_OP_GROUPREF_IGNORE = 13; public static final int SRE_OP_IN = 14; public static final int SRE_OP_IN_IGNORE = 15; public static final int SRE_OP_INFO = 16; public static final int SRE_OP_JUMP = 17; public static final int SRE_OP_LITERAL = 18; public static final int SRE_OP_LITERAL_IGNORE = 19; public static final int SRE_OP_MARK = 20; public static final int SRE_OP_MAX_UNTIL = 21; public static final int SRE_OP_MIN_UNTIL = 22; public static final int SRE_OP_NOT_LITERAL = 23; public static final int SRE_OP_NOT_LITERAL_IGNORE = 24; public static final int SRE_OP_NEGATE = 25; public static final int SRE_OP_RANGE = 26; public static final int SRE_OP_REPEAT = 27; public static final int SRE_OP_REPEAT_ONE = 28; public static final int SRE_OP_SUBPATTERN = 29; public static final int SRE_AT_BEGINNING = 0; public static final int SRE_AT_BEGINNING_LINE = 1; public static final int SRE_AT_BEGINNING_STRING = 2; public static final int SRE_AT_BOUNDARY = 3; public static final int SRE_AT_NON_BOUNDARY = 4; public static final int SRE_AT_END = 5; public static final int SRE_AT_END_LINE = 6; public static final int SRE_AT_END_STRING = 7; public static final int SRE_AT_LOC_BOUNDARY = 8; public static final int SRE_AT_LOC_NON_BOUNDARY = 9; public static final int SRE_AT_UNI_BOUNDARY = 10; public static final int SRE_AT_UNI_NON_BOUNDARY = 11; public static final int SRE_CATEGORY_DIGIT = 0; public static final int SRE_CATEGORY_NOT_DIGIT = 1; public static final int SRE_CATEGORY_SPACE = 2; public static final int SRE_CATEGORY_NOT_SPACE = 3; public static final int SRE_CATEGORY_WORD = 4; public static final int SRE_CATEGORY_NOT_WORD = 5; public static final int SRE_CATEGORY_LINEBREAK = 6; public static final int SRE_CATEGORY_NOT_LINEBREAK = 7; public static final int SRE_CATEGORY_LOC_WORD = 8; public static final int SRE_CATEGORY_LOC_NOT_WORD = 9; public static final int SRE_CATEGORY_UNI_DIGIT = 10; public static final int SRE_CATEGORY_UNI_NOT_DIGIT = 11; public static final int SRE_CATEGORY_UNI_SPACE = 12; public static final int SRE_CATEGORY_UNI_NOT_SPACE = 13; public static final int SRE_CATEGORY_UNI_WORD = 14; public static final int SRE_CATEGORY_UNI_NOT_WORD = 15; public static final int SRE_CATEGORY_UNI_LINEBREAK = 16; public static final int SRE_CATEGORY_UNI_NOT_LINEBREAK = 17; public static final int SRE_FLAG_TEMPLATE = 1; public static final int SRE_FLAG_IGNORECASE = 2; public static final int SRE_FLAG_LOCALE = 4; public static final int SRE_FLAG_MULTILINE = 8; public static final int SRE_FLAG_DOTALL = 16; public static final int SRE_FLAG_UNICODE = 32; public static final int SRE_FLAG_VERBOSE = 64; public static final int SRE_INFO_PREFIX = 1; public static final int SRE_INFO_LITERAL = 2; public static final int SRE_INFO_CHARSET = 4; public static final int USE_RECURSION_LIMIT = 2000; /* string pointers */ int ptr; /* current position (also end of current slice) */ int beginning; /* start of original string */ int start; /* start of current slice */ int end; /* end of original string */ /* attributes for the match object */ char[] str; int pos; int endpos; /* character size */ int charsize; /* registers */ int lastindex; int lastmark; /* FIXME: <fl> should be dynamically allocated! */ int[] mark = new int[200]; /* dynamically allocated stuff */ int[] mark_stack; int mark_stack_size; int mark_stack_base; SRE_REPEAT repeat; /* current repeat context */ /* debugging */ int maxlevel; /* duplicated from the PatternObject */ int flags; public SRE_STATE(String str, int start, int end, int flags) { this.str = str.toCharArray(); int size = str.length(); this.charsize = 1; /* adjust boundaries */ if (start < 0) start = 0; else if (start > size) start = size; if (end < 0) end = 0; else if (end > size) end = size; this.start = start; this.end = end; this.pos = start; this.endpos = end; state_reset(); this.flags = flags; } private void mark_fini() { mark_stack = null; mark_stack_size = mark_stack_base = 0; } private void mark_save(int lo, int hi) { if (hi <= lo) return; int size = (hi - lo) + 1; int newsize = mark_stack_size; int minsize = mark_stack_base + size; int[] stack; if (newsize < minsize) { /* create new stack */ if (newsize == 0) { newsize = 512; if (newsize < minsize) newsize = minsize; //TRACE(0, ptr, "allocate stack " + newsize); stack = new int[newsize]; } else { /* grow the stack */ while (newsize < minsize) newsize += newsize; //TRACE(0, ptr, "grow stack to " + newsize); stack = new int[newsize]; System.arraycopy(mark_stack, 0, stack, 0, mark_stack.length); } mark_stack = stack; mark_stack_size = newsize; } //TRACE(0, ptr, "copy " + lo + ":" + hi + " to " + mark_stack_base + " (" + size + ")"); System.arraycopy(mark, lo, mark_stack, mark_stack_base, size); mark_stack_base += size; } private void mark_restore(int lo, int hi) { if (hi <= lo) return; int size = (hi - lo) + 1; mark_stack_base -= size; //TRACE(0, ptr, "copy " + lo + ":" + hi + " from " + mark_stack_base); System.arraycopy(mark_stack, mark_stack_base, mark, lo, size); } final boolean SRE_AT(int ptr, char at) { /* check if pointer is at given position. return 1 if so, 0 otherwise */ boolean thiS, that; switch (at) { case SRE_AT_BEGINNING: case SRE_AT_BEGINNING_STRING: return ptr == beginning; case SRE_AT_BEGINNING_LINE: return (ptr == beginning || SRE_IS_LINEBREAK(str[ptr-1])); case SRE_AT_END: return (ptr+1 == end && SRE_IS_LINEBREAK(str[ptr])) || ptr == end; case SRE_AT_END_LINE: return ptr == end || SRE_IS_LINEBREAK(str[ptr]); case SRE_AT_END_STRING: return ptr == end; case SRE_AT_BOUNDARY: /* word boundary */ if (beginning == end) return false; that = (ptr > beginning) ? SRE_IS_WORD(str[ptr-1]) : false; thiS = (ptr < end) ? SRE_IS_WORD(str[ptr]) : false; return thiS != that; case SRE_AT_NON_BOUNDARY: /* word non-boundary */ if (beginning == end) return false; that = (ptr > beginning) ? SRE_IS_WORD(str[ptr-1]) : false; thiS = (ptr < end) ? SRE_IS_WORD(str[ptr]) : false; return thiS == that; case SRE_AT_LOC_BOUNDARY: case SRE_AT_UNI_BOUNDARY: if (beginning == end) return false; that = (ptr > beginning) ? SRE_LOC_IS_WORD(str[ptr-1]) : false; thiS = (ptr < end) ? SRE_LOC_IS_WORD(str[ptr]) : false; return thiS != that; case SRE_AT_LOC_NON_BOUNDARY: case SRE_AT_UNI_NON_BOUNDARY: /* word non-boundary */ if (beginning == end) return false; that = (ptr > beginning) ? SRE_LOC_IS_WORD(str[ptr-1]) : false; thiS = (ptr < end) ? SRE_LOC_IS_WORD(str[ptr]) : false; return thiS == that; } return false; } final boolean SRE_CHARSET(char[] set, int setidx, char ch) { /* check if character is a member of the given set. return 1 if so, 0 otherwise */ boolean ok = true; for (;;) { switch (set[setidx++]) { case SRE_OP_LITERAL: + //TRACE(setidx, ch, "CHARSET LITERAL " + (int) set[setidx]); /* <LITERAL> <code> */ if (ch == set[setidx]) return ok; setidx++; break; case SRE_OP_RANGE: /* <RANGE> <lower> <upper> */ + //TRACE(setidx, ch, "CHARSET RANGE " + (int) set[setidx] + " " + (int) set[setidx+1]); if (set[setidx] <= ch && ch <= set[setidx+1]) return ok; setidx += 2; break; case SRE_OP_CHARSET: + //TRACE(setidx, ch, "CHARSET CHARSET "); /* <CHARSET> <bitmap> (16 bits per code word) */ if (ch < 256 && (set[setidx + (ch >> 4)] & (1 << (ch & 15))) != 0) return ok; setidx += 16; break; case SRE_OP_BIGCHARSET: /* <BIGCHARSET> <blockcount> <256 blockindices> <blocks> */ + //TRACE(setidx, ch, "CHARSET BIGCHARSET "); int count = set[setidx++]; - int block = set[ch >> 8]; + int shift = ((ch >> 8) & 1) == 0 ? 8 : 0; + int block = (set[setidx + (ch >> 8) / 2] >> shift) & 0xFF; setidx += 128; int idx = block*16 + ((ch & 255)>>4); if ((set[setidx + idx] & (1 << (ch & 15))) != 0) return ok; setidx += count*16; break; case SRE_OP_CATEGORY: /* <CATEGORY> <code> */ + //TRACE(setidx, ch, "CHARSET CHARSET " + (int) set[setidx]); if (sre_category(set[setidx], ch)) return ok; setidx++; break; case SRE_OP_NEGATE: + //TRACE(setidx, ch, "CHARSET NEGATE"); ok = !ok; break; case SRE_OP_FAILURE: + //TRACE(setidx, ch, "CHARSET FAILURE"); return !ok; default: /* internal error -- there's not much we can do about it here, so let's just pretend it didn't match... */ return false; } } } private int SRE_COUNT(char[] pattern, int pidx, int maxcount, int level) { char chr; int ptr = this.ptr; int end = this.end; int i; /* adjust end */ if (maxcount < end - ptr && maxcount != 65535) end = ptr + maxcount; switch (pattern[pidx]) { case SRE_OP_ANY: /* repeated dot wildcard. */ //TRACE(pidx, ptr, "COUNT ANY"); while (ptr < end && !SRE_IS_LINEBREAK(str[ptr])) ptr++; break; case SRE_OP_ANY_ALL: /* repeated dot wildcare. skip to the end of the target string, and backtrack from there */ //TRACE(pidx, ptr, "COUNT ANY_ALL"); ptr = end; break; case SRE_OP_LITERAL: /* repeated literal */ chr = pattern[pidx+1]; //TRACE(pidx, ptr, "COUNT LITERAL " + (int) chr); while (ptr < end && str[ptr] == chr) ptr++; break; case SRE_OP_LITERAL_IGNORE: /* repeated literal */ chr = pattern[pidx+1]; //TRACE(pidx, ptr, "COUNT LITERAL_IGNORE " + (int) chr); while (ptr < end && lower(str[ptr]) == chr) ptr++; break; case SRE_OP_NOT_LITERAL: /* repeated non-literal */ chr = pattern[pidx+1]; //TRACE(pidx, ptr, "COUNT NOT_LITERAL " + (int) chr); while (ptr < end && str[ptr] != chr) ptr++; break; case SRE_OP_NOT_LITERAL_IGNORE: /* repeated non-literal */ chr = pattern[pidx+1]; //TRACE(pidx, ptr, "COUNT NOT_LITERAL_IGNORE " + (int) chr); while (ptr < end && lower(str[ptr]) != chr) ptr++; break; case SRE_OP_IN: /* repeated set */ //TRACE(pidx, ptr, "COUNT IN"); while (ptr < end && SRE_CHARSET(pattern, pidx + 2, str[ptr])) ptr++; break; default: /* repeated single character pattern */ //TRACE(pidx, ptr, "COUNT SUBPATTERN"); while (this.ptr < end) { i = SRE_MATCH(pattern, pidx, level); if (i < 0) return i; if (i == 0) break; } return this.ptr - ptr; } return ptr - this.ptr; } final int SRE_MATCH(char[] pattern, int pidx, int level) { /* check if string matches the given pattern. returns <0 for error, 0 for failure, and 1 for success */ int end = this.end; int ptr = this.ptr; int i, count; char chr; int lastmark; //TRACE(pidx, ptr, "ENTER " + level); if (level > USE_RECURSION_LIMIT) return SRE_ERROR_RECURSION_LIMIT; if (pattern[pidx] == SRE_OP_INFO) { /* optimization info block */ /* args: <1=skip> <2=flags> <3=min> ... */ if (pattern[pidx+3] != 0 && (end - ptr) < pattern[pidx+3]) { return 0; } pidx += pattern[pidx+1] + 1; } for (;;) { switch (pattern[pidx++]) { case SRE_OP_FAILURE: /* immediate failure */ //TRACE(pidx, ptr, "FAILURE"); return 0; case SRE_OP_SUCCESS: /* end of pattern */ //TRACE(pidx, ptr, "SUCCESS"); this.ptr = ptr; return 1; case SRE_OP_AT: /* match at given position */ /* <AT> <code> */ //TRACE(pidx, ptr, "AT " + (int) pattern[pidx]); if (!SRE_AT(ptr, pattern[pidx])) return 0; pidx++; break; case SRE_OP_CATEGORY: /* match at given category */ /* <CATEGORY> <code> */ //TRACE(pidx, ptr, "CATEGORY " + (int)pattern[pidx]); if (ptr >= end || !sre_category(pattern[pidx], str[ptr])) return 0; pidx++; ptr++; break; case SRE_OP_LITERAL: /* match literal character */ /* <LITERAL> <code> */ //TRACE(pidx, ptr, "LITERAL " + (int) pattern[pidx]); if (ptr >= end || str[ptr] != pattern[pidx]) return 0; pidx++; ptr++; break; case SRE_OP_NOT_LITERAL: /* match anything that is not literal character */ /* args: <code> */ //TRACE(pidx, ptr, "NOT_LITERAL " + (int) pattern[pidx]); if (ptr >= end || str[ptr] == pattern[pidx]) return 0; pidx++; ptr++; break; case SRE_OP_ANY: /* match anything */ //TRACE(pidx, ptr, "ANY"); if (ptr >= end || SRE_IS_LINEBREAK(str[ptr])) return 0; ptr++; break; case SRE_OP_ANY_ALL: /* match anything */ /* <ANY_ALL> */ //TRACE(pidx, ptr, "ANY_ALL"); if (ptr >= end) return 0; ptr++; break; case SRE_OP_IN: /* match set member (or non_member) */ /* <IN> <skip> <set> */ //TRACE(pidx, ptr, "IN"); if (ptr >= end || !SRE_CHARSET(pattern, pidx + 1, str[ptr])) return 0; pidx += (int)pattern[pidx]; ptr++; break; case SRE_OP_GROUPREF: /* match backreference */ i = pattern[pidx]; //TRACE(pidx, ptr, "GROUPREF " + i); int p = mark[i+i]; int e = mark[i+i+1]; if (p == -1 || e == -1 || e < p) return 0; while (p < e) { if (ptr >= end || str[ptr] != str[p]) return 0; p++; ptr++; } pidx++; break; case SRE_OP_GROUPREF_IGNORE: /* match backreference */ i = pattern[pidx]; //TRACE(pidx, ptr, "GROUPREF_IGNORE " + i); p = mark[i+i]; e = mark[i+i+1]; if (p == -1 || e == -1 || e < p) return 0; while (p < e) { if (ptr >= end || lower(str[ptr]) != lower(str[p])) return 0; p++; ptr++; } pidx++; break; case SRE_OP_LITERAL_IGNORE: //TRACE(pidx, ptr, "LITERAL_IGNORE " + (int) pattern[pidx]); if (ptr >= end || lower(str[ptr]) != lower(pattern[pidx])) return 0; pidx++; ptr++; break; case SRE_OP_NOT_LITERAL_IGNORE: //TRACE(pidx, ptr, "NOT_LITERAL_IGNORE " + (int) pattern[pidx]); if (ptr >= end || lower(str[ptr]) == lower(pattern[pidx])) return 0; pidx++; ptr++; break; case SRE_OP_IN_IGNORE: //TRACE(pidx, ptr, "IN_IGNORE"); if (ptr >= end || !SRE_CHARSET(pattern, pidx + 1, lower(str[ptr]))) return 0; pidx += (int)pattern[pidx]; ptr++; break; case SRE_OP_MARK: /* set mark */ /* <MARK> <gid> */ //TRACE(pidx, ptr, "MARK " + (int) pattern[pidx]); i = pattern[pidx]; if ((i & 1) != 0) lastindex = i / 2 + 1; if (i > this.lastmark) this.lastmark = i; mark[i] = ptr; pidx++; break; case SRE_OP_JUMP: case SRE_OP_INFO: /* jump forward */ /* <JUMP> <offset> */ //TRACE(pidx, ptr, "JUMP " + (int) pattern[pidx]); pidx += (int)pattern[pidx]; break; case SRE_OP_ASSERT: /* assert subpattern */ /* args: <skip> <back> <pattern> */ //TRACE(pidx, ptr, "ASSERT " + (int) pattern[pidx+1]); this.ptr = ptr - pattern[pidx + 1]; if (this.ptr < this.beginning) return 0; i = SRE_MATCH(pattern, pidx + 2, level + 1); if (i <= 0) return i; pidx += pattern[pidx]; break; case SRE_OP_ASSERT_NOT: /* assert not subpattern */ /* args: <skip> <pattern> */ //TRACE(pidx, ptr, "ASSERT_NOT " + (int) pattern[pidx]); this.ptr = ptr - pattern[pidx + 1]; if (this.ptr >= this.beginning) { i = SRE_MATCH(pattern, pidx + 2, level + 1); if (i < 0) return i; if (i != 0) return 0; } pidx += pattern[pidx]; break; case SRE_OP_BRANCH: /* try an alternate branch */ /* <BRANCH> <0=skip> code <JUMP> ... <NULL> */ //TRACE(pidx, ptr, "BRANCH"); lastmark = this.lastmark; for (; pattern[pidx] != 0; pidx += pattern[pidx]) { if (pattern[pidx+1] == SRE_OP_LITERAL && (ptr >= end || str[ptr] != pattern[pidx+2])) continue; if (pattern[pidx+1] == SRE_OP_IN && (ptr >= end || !SRE_CHARSET(pattern, pidx + 3, str[ptr]))) continue; this.ptr = ptr; i = SRE_MATCH(pattern, pidx + 1, level + 1); if (i != 0) return i; while (this.lastmark > lastmark) mark[this.lastmark--] = -1; } return 0; case SRE_OP_REPEAT_ONE: /* match repeated sequence (maximizing regexp) */ /* this operator only works if the repeated item is exactly one character wide, and we're not already collecting backtracking points. for other cases, use the MAX_REPEAT operator */ /* <REPEAT_ONE> <skip> <1=min> <2=max> item <SUCCESS> tail */ int mincount = pattern[pidx+1]; //TRACE(pidx, ptr, "REPEAT_ONE " + mincount + " " + (int)pattern[pidx+2]); if (ptr + mincount > end) return 0; /* cannot match */ this.ptr = ptr; count = SRE_COUNT(pattern, pidx + 3, pattern[pidx+2], level + 1); if (count < 0) return count; ptr += count; /* when we arrive here, count contains the number of matches, and ptr points to the tail of the target string. check if the rest of the pattern matches, and backtrack if not. */ if (count < mincount) return 0; if (pattern[pidx + pattern[pidx]] == SRE_OP_SUCCESS) { /* tail is empty. we're finished */ this.ptr = ptr; return 1; } else if (pattern[pidx + pattern[pidx]] == SRE_OP_LITERAL) { /* tail starts with a literal. skip positions where the rest of the pattern cannot possibly match */ chr = pattern[pidx + pattern[pidx]+1]; for (;;) { while (count >= mincount && (ptr >= end || str[ptr] != chr)) { ptr--; count--; } if (count < mincount) break; this.ptr = ptr; i = SRE_MATCH(pattern, pidx + pattern[pidx], level + 1); if (i != 0) return 1; ptr--; count--; } } else { /* general case */ lastmark = this.lastmark; while (count >= mincount) { this.ptr = ptr; i = SRE_MATCH(pattern, pidx + pattern[pidx], level + 1); if (i != 0) return i; ptr--; count--; while (this.lastmark > lastmark) mark[this.lastmark--] = -1; } } return 0; case SRE_OP_REPEAT: /* create repeat context. all the hard work is done by the UNTIL operator (MAX_UNTIL, MIN_UNTIL) */ /* <REPEAT> <skip> <1=min> <2=max> item <UNTIL> tail */ //TRACE(pidx, ptr, "REPEAT " + (int)pattern[pidx+1] + " " + (int)pattern[pidx+2]); SRE_REPEAT rep = new SRE_REPEAT(repeat); rep.count = -1; rep.pidx = pidx; repeat = rep; this.ptr = ptr; i = SRE_MATCH(pattern, pidx + pattern[pidx], level + 1); repeat = rep.prev; return i; case SRE_OP_MAX_UNTIL: /* maximizing repeat */ /* <REPEAT> <skip> <1=min> <2=max> item <MAX_UNTIL> tail */ /* FIXME: we probably need to deal with zero-width matches in here... */ SRE_REPEAT rp = this.repeat; if (rp == null) return SRE_ERROR_STATE; this.ptr = ptr; count = rp.count + 1; //TRACE(pidx, ptr, "MAX_UNTIL " + count); if (count < pattern[rp.pidx + 1]) { /* not enough matches */ rp.count = count; i = SRE_MATCH(pattern, rp.pidx + 3, level + 1); if (i != 0) return i; rp.count = count - 1; this.ptr = ptr; return 0; } if (count < pattern[rp.pidx+2] || pattern[rp.pidx+2] == 65535) { /* we may have enough matches, but if we can match another item, do so */ rp.count = count; lastmark = this.lastmark; mark_save(0, lastmark); /* RECURSIVE */ i = SRE_MATCH(pattern, rp.pidx + 3, level + 1); if (i != 0) return i; mark_restore(0, lastmark); this.lastmark = lastmark; rp.count = count - 1; this.ptr = ptr; } /* cannot match more repeated items here. make sure the tail matches */ this.repeat = rp.prev; /* RECURSIVE */ i = SRE_MATCH(pattern, pidx, level + 1); if (i != 0) return i; this.repeat = rp; this.ptr = ptr; return 0; case SRE_OP_MIN_UNTIL: /* minimizing repeat */ /* <REPEAT> <skip> <1=min> <2=max> item <MIN_UNTIL> tail */ rp = this.repeat; if (rp == null) return SRE_ERROR_STATE; count = rp.count + 1; //TRACE(pidx, ptr, "MIN_UNTIL " + count + " " + rp.pidx); this.ptr = ptr; if (count < pattern[rp.pidx + 1]) { /* not enough matches */ rp.count = count; /* RECURSIVE */ i = SRE_MATCH(pattern, rp.pidx + 3, level + 1); if (i != 0) return i; rp.count = count-1; this.ptr = ptr; return 0; } /* see if the tail matches */ this.repeat = rp.prev; i = SRE_MATCH(pattern, pidx, level + 1); if (i != 0) return i; this.ptr = ptr; this.repeat = rp; if (count >= pattern[rp.pidx+2] && pattern[rp.pidx+2] != 65535) return 0; rp.count = count; /* RECURSIVE */ i = SRE_MATCH(pattern, rp.pidx + 3, level + 1); if (i != 0) return i; rp.count = count - 1; this.ptr = ptr; return 0; default: //TRACE(pidx, ptr, "UNKNOWN " + (int) pattern[pidx-1]); return SRE_ERROR_ILLEGAL; } } //return SRE_ERROR_ILLEGAL; } int SRE_SEARCH(char[] pattern, int pidx) { int ptr = this.start; int end = this.end; int status = 0; int prefix_len = 0; int prefix_skip = 0; int prefix = 0; int charset = 0; int overlap = 0; int flags = 0; if (pattern[pidx] == SRE_OP_INFO) { /* optimization info block */ /* <INFO> <1=skip> <2=flags> <3=min> <4=max> <5=prefix info> */ flags = pattern[pidx+2]; if (pattern[pidx+3] > 0) { /* adjust end point (but make sure we leave at least one character in there, so literal search will work) */ end -= pattern[pidx+3]-1; if (end <= ptr) end = ptr; // FBO } if ((flags & SRE_INFO_PREFIX) != 0) { /* pattern starts with a known prefix */ /* <length> <skip> <prefix data> <overlap data> */ prefix_len = pattern[pidx+5]; prefix_skip = pattern[pidx+6]; prefix = pidx + 7; overlap = prefix + prefix_len - 1; } else if ((flags & SRE_INFO_CHARSET) != 0) { /* pattern starts with a character from a known set */ /* <charset> */ charset = pidx + 5; } pidx += 1 + pattern[pidx+1]; } if (prefix_len > 1) { /* pattern starts with a known prefix. use the overlap table to skip forward as fast as we possibly can */ int i = 0; end = this.end; while (ptr < end) { for (;;) { if (str[ptr] != pattern[prefix+i]) { if (i == 0) break; else i = pattern[overlap+i]; } else { if (++i == prefix_len) { /* found a potential match */ //TRACE(pidx, ptr, "SEARCH SCAN " + prefix_skip + " " + prefix_len); this.start = ptr + 1 - prefix_len; this.ptr = ptr + 1 - prefix_len + prefix_skip; if ((flags & SRE_INFO_LITERAL) != 0) return 1; /* we got all of it */ status = SRE_MATCH(pattern, pidx + 2*prefix_skip, 1); if (status != 0) return status; /* close but no cigar -- try again */ i = pattern[overlap + i]; } break; } } ptr++; } return 0; } if (pattern[pidx] == SRE_OP_LITERAL) { /* pattern starts with a literal */ char chr = pattern[pidx + 1]; end = this.end; for (;;) { while (ptr < end && str[ptr] != chr) ptr++; if (ptr == end) return 0; //TRACE(pidx, ptr, "SEARCH LITERAL"); this.start = ptr; this.ptr = ++ptr; if ((flags & SRE_INFO_LITERAL) != 0) return 1; status = SRE_MATCH(pattern, pidx + 2, 1); if (status != 0) break; } } else if (charset != 0) { /* pattern starts with a character from a known set */ end = this.end; for (;;) { while (ptr < end && !SRE_CHARSET(pattern, charset, str[ptr])) ptr++; if (ptr == end) return 0; //TRACE(pidx, ptr, "SEARCH CHARSET"); this.start = ptr; this.ptr = ptr; status = SRE_MATCH(pattern, pidx, 1); if (status != 0) break; ptr++; } } else { /* general case */ while (ptr <= end) { //TRACE(pidx, ptr, "SEARCH"); this.start = this.ptr = ptr++; status = SRE_MATCH(pattern, pidx, 1); if (status != 0) break; } } return status; } final boolean sre_category(char category, char ch) { switch (category) { case SRE_CATEGORY_DIGIT: return SRE_IS_DIGIT(ch); case SRE_CATEGORY_NOT_DIGIT: return ! SRE_IS_DIGIT(ch); case SRE_CATEGORY_SPACE: return SRE_IS_SPACE(ch); case SRE_CATEGORY_NOT_SPACE: return ! SRE_IS_SPACE(ch); case SRE_CATEGORY_WORD: return SRE_IS_WORD(ch); case SRE_CATEGORY_NOT_WORD: return ! SRE_IS_WORD(ch); case SRE_CATEGORY_LINEBREAK: return SRE_IS_LINEBREAK(ch); case SRE_CATEGORY_NOT_LINEBREAK: return ! SRE_IS_LINEBREAK(ch); case SRE_CATEGORY_LOC_WORD: return SRE_LOC_IS_WORD(ch); case SRE_CATEGORY_LOC_NOT_WORD: return ! SRE_LOC_IS_WORD(ch); case SRE_CATEGORY_UNI_DIGIT: return Character.isDigit(ch); case SRE_CATEGORY_UNI_NOT_DIGIT: return !Character.isDigit(ch); case SRE_CATEGORY_UNI_SPACE: return Character.isWhitespace(ch); case SRE_CATEGORY_UNI_NOT_SPACE: return !Character.isWhitespace(ch); case SRE_CATEGORY_UNI_WORD: return Character.isLetterOrDigit(ch) || ch == '_'; case SRE_CATEGORY_UNI_NOT_WORD: return ! (Character.isLetterOrDigit(ch) || ch == '_'); case SRE_CATEGORY_UNI_LINEBREAK: return SRE_UNI_IS_LINEBREAK(ch); case SRE_CATEGORY_UNI_NOT_LINEBREAK: return ! SRE_UNI_IS_LINEBREAK(ch); } return false; } /* default character predicates (run sre_chars.py to regenerate tables) */ static final int SRE_DIGIT_MASK = 1; static final int SRE_SPACE_MASK = 2; static final int SRE_LINEBREAK_MASK = 4; static final int SRE_ALNUM_MASK = 8; static final int SRE_WORD_MASK = 16; static byte[] sre_char_info = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 0, 0, 16, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 0, 0, 0 }; static byte[] sre_char_lower = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127 }; final boolean SRE_IS_DIGIT(char ch) { return ((ch) < 128 ? (sre_char_info[(ch)] & SRE_DIGIT_MASK) != 0 : false); } final boolean SRE_IS_SPACE(char ch) { return ((ch) < 128 ? (sre_char_info[(ch)] & SRE_SPACE_MASK) != 0 : false); } final boolean SRE_IS_WORD(char ch) { return ((ch) < 128 ? (sre_char_info[(ch)] & SRE_WORD_MASK) != 0 : false); } final boolean SRE_IS_LINEBREAK(char ch) { return ch == '\n'; } final boolean SRE_LOC_IS_WORD(char ch) { return Character.isLetterOrDigit(ch) || ch == '_'; } final boolean SRE_UNI_IS_LINEBREAK(char ch) { switch (ch) { case 0x000A: /* LINE FEED */ case 0x000D: /* CARRIAGE RETURN */ case 0x001C: /* FILE SEPARATOR */ case 0x001D: /* GROUP SEPARATOR */ case 0x001E: /* RECORD SEPARATOR */ case 0x0085: /* NEXT LINE */ case 0x2028: /* LINE SEPARATOR */ case 0x2029: /* PARAGRAPH SEPARATOR */ return true; default: return false; } } final char lower(char ch) { if ((flags & SRE_FLAG_LOCALE) != 0) return ((ch) < 256 ? Character.toLowerCase(ch) : ch); if ((flags & SRE_FLAG_UNICODE) != 0) return Character.toLowerCase(ch); return ((ch) < 128 ? (char)sre_char_lower[ch] : ch); } public static int getlower(int ch, int flags) { if ((flags & SRE_FLAG_LOCALE) != 0) return ((ch) < 256 ? Character.toLowerCase((char) ch) : ch); if ((flags & SRE_FLAG_UNICODE) != 0) return Character.toLowerCase((char)ch); return ((ch) < 128 ? (char)sre_char_lower[ch] : ch); } String getslice(int index, String string, boolean empty) { int i, j; index = (index - 1) * 2; if (string == null || mark[index] == -1 || mark[index+1] == -1) { if (empty) { /* want empty string */ i = j = 0; } else { return null; } } else { i = mark[index]; j = mark[index+1]; } return string.substring(i, j); } void state_reset() { lastmark = 0; /* FIXME: dynamic! */ for (int i = 0; i < mark.length; i++) mark[i] = -1; lastindex = -1; repeat = null; mark_fini(); } private void TRACE(int pidx, int ptr, String string) { //System.out.println(" |" + pidx + "|" + ptr + ": " + string); } }
false
false
null
null
diff --git a/ace-repository/src/main/java/org/apache/ace/repository/impl/RepositoryFactory.java b/ace-repository/src/main/java/org/apache/ace/repository/impl/RepositoryFactory.java index b7486908..5632c6f9 100644 --- a/ace-repository/src/main/java/org/apache/ace/repository/impl/RepositoryFactory.java +++ b/ace-repository/src/main/java/org/apache/ace/repository/impl/RepositoryFactory.java @@ -1,181 +1,181 @@ /* * 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.ace.repository.impl; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.Dictionary; import java.util.HashMap; import java.util.Map; import org.apache.ace.repository.Repository; import org.apache.ace.repository.RepositoryReplication; import org.apache.ace.repository.impl.constants.RepositoryConstants; import org.apache.felix.dm.DependencyManager; -import org.apache.felix.dm.service.Service; +import org.apache.felix.dm.Service; import org.osgi.framework.BundleContext; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedServiceFactory; import org.osgi.service.log.LogService; import org.osgi.service.prefs.BackingStoreException; import org.osgi.service.prefs.Preferences; import org.osgi.service.prefs.PreferencesService; /** * A <code>ManagedServiceFactory</code> responsible for creating a (<code>Replication</code>)<code>Repository</code> * instance for each valid configuration that is received from the <code>ConfigurationAdmin</code>. */ public class RepositoryFactory implements ManagedServiceFactory { private volatile LogService m_log; /* injected by dependency manager */ private volatile BundleContext m_context; /* injected by dependency manager */ private volatile PreferencesService m_prefsService; /* injected by dependency manager */ private File m_tempDir; private File m_baseDir; private Preferences m_prefs; private final DependencyManager m_manager; private final Map<String, Service> m_instances = new HashMap<String, Service>(); public RepositoryFactory(DependencyManager manager) { m_manager = manager; } public synchronized void deleted(String pid) { // pull service Service service = m_instances.remove(pid); if (service != null) { m_manager.remove(service); } // remove persisted data File dir = new File(m_baseDir, pid); if (dir.isDirectory()) { File[] files = dir.listFiles(); for (int i = 0; (files != null) && (i < files.length); i++) { files[i].delete(); } if (!dir.delete()) { m_log.log(LogService.LOG_WARNING, "Unable to clean up files ( in " + dir.getAbsolutePath() + ") after removing repository"); } } try { m_prefs.node(pid).removeNode(); m_prefs.sync(); } catch (BackingStoreException e) { // Not much we can do } } public String getName() { return "RepositoryFactory"; } public synchronized void init() { m_tempDir = m_context.getDataFile("tmp"); if ((m_tempDir != null) && !m_tempDir.isDirectory() && !m_tempDir.mkdirs()) { throw new IllegalArgumentException("Unable to create temp directory (" + m_tempDir.getAbsolutePath() + ")"); } m_baseDir = m_context.getDataFile("repos"); if ((m_baseDir != null) && !m_baseDir.isDirectory() && !m_baseDir.mkdirs()) { throw new IllegalArgumentException("Unable to create base directory (" + m_baseDir.getAbsolutePath() + ")"); } } /** * Creates a new instance if the supplied dictionary contains a valid configuration. A configuration is valid if * <code>RepositoryConstants.REPOSITORY_NAME</code> and <code>RepositoryConstants.REPOSITORY_CUSTOMER</code> properties * are present, not empty and the combination of the two is unique in respect to other previously created instances. * Finally a property <code>RepositoryConstants.REPOSITORY_MASTER</code> should be present and be either <code>true</code> * or <code>false</code>. * * @param pid A unique identifier for the instance, generated by <code>ConfigurationAdmin</code> normally. * @param dict The configuration properties for the instance, see description above. * @throws ConfigurationException If any of the above explanation fails <b>or</b>when there is an internal error creating the repository. */ @SuppressWarnings("unchecked") public synchronized void updated(String pid, Dictionary dict) throws ConfigurationException { String name = (String) dict.get(RepositoryConstants.REPOSITORY_NAME); if ((name == null) || "".equals(name)) { throw new ConfigurationException(RepositoryConstants.REPOSITORY_NAME, "Repository name has to be specified."); } String customer = (String) dict.get(RepositoryConstants.REPOSITORY_CUSTOMER); if ((customer == null) || "".equals(customer)) { throw new ConfigurationException(RepositoryConstants.REPOSITORY_CUSTOMER, "Repository customer has to be specified."); } String master = (String) dict.get(RepositoryConstants.REPOSITORY_MASTER); if (!("false".equalsIgnoreCase(master.trim()) || "true".equalsIgnoreCase(master.trim()))) { throw new ConfigurationException(RepositoryConstants.REPOSITORY_MASTER, "Have to specify whether the repository is the master or a slave."); } boolean isMaster = Boolean.parseBoolean(master); String initialContents = (String) dict.get(RepositoryConstants.REPOSITORY_INITIAL_CONTENT); if (m_prefs == null) { m_prefs = m_prefsService.getSystemPreferences(); } String[] nodes; try { nodes = m_prefs.childrenNames(); } catch (BackingStoreException e) { throw new ConfigurationException("none", "Internal error while validating configuration."); } for (int i = 0; i < nodes.length; i++) { Preferences node = m_prefs.node(nodes[i]); if (name.equalsIgnoreCase(node.get(RepositoryConstants.REPOSITORY_NAME, "")) && name.equalsIgnoreCase(node.get(RepositoryConstants.REPOSITORY_CUSTOMER, ""))) { throw new ConfigurationException("name and customer", "Name and customer combination already exists"); } } Preferences node = m_prefs.node(pid); node.put(RepositoryConstants.REPOSITORY_NAME, name); node.put(RepositoryConstants.REPOSITORY_CUSTOMER, customer); Service service = m_instances.get(pid); if (service == null) { // new instance File dir = new File(m_baseDir, pid); RepositoryImpl store = new RepositoryImpl(dir, m_tempDir, isMaster); if ((initialContents != null) && isMaster) { try { store.commit(new ByteArrayInputStream(initialContents.getBytes()), 0); } catch (IOException e) { m_log.log(LogService.LOG_ERROR, "Unable to set initial contents of the repository.", e); } } service = m_manager.createService() .setInterface(new String[] {RepositoryReplication.class.getName(), Repository.class.getName()}, dict) .setImplementation(store) .add(m_manager.createServiceDependency().setService(LogService.class).setRequired(false)); m_manager.add(service); m_instances.put(pid, service); } else { // update existing instance RepositoryImpl store = (RepositoryImpl) service.getService(); store.updated(isMaster); } } } \ No newline at end of file
true
false
null
null
diff --git a/server/RequestProcessor.java b/server/RequestProcessor.java index bca7c88..b8ddc46 100644 --- a/server/RequestProcessor.java +++ b/server/RequestProcessor.java @@ -1,134 +1,135 @@ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.Socket; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.LinkedList; import java.util.List; import com.trend.Packet; public class RequestProcessor implements Runnable { private static List<Socket> pool = new LinkedList<Socket>(); private File localFile = null; private String filename =""; private long filesize = 0; private BufferedOutputStream fout = null; private MessageDigest mdsum; public static void processRequest(Socket request) { synchronized(pool) { pool.add(pool.size(), request); pool.notifyAll(); } } private void writeResponse(boolean success, Packet.Ack.AckType type, BufferedOutputStream conOut) throws IOException { Packet.Ack.Builder ackBuilder = Packet.Ack.newBuilder(); ackBuilder.setType(type); ackBuilder.setSuccess(success); Packet.Ack response = ackBuilder.build(); response.writeDelimitedTo(conOut); conOut.flush(); } private Packet.Block getFileBlock(BufferedInputStream in ) throws IOException { Packet.Block.Builder blockBuilder = Packet.Block.newBuilder(); blockBuilder.mergeDelimitedFrom(in); Packet.Block block = blockBuilder.build(); System.out.println(String.format("Receive a new block(Seq:%d Size:%d Digest:%s EOF:%s)", block.getSeqNum(), block.getSize(), block.getDigest(), block.getEof())); return block; } @Override public void run() { while (true) { Socket connection; synchronized(pool) { while (pool.isEmpty()) { try { pool.wait(); } catch (InterruptedException e) { } } connection = pool.remove(0); System.out.println("Accept a client from "+connection.getInetAddress().toString()); } try { BufferedInputStream in = new BufferedInputStream(connection.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); if (mdsum == null) mdsum = MessageDigest.getInstance("MD5"); else mdsum.reset(); if (fout == null) { Packet.Header.Builder headerBuilder = Packet.Header.newBuilder(); headerBuilder.mergeDelimitedFrom(in); Packet.Header header = headerBuilder.build(); fout = new BufferedOutputStream(new FileOutputStream("/tmp/"+header.getFileName())); filesize = header.getFileSize(); writeResponse(true, Packet.Ack.AckType.HEADER, out); System.out.println(String.format("Receive a new Header(filename:%s size:%d)",header.getFileName(), header.getFileSize())); } if (fout != null) { while (true) { Packet.Block block = getFileBlock(in); if (block.getEof()) { String digest = String.valueOf(mdsum.digest()); if (block.getDigest().equals(digest)) writeResponse(true, Packet.Ack.AckType.EOF, out); else writeResponse(false, Packet.Ack.AckType.EOF, out); break; } byte[] content = block.getContent().toByteArray(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(content); - String digest = String.valueOf(md.digest()); + String digest = md.digest().toString() ; + System.out.println( digest ) ; if (block.getDigest().equals(digest)) { fout.write(content, 0, block.getSize()); writeResponse(true, Packet.Ack.AckType.BLOCK, out); mdsum.update(content); } else { writeResponse(false, Packet.Ack.AckType.BLOCK, out); } } } } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { try { if (connection != null) connection.close(); if (fout != null) { fout.flush(); fout.close(); fout = null; } } catch (Exception e) { // Todo: } } } // end while } }
true
true
public void run() { while (true) { Socket connection; synchronized(pool) { while (pool.isEmpty()) { try { pool.wait(); } catch (InterruptedException e) { } } connection = pool.remove(0); System.out.println("Accept a client from "+connection.getInetAddress().toString()); } try { BufferedInputStream in = new BufferedInputStream(connection.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); if (mdsum == null) mdsum = MessageDigest.getInstance("MD5"); else mdsum.reset(); if (fout == null) { Packet.Header.Builder headerBuilder = Packet.Header.newBuilder(); headerBuilder.mergeDelimitedFrom(in); Packet.Header header = headerBuilder.build(); fout = new BufferedOutputStream(new FileOutputStream("/tmp/"+header.getFileName())); filesize = header.getFileSize(); writeResponse(true, Packet.Ack.AckType.HEADER, out); System.out.println(String.format("Receive a new Header(filename:%s size:%d)",header.getFileName(), header.getFileSize())); } if (fout != null) { while (true) { Packet.Block block = getFileBlock(in); if (block.getEof()) { String digest = String.valueOf(mdsum.digest()); if (block.getDigest().equals(digest)) writeResponse(true, Packet.Ack.AckType.EOF, out); else writeResponse(false, Packet.Ack.AckType.EOF, out); break; } byte[] content = block.getContent().toByteArray(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(content); String digest = String.valueOf(md.digest()); if (block.getDigest().equals(digest)) { fout.write(content, 0, block.getSize()); writeResponse(true, Packet.Ack.AckType.BLOCK, out); mdsum.update(content); } else { writeResponse(false, Packet.Ack.AckType.BLOCK, out); } } } } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { try { if (connection != null) connection.close(); if (fout != null) { fout.flush(); fout.close(); fout = null; } } catch (Exception e) { // Todo: } } } // end while }
public void run() { while (true) { Socket connection; synchronized(pool) { while (pool.isEmpty()) { try { pool.wait(); } catch (InterruptedException e) { } } connection = pool.remove(0); System.out.println("Accept a client from "+connection.getInetAddress().toString()); } try { BufferedInputStream in = new BufferedInputStream(connection.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); if (mdsum == null) mdsum = MessageDigest.getInstance("MD5"); else mdsum.reset(); if (fout == null) { Packet.Header.Builder headerBuilder = Packet.Header.newBuilder(); headerBuilder.mergeDelimitedFrom(in); Packet.Header header = headerBuilder.build(); fout = new BufferedOutputStream(new FileOutputStream("/tmp/"+header.getFileName())); filesize = header.getFileSize(); writeResponse(true, Packet.Ack.AckType.HEADER, out); System.out.println(String.format("Receive a new Header(filename:%s size:%d)",header.getFileName(), header.getFileSize())); } if (fout != null) { while (true) { Packet.Block block = getFileBlock(in); if (block.getEof()) { String digest = String.valueOf(mdsum.digest()); if (block.getDigest().equals(digest)) writeResponse(true, Packet.Ack.AckType.EOF, out); else writeResponse(false, Packet.Ack.AckType.EOF, out); break; } byte[] content = block.getContent().toByteArray(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(content); String digest = md.digest().toString() ; System.out.println( digest ) ; if (block.getDigest().equals(digest)) { fout.write(content, 0, block.getSize()); writeResponse(true, Packet.Ack.AckType.BLOCK, out); mdsum.update(content); } else { writeResponse(false, Packet.Ack.AckType.BLOCK, out); } } } } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { try { if (connection != null) connection.close(); if (fout != null) { fout.flush(); fout.close(); fout = null; } } catch (Exception e) { // Todo: } } } // end while }
diff --git a/ini/trakem2/persistence/CacheImageMipMaps.java b/ini/trakem2/persistence/CacheImageMipMaps.java index fa54ff23..adf98a6c 100644 --- a/ini/trakem2/persistence/CacheImageMipMaps.java +++ b/ini/trakem2/persistence/CacheImageMipMaps.java @@ -1,484 +1,487 @@ /** TrakEM2 plugin for ImageJ(C). Copyright (C) 2008 Albert Cardona and Stephan Preibisch. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (http://www.gnu.org/licenses/gpl.txt ) This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. You may contact Albert Cardona at acardona at ini.phys.ethz.ch Institute of Neuroinformatics, University of Zurich / ETH, Switzerland. **/ package ini.trakem2.persistence; import ini.trakem2.utils.IJError; import java.util.ArrayList; import java.util.Hashtable; import java.util.HashMap; import java.util.ListIterator; import java.util.LinkedList; import java.util.Iterator; import java.util.Map; import java.awt.Image; /** A cache for TrakEM2's rolling memory of java.awt.Image instances. * Uses both a list and a map. When the list goes beyond a certain LINEAR_SEARCH_LIMIT, then the map is used. * Each image is added as a CacheImageMipMaps.Entry, which stores the image, the corresponding Patch id and the level of the image (0, 1, 2 ... mipmap level of descresing power of 2 sizes). * The map contains unique Patch id keys versus Image arrays of values, where the array index is the index. */ public class CacheImageMipMaps { private final LinkedList<Entry> cache; private final HashMap<Long,Image[]> map = new HashMap<Long,Image[]>(); private boolean use_map = false; public static int LINEAR_SEARCH_LIMIT = 0; private class Entry { final long id; final int level; Image image; Entry (final long id, final int level, final Image image) { this.id = id; this.level = level; this.image = image; } public final boolean equals(final Object ob) { final Entry e = (Entry)ob; return e.id == id && e.level == level; } public final boolean equals(final long id, final int level) { return this.id == id && this.level == level; } } public CacheImageMipMaps(int initial_size) { cache = new LinkedList<Entry>(); } private final Entry rfind(final long id, final int level) { final ListIterator<Entry> li = cache.listIterator(cache.size()); // descendingIterator() is from java 1.6 ! while (li.hasPrevious()) { final Entry e = li.previous(); if (e.equals(id, level)) return e; } return null; } /** Replace or put. */ public void replace(final long id, final Image image, final int level) { final Entry e = rfind(id, level); if (null == e) put(id, image, level); else { if (null != e.image) e.image.flush(); e.image = image; } } static private final int computeLevel(final int i) { return (int)(0.5 + ((Math.log(i) - Math.log(32)) / Math.log(2))) + 1; } /** The position in the array is the Math.max(width, height) of an image. */ private final static int[] max_levels = new int[50000]; // don't change to smaller than 33. Here 50000 is the maximum width or height for which precomputed mipmap levels will exist. static { // from 0 to 31 all zeros for (int i=32; i<max_levels.length; i++) { max_levels[i] = computeLevel(i); } } private final int maxLevel(final Image image, final int starting_level) { final int w = image.getWidth(null); final int h = image.getHeight(null); /* int max_level = starting_level; while (w > 32 || h > 32) { w /= 2; h /= 2; max_level++; } return max_level; */ final int max = Math.max(w, h); if (max >= max_levels.length) { //if (max <= 32) return starting_level; return starting_level + computeLevel(max); } else { return starting_level + max_levels[max]; } } /** No duplicates allowed: if the id exists it's sended to the end and the image is first flushed (if different), then updated with the new one provided. */ public final void put(final long id, final Image image, final int level) { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { // images are more likely to be close to the end final Entry e = li.previous(); if (id == e.id && level == e.level) { li.remove(); cache.addLast(e); if (image != e.image) { // replace e.image.flush(); e.image = image; // replace in map - if (use_map) map.get(id)[level] = image; + if (use_map) { + final Image[] im = map.get(id); + if (null != im) im[level] = image; + } } return; } } // else, new cache.addLast(new Entry(id, level, image)); if (use_map) { // add new to the map Image[] images = map.get(id); try { if (null == images) { //System.out.println("CREATION maxLevel, level, image.width: " + maxLevel(image, level) + ", " + level + ", " + image.getWidth(null)); images = new Image[maxLevel(image, level)]; images[level] = image; map.put(id, images); } else { images[level] = image; } } catch (Exception e) { System.out.println("length of images[]: " + images.length); System.out.println("level to add: " + level); System.out.println("size of the image: " + image.getWidth(null)); System.out.println("maxlevel is: " + maxLevel(image, level)); } } else if (cache.size() >= LINEAR_SEARCH_LIMIT) { // create the map one step before it's used, hence the >= not > alone. // initialize map final ListIterator<Entry> lim = cache.listIterator(0); while (lim.hasNext()) { final Entry e = lim.next(); if (!map.containsKey(e.id)) { final Image[] images = new Image[maxLevel(image, level)]; images[e.level] = e.image; map.put(e.id, images); } else { final Image[] images = map.get(e.id); images[e.level] = e.image; } } use_map = true; //System.out.println("CREATED map"); } } /** A call to this method puts the element at the end of the list, and returns it. Returns null if not found. */ public final Image get(final long id, final int level) { if (0 == LINEAR_SEARCH_LIMIT) return getFromMap(id, level); final ListIterator<Entry> li = cache.listIterator(cache.size()); int i = 0; while (li.hasPrevious()) { // images are more likely to be close to the end if (i > LINEAR_SEARCH_LIMIT) { return getFromMap(id, level); } i++; /// final Entry e = li.previous(); if (id == e.id && level == e.level) { li.remove(); cache.addLast(e); return e.image; } } return null; } private final Image getFromMap(final long id, final int level) { final Image[] images = map.get(id); if (null == images) return null; return level < images.length ? images[level] : null; } private final Image getAboveFromMap(final long id, final int level) { final Image[] images = map.get(id); if (null == images) return null; for (int i=Math.min(level, images.length-1); i>-1; i--) { if (null != images[i]) return images[i]; } return null; } private final Image getBelowFromMap(final long id, final int level) { final Image[] images = map.get(id); if (null == images) return null; for (int i=level; i<images.length; i++) { if (null != images[i]) return images[i]; } return null; } /** Find the cached image of the given level or its closest but smaller image (larger level), or null if none found. */ public final Image getClosestBelow(final long id, final int level) { if (0 == LINEAR_SEARCH_LIMIT) return getBelowFromMap(id, level); Entry ee = null; int lev = Integer.MAX_VALUE; final ListIterator<Entry> li = cache.listIterator(cache.size()); int i = 0; while (li.hasPrevious()) { // images are more likely to be close to the end if (i > LINEAR_SEARCH_LIMIT) { return getBelowFromMap(id, level); } i++; /// final Entry e = li.previous(); if (e.id != id) continue; if (e.level == level) return e.image; if (e.level > level) { // if smaller image (larger level) than asked, choose the less smaller if (e.level < lev) { lev = e.level; ee = e; } } } if (null != ee) { cache.remove(ee); // unfortunaelly, removeLastOcurrence is java 1.6 only cache.addLast(ee); return ee.image; } return null; } /** Find the cached image of the given level or its closest but larger image (smaller level), or null if none found. */ public final Image getClosestAbove(final long id, final int level) { if (0 == LINEAR_SEARCH_LIMIT) return getAboveFromMap(id, level); int lev = -1; Entry ee = null; final ListIterator<Entry> li = cache.listIterator(cache.size()); int i = 0; while (li.hasPrevious()) { // images are more likely to be close to the end if (i > LINEAR_SEARCH_LIMIT) { return getAboveFromMap(id, level); } i++; final Entry e = li.previous(); if (e.id != id) continue; // if equal level as asked, just return it if (e.level == level) return e.image; // if exactly one above, just return it // may hinder finding an exact one, but potentially cuts down search time a lot // if (e.level == level + 1) return e.image; // WOULD NOT BE THE PERFECT IMAGE if the actual asked level is cached at a previous entry. if (e.level < level) { if (e.level > lev) { lev = e.level; ee = e; } } } if (null != ee) { cache.remove(ee); cache.addLast(ee); return ee.image; } return null; } /** Remove the Image if found and returns it, without flushing it. Returns null if not found. */ public final Image remove(final long id, final int level) { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (id == e.id && level == e.level) { li.remove(); return e.image; } } if (use_map) { final Image[] images = map.get(id); if (images == null) return null; images[level] = null; } return null; } /** Removes and flushes all images, and shrinks arrays. */ public final void removeAndFlushAll() { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); e.image.flush(); } cache.clear(); if (use_map) map.clear(); } /** Remove all awts associated with a level different than 0 (that means all scaled down versions) for any id. */ public void removeAllPyramids() { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (e.level > 0) { e.image.flush(); li.remove(); } } if (use_map) { final Iterator<Map.Entry<Long,Image[]>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Long,Image[]> entry = it.next(); final Image[] images = entry.getValue(); if (null == images[0]) it.remove(); for (int i=1; i<images.length; i++) { images[i] = null; } } } } /** Remove all awts associated with a level different than 0 (that means all scaled down versions) for the given id. */ public void removePyramid(final long id) { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (id == e.id && e.level > 0) { e.image.flush(); li.remove(); } } if (use_map) { final Image[] images = map.get(id); if (null != images) { for (int i=1; i<images.length; i++) { images[i] = null; } if (null == images[0]) map.remove(id); } } } /** Remove all images that share the same id (but have different levels). */ public final ArrayList<Image> remove(final long id) { final ArrayList<Image> al = new ArrayList<Image>(); final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (id == e.id) { al.add(e.image); li.remove(); } } if (use_map) { map.remove(id); } return al; } /** Returns a table of level keys and image values that share the same id (that is, belong to the same Patch). */ public final Hashtable<Integer,Image> getAll(final long id) { final Hashtable<Integer,Image> ht = new Hashtable<Integer,Image>(); if (use_map) { final Image[] images = map.get(id); if (null != images) { for (int i=0; i<images.length; i++) { if (null != images[i]) { ht.put(i, images[i]); } } } } else { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (id == e.id) ht.put(e.level, e.image); } } return ht; } /** Remove and flush away all images that share the same id. */ public final void removeAndFlush(final long id) { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (id == e.id) { e.image.flush(); li.remove(); } } if (use_map) map.remove(id); } /** Remove the given index and return it, returns null if outside range. */ public final Image remove(int i) { if (i < 0 || i >= cache.size()) return null; final Entry e = cache.remove(i); if (use_map) { nullifyMap(e.id, e.level); } return e.image; } private final void nullifyMap(final long id, final int level) { final Image[] images = map.get(id); if (null != images) { images[level] = null; for (Image im : images) { if (null != im) return; } // all null, remove map.remove(id); } } /** Remove the first element and return it. Returns null if none. The underlaying arrays are untouched besides nullifying the proper pointer. */ public final Image removeFirst() { final Entry e = cache.removeFirst(); if (use_map) { nullifyMap(e.id, e.level); } return e.image; } /** Checks if there's any image at all for the given id. */ public final boolean contains(final long id) { if (use_map) { return map.containsKey(id); } else { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { final Entry e = li.previous(); if (id == e.id) return true; } } return false; } /** Checks if there's any image for the given id and level. */ public final boolean contains(final long id, final int level) { if (use_map) { final Image[] images = map.get(id); if (null == images) return false; return level < images.length ? null != images[level] : false; } return -1 != cache.lastIndexOf(new Entry(id, level, null)); } public int size() { return cache.size(); } public void debug() { System.out.println("cache size: " + cache.size() + ", " + map.size()); } /** Does nothing. */ public void gc() {} }
true
true
public final void put(final long id, final Image image, final int level) { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { // images are more likely to be close to the end final Entry e = li.previous(); if (id == e.id && level == e.level) { li.remove(); cache.addLast(e); if (image != e.image) { // replace e.image.flush(); e.image = image; // replace in map if (use_map) map.get(id)[level] = image; } return; } } // else, new cache.addLast(new Entry(id, level, image)); if (use_map) { // add new to the map Image[] images = map.get(id); try { if (null == images) { //System.out.println("CREATION maxLevel, level, image.width: " + maxLevel(image, level) + ", " + level + ", " + image.getWidth(null)); images = new Image[maxLevel(image, level)]; images[level] = image; map.put(id, images); } else { images[level] = image; } } catch (Exception e) { System.out.println("length of images[]: " + images.length); System.out.println("level to add: " + level); System.out.println("size of the image: " + image.getWidth(null)); System.out.println("maxlevel is: " + maxLevel(image, level)); } } else if (cache.size() >= LINEAR_SEARCH_LIMIT) { // create the map one step before it's used, hence the >= not > alone. // initialize map final ListIterator<Entry> lim = cache.listIterator(0); while (lim.hasNext()) { final Entry e = lim.next(); if (!map.containsKey(e.id)) { final Image[] images = new Image[maxLevel(image, level)]; images[e.level] = e.image; map.put(e.id, images); } else { final Image[] images = map.get(e.id); images[e.level] = e.image; } } use_map = true; //System.out.println("CREATED map"); } }
public final void put(final long id, final Image image, final int level) { final ListIterator<Entry> li = cache.listIterator(cache.size()); while (li.hasPrevious()) { // images are more likely to be close to the end final Entry e = li.previous(); if (id == e.id && level == e.level) { li.remove(); cache.addLast(e); if (image != e.image) { // replace e.image.flush(); e.image = image; // replace in map if (use_map) { final Image[] im = map.get(id); if (null != im) im[level] = image; } } return; } } // else, new cache.addLast(new Entry(id, level, image)); if (use_map) { // add new to the map Image[] images = map.get(id); try { if (null == images) { //System.out.println("CREATION maxLevel, level, image.width: " + maxLevel(image, level) + ", " + level + ", " + image.getWidth(null)); images = new Image[maxLevel(image, level)]; images[level] = image; map.put(id, images); } else { images[level] = image; } } catch (Exception e) { System.out.println("length of images[]: " + images.length); System.out.println("level to add: " + level); System.out.println("size of the image: " + image.getWidth(null)); System.out.println("maxlevel is: " + maxLevel(image, level)); } } else if (cache.size() >= LINEAR_SEARCH_LIMIT) { // create the map one step before it's used, hence the >= not > alone. // initialize map final ListIterator<Entry> lim = cache.listIterator(0); while (lim.hasNext()) { final Entry e = lim.next(); if (!map.containsKey(e.id)) { final Image[] images = new Image[maxLevel(image, level)]; images[e.level] = e.image; map.put(e.id, images); } else { final Image[] images = map.get(e.id); images[e.level] = e.image; } } use_map = true; //System.out.println("CREATED map"); } }
diff --git a/dsz/DSZ.java b/dsz/DSZ.java index 78032bf..a19ad21 100644 --- a/dsz/DSZ.java +++ b/dsz/DSZ.java @@ -1,42 +1,41 @@ package dsz; import java.io.FileNotFoundException; import java.io.FileReader; import org.jsfml.window.*; import org.jsfml.window.event.*; import org.jsfml.graphics.*; public class DSZ { static String title = "Dungeons, Swords & Zombies"; public static void main(String[] args) { RenderWindow screen = new RenderWindow(new VideoMode(800,600),title); screen.setFramerateLimit(60); TextureArray texs = new TextureArray("tiles.png",8,2); Map bleh = new Map(texs); try { bleh.loadMapFile(new FileReader("test.map")); } catch (FileNotFoundException e) { e.printStackTrace(); } - System.out.println(bleh.colMap.get(441)); Sprite world = new Sprite(bleh.drawMap(800, 600)); while(screen.isOpen()){ for(Event event : screen.pollEvents()){ if(event.type == Event.Type.CLOSED){ screen.close(); } } screen.clear(Color.CYAN); screen.draw(world); screen.display(); } } } diff --git a/dsz/Map.java b/dsz/Map.java index f2b7764..85d340d 100644 --- a/dsz/Map.java +++ b/dsz/Map.java @@ -1,70 +1,67 @@ package dsz; import java.io.*; import java.util.ArrayList; import org.jsfml.graphics.*; public class Map { int XSize, YSize, totalSize; TextureArray textures; ArrayList<Integer> textureMap = new ArrayList<Integer>(); ArrayList<Integer> colMap = new ArrayList<Integer>(); public Map(TextureArray texts){ textures = texts; } void loadMapFile(FileReader file){ String buf, data=""; try{ BufferedReader br = new BufferedReader(file); while((buf=br.readLine()) != null){ data+=buf; } br.close(); } catch(IOException e){ System.out.println("Can't open file"); System.exit(0); } loadMap(data); } void loadMap(String data){ String[] dataArray = data.split("\\s+"); XSize = Integer.parseInt(dataArray[0]); YSize = Integer.parseInt(dataArray[1]); totalSize = XSize * YSize; int size = totalSize; - System.out.println(size); - for(int i=2;i<size+3;i++){ - //System.out.println(i); + for(int i=2;(i-2)<size;i++){ textureMap.add(Integer.parseInt(dataArray[i])); - colMap.add(Integer.parseInt(dataArray[(size-1)+i])); + colMap.add(Integer.parseInt(dataArray[(size)+i])); } } ConstTexture drawMap(int width,int height){ Sprite currentTile = new Sprite(); RenderTexture screen = new RenderTexture(); int currentSlot = 0; screen.create(width, height); screen.clear(); for(int x=0;x<XSize;x++){ for(int y=0;y<YSize;y++){ currentTile.setPosition(x*16,y*16); currentTile.setTexture(textures.tiles.get(textureMap.get(currentSlot))); - //System.out.println(textureMap.get(currentSlot)); screen.draw(currentTile); currentSlot++; } } screen.display(); return screen.getTexture(); } }
false
false
null
null
diff --git a/src/test/java/net/sourceforge/buildmonitor/monitors/BambooPropertiesTest.java b/src/test/java/net/sourceforge/buildmonitor/monitors/BambooPropertiesTest.java index 696c291..070b71f 100644 --- a/src/test/java/net/sourceforge/buildmonitor/monitors/BambooPropertiesTest.java +++ b/src/test/java/net/sourceforge/buildmonitor/monitors/BambooPropertiesTest.java @@ -1,63 +1,63 @@ /* * Copyright 2007 Sebastien Brunot (sbrunot@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sourceforge.buildmonitor.monitor; import net.sourceforge.buildmonitor.monitors.BambooProperties; import java.io.IOException; import junit.framework.TestCase; /** * Unit tests for the RssFeedReader class. * @author vegarwe * */ public class BambooPropertiesTest extends TestCase { public void testloadFromFileBase64Password() { BambooProperties bambooProperties = new BambooProperties(); try { - System.setProperty("user.home", "/home/vegarwe/devel/build-monitor/src/test/resources/base64pass"); + System.setProperty("user.home", "/home/vewe/devel/build-monitor/src/test/resources/base64pass"); bambooProperties.loadFromFile(); } catch (IOException e) {} assertEquals(bambooProperties.getPassword(), "testpassord"); } public void testloadFromFilePlaintextPassword() { BambooProperties bambooProperties = new BambooProperties(); try { - System.setProperty("user.home", "/home/vegarwe/devel/build-monitor/src/test/resources/plainpass"); + System.setProperty("user.home", "/home/vewe/devel/build-monitor/src/test/resources/plainpass"); bambooProperties.loadFromFile(); } catch (IOException e) {} assertEquals(bambooProperties.getPassword(), "testpassord"); } public void testSaveToFilePlaintextPassword() { BambooProperties bambooProperties = new BambooProperties(); try { - System.setProperty("user.home", "/home/vegarwe/devel/build-monitor/src/test/resources/plainpass"); + System.setProperty("user.home", "/home/vewe/devel/build-monitor/src/test/resources/plainpass"); bambooProperties.loadFromFile(); - System.setProperty("user.home", "/home/vegarwe/devel/build-monitor/src/test/resources/tmp"); + System.setProperty("user.home", "/home/vewe/devel/build-monitor/src/test/resources/tmp"); bambooProperties.saveToFile(); bambooProperties.loadFromFile(); } catch (IOException e) {} assertEquals(bambooProperties.getPassword(), "testpassord"); } }
false
false
null
null
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskPlanningEditor.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskPlanningEditor.java index 2534692a3..a83a84b46 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskPlanningEditor.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskPlanningEditor.java @@ -1,955 +1,957 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui.editors; import java.io.File; import java.text.DateFormat; import java.util.Calendar; import java.util.Set; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.Action; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.TextViewer; import org.eclipse.mylyn.context.core.ContextCorePlugin; import org.eclipse.mylyn.internal.tasks.core.LocalRepositoryConnector; import org.eclipse.mylyn.internal.tasks.core.LocalTask; import org.eclipse.mylyn.internal.tasks.ui.RetrieveTitleFromUrlJob; import org.eclipse.mylyn.internal.tasks.ui.TasksUiImages; import org.eclipse.mylyn.internal.tasks.ui.actions.TaskActivateAction; import org.eclipse.mylyn.internal.tasks.ui.actions.TaskDeactivateAction; import org.eclipse.mylyn.internal.tasks.ui.views.TaskListView; import org.eclipse.mylyn.monitor.core.DateUtil; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.monitor.ui.MonitorUiPlugin; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.ITaskListChangeListener; import org.eclipse.mylyn.tasks.core.TaskContainerDelta; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.AbstractTask.PriorityLevel; import org.eclipse.mylyn.tasks.ui.AbstractRepositoryConnectorUi; import org.eclipse.mylyn.tasks.ui.DatePicker; import org.eclipse.mylyn.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.tasks.ui.TasksUiUtil; import org.eclipse.mylyn.tasks.ui.editors.TaskEditor; import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput; import org.eclipse.mylyn.tasks.ui.editors.TaskFormPage; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; 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.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.IManagedForm; import org.eclipse.ui.forms.editor.FormEditor; import org.eclipse.ui.forms.events.ExpansionEvent; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.events.IExpansionListener; import org.eclipse.ui.forms.events.IHyperlinkListener; import org.eclipse.ui.forms.widgets.ExpandableComposite; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ImageHyperlink; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.ui.forms.widgets.Section; /** * @author Mik Kersten * @author Ken Sueda (initial prototype) * @author Rob Elves */ public class TaskPlanningEditor extends TaskFormPage { private static final int NOTES_MINSIZE = 100; public static final String ID = "org.eclipse.mylyn.tasks.ui.editors.planning"; private static final String CLEAR = "Clear"; private static final String LABEL_DUE = "Due:"; private static final String LABEL_SCHEDULE = "Scheduled for:"; private static final String DESCRIPTION_ESTIMATED = "Time that the task has been actively worked on in Eclipse.\n Inactivity timeout is " + MonitorUiPlugin.getDefault().getInactivityTimeout() / (60 * 1000) + " minutes."; public static final String LABEL_INCOMPLETE = "Incomplete"; public static final String LABEL_COMPLETE = "Complete"; private static final String LABEL_PLAN = "Personal Planning"; private static final String NO_TIME_ELAPSED = "0 seconds"; // private static final String LABEL_OVERVIEW = "Task Info"; private static final String LABEL_NOTES = "Notes"; private DatePicker dueDatePicker; private DatePicker datePicker; private AbstractTask task; private Composite editorComposite; protected static final String CONTEXT_MENU_ID = "#MylynPlanningEditor"; private Text pathText; private Text endDate; private ScrolledForm form; private Text summary; private Text issueReportURL; private CCombo priorityCombo; private CCombo statusCombo; private TextViewer noteEditor; private Spinner estimated; private ImageHyperlink getDescLink; private ImageHyperlink openUrlLink; private TaskEditor parentEditor = null; private ITaskListChangeListener TASK_LIST_LISTENER = new ITaskListChangeListener() { public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta taskContainerDelta : containers) { if (taskContainerDelta.getContainer() instanceof AbstractTask) { final AbstractTask updateTask = (AbstractTask) taskContainerDelta.getContainer(); if (updateTask != null && task != null && updateTask.getHandleIdentifier().equals(task.getHandleIdentifier())) { if (PlatformUI.getWorkbench() != null && !PlatformUI.getWorkbench().isClosing()) { PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() { public void run() { updateTaskData(updateTask); } }); } } } } } }; private FormToolkit toolkit; private Action activateAction; public TaskPlanningEditor(FormEditor editor) { super(editor, ID, "Planning"); TasksUiPlugin.getTaskListManager().getTaskList().addChangeListener(TASK_LIST_LISTENER); } /** public for testing */ public void updateTaskData(final AbstractTask updateTask) { if (datePicker != null && !datePicker.isDisposed()) { if (updateTask.getScheduledForDate() != null) { Calendar cal = Calendar.getInstance(); cal.setTime(updateTask.getScheduledForDate()); datePicker.setDate(cal); } else { datePicker.setDate(null); } } if (summary == null) return; if (!summary.isDisposed()) { if (!summary.getText().equals(updateTask.getSummary())) { boolean wasDirty = TaskPlanningEditor.this.isDirty; summary.setText(updateTask.getSummary()); TaskPlanningEditor.this.markDirty(wasDirty); } if (parentEditor != null) { parentEditor.changeTitle(); parentEditor.updateTitle(updateTask.getSummary()); } } if (!priorityCombo.isDisposed() && updateTask != null) { PriorityLevel level = PriorityLevel.fromString(updateTask.getPriority()); if (level != null) { int prioritySelectionIndex = priorityCombo.indexOf(level.getDescription()); priorityCombo.select(prioritySelectionIndex); } } if (!statusCombo.isDisposed()) { if (task.isCompleted()) { statusCombo.select(0); } else { statusCombo.select(1); } } if ((updateTask instanceof LocalTask) && !endDate.isDisposed()) { endDate.setText(getTaskDateString(updateTask)); } } @Override public void doSave(IProgressMonitor monitor) { if (task instanceof LocalTask) { String label = summary.getText(); // task.setDescription(label); TasksUiPlugin.getTaskListManager().getTaskList().renameTask(task, label); // TODO: refactor mutation into TaskList? task.setUrl(issueReportURL.getText()); String priorityDescription = priorityCombo.getItem(priorityCombo.getSelectionIndex()); PriorityLevel level = PriorityLevel.fromDescription(priorityDescription); if (level != null) { task.setPriority(level.toString()); } if (statusCombo.getSelectionIndex() == 0) { task.setCompleted(true); } else { task.setCompleted(false); } } String note = noteEditor.getTextWidget().getText();// notes.getText(); task.setNotes(note); task.setEstimatedTimeHours(estimated.getSelection()); if (datePicker != null && datePicker.getDate() != null) { TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, datePicker.getDate().getTime()); } else { TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, null); } if (dueDatePicker != null && dueDatePicker.getDate() != null) { TasksUiPlugin.getTaskActivityManager().setDueDate(task, dueDatePicker.getDate().getTime()); } else { TasksUiPlugin.getTaskActivityManager().setDueDate(task, null); } // if (parentEditor != null) { // parentEditor.notifyTaskChanged(); // } markDirty(false); } @Override public void doSaveAs() { // don't support saving as } @Override public boolean isDirty() { return isDirty; } @Override public boolean isSaveAsAllowed() { return false; } @Override protected void createFormContent(IManagedForm managedForm) { super.createFormContent(managedForm); TaskEditorInput taskEditorInput = (TaskEditorInput) getEditorInput(); task = taskEditorInput.getTask(); form = managedForm.getForm(); toolkit = managedForm.getToolkit(); if (task != null) { addHeaderControls(); } editorComposite = form.getBody(); GridLayout editorLayout = new GridLayout(); editorLayout.verticalSpacing = 3; editorComposite.setLayout(editorLayout); //editorComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); if (task instanceof LocalTask) { createSummarySection(editorComposite); } createPlanningSection(editorComposite); createNotesSection(editorComposite); if (summary != null && LocalRepositoryConnector.DEFAULT_SUMMARY.equals(summary.getText())) { summary.setSelection(0, summary.getText().length()); summary.setFocus(); } else if (summary != null) { summary.setFocus(); } } private void addHeaderControls() { if (parentEditor.getTopForm() != null && parentEditor.getTopForm().getToolBarManager().isEmpty()) { activateAction = new Action() { @Override public void run() { if (!task.isActive()) { setChecked(true); new TaskActivateAction().run(task); } else { setChecked(false); new TaskDeactivateAction().run(task); } } }; activateAction.setImageDescriptor(TasksUiImages.TASK_ACTIVE_CENTERED); activateAction.setToolTipText("Toggle Activation"); activateAction.setChecked(task.isActive()); parentEditor.getTopForm().getToolBarManager().add(activateAction); parentEditor.getTopForm().getToolBarManager().update(true); } // if (form.getToolBarManager() != null) { // form.getToolBarManager().add(repositoryLabelControl); // if (repositoryTask != null) { // SynchronizeEditorAction synchronizeEditorAction = new // SynchronizeEditorAction(); // synchronizeEditorAction.selectionChanged(new // StructuredSelection(this)); // form.getToolBarManager().add(synchronizeEditorAction); // } // // // Header drop down menu additions: // // form.getForm().getMenuManager().add(new // // SynchronizeSelectedAction()); // // form.getToolBarManager().update(true); // } } @Override public void setFocus() { // form.setFocus(); if (summary != null && !summary.isDisposed()) { summary.setFocus(); } } public Control getControl() { return form; } private Text addNameValueComp(Composite parent, String label, String value, int style) { Composite nameValueComp = toolkit.createComposite(parent); GridLayout layout = new GridLayout(2, false); layout.marginHeight = 3; nameValueComp.setLayout(layout); toolkit.createLabel(nameValueComp, label, SWT.NONE).setForeground( toolkit.getColors().getColor(IFormColors.TITLE)); Text text; if ((SWT.READ_ONLY & style) == SWT.READ_ONLY) { text = new Text(nameValueComp, style); toolkit.adapt(text, true, true); text.setText(value); } else { text = toolkit.createText(nameValueComp, value, style); } return text; } private void createSummarySection(Composite parent) { // Summary Composite summaryComposite = toolkit.createComposite(parent); GridLayout summaryLayout = new GridLayout(); summaryLayout.verticalSpacing = 2; summaryLayout.marginHeight = 2; summaryLayout.marginLeft = 5; summaryComposite.setLayout(summaryLayout); GridDataFactory.fillDefaults().grab(true, false).applyTo(summaryComposite); summary = toolkit.createText(summaryComposite, task.getSummary(), SWT.LEFT | SWT.FLAT); summary.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); GridDataFactory.fillDefaults().minSize(100, SWT.DEFAULT).grab(true, false).applyTo(summary); if (!(task instanceof LocalTask)) { summary.setEnabled(false); } else { summary.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { markDirty(true); } }); } toolkit.paintBordersFor(summaryComposite); Composite statusComposite = toolkit.createComposite(parent); GridLayout compLayout = new GridLayout(7, false); compLayout.verticalSpacing = 0; compLayout.horizontalSpacing = 5; compLayout.marginHeight = 3; statusComposite.setLayout(compLayout); statusComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); Composite nameValueComp = toolkit.createComposite(statusComposite); GridLayout nameValueLayout = new GridLayout(2, false); nameValueLayout.marginHeight = 3; nameValueComp.setLayout(nameValueLayout); toolkit.createLabel(nameValueComp, "Priority:").setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); - priorityCombo = new CCombo(nameValueComp, SWT.FLAT); + priorityCombo = new CCombo(nameValueComp, SWT.FLAT | SWT.READ_ONLY); + toolkit.adapt(priorityCombo, true, true); priorityCombo.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); toolkit.paintBordersFor(nameValueComp); // Populate the combo box with priority levels for (String priorityLevel : TaskListView.PRIORITY_LEVEL_DESCRIPTIONS) { priorityCombo.add(priorityLevel); } PriorityLevel level = PriorityLevel.fromString(task.getPriority()); if (level != null) { int prioritySelectionIndex = priorityCombo.indexOf(level.getDescription()); priorityCombo.select(prioritySelectionIndex); } if (!(task instanceof LocalTask)) { priorityCombo.setEnabled(false); } else { priorityCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { TaskPlanningEditor.this.markDirty(true); } }); } nameValueComp = toolkit.createComposite(statusComposite); nameValueComp.setLayout(new GridLayout(2, false)); toolkit.createLabel(nameValueComp, "Status:").setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); - statusCombo = new CCombo(nameValueComp, SWT.FLAT); + statusCombo = new CCombo(nameValueComp, SWT.FLAT | SWT.READ_ONLY); + toolkit.adapt(statusCombo, true, true); statusCombo.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); toolkit.paintBordersFor(nameValueComp); statusCombo.add(LABEL_COMPLETE); statusCombo.add(LABEL_INCOMPLETE); if (task.isCompleted()) { statusCombo.select(0); } else { statusCombo.select(1); } if (!(task instanceof LocalTask)) { statusCombo.setEnabled(false); } else { statusCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (statusCombo.getSelectionIndex() == 0) { task.setCompleted(true); } else { task.setCompleted(false); } TaskPlanningEditor.this.markDirty(true); } }); } String creationDateString = ""; try { creationDateString = DateFormat.getDateInstance(DateFormat.LONG).format(task.getCreationDate()); } catch (RuntimeException e) { StatusHandler.fail(e, "Could not format creation date", true); } addNameValueComp(statusComposite, "Created:", creationDateString, SWT.FLAT | SWT.READ_ONLY); String completionDateString = ""; if (task.isCompleted()) { completionDateString = getTaskDateString(task); } endDate = addNameValueComp(statusComposite, "Completed:", completionDateString, SWT.FLAT | SWT.READ_ONLY); // URL Composite urlComposite = toolkit.createComposite(parent); GridLayout urlLayout = new GridLayout(4, false); urlLayout.verticalSpacing = 0; urlLayout.marginHeight = 2; urlLayout.marginLeft = 5; urlComposite.setLayout(urlLayout); GridDataFactory.fillDefaults().grab(true, false).applyTo(urlComposite); Label label = toolkit.createLabel(urlComposite, "URL:"); label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); issueReportURL = toolkit.createText(urlComposite, task.getUrl(), SWT.FLAT); issueReportURL.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); if (!(task instanceof LocalTask)) { issueReportURL.setEditable(false); } else { issueReportURL.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { markDirty(true); } }); } getDescLink = toolkit.createImageHyperlink(urlComposite, SWT.NONE); getDescLink.setImage(TasksUiImages.getImage(TasksUiImages.TASK_RETRIEVE)); getDescLink.setToolTipText("Retrieve task description from URL"); getDescLink.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); setButtonStatus(); issueReportURL.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { setButtonStatus(); } public void keyReleased(KeyEvent e) { setButtonStatus(); } }); getDescLink.addHyperlinkListener(new IHyperlinkListener() { public void linkActivated(HyperlinkEvent e) { retrieveTaskDescription(issueReportURL.getText()); } public void linkEntered(HyperlinkEvent e) { } public void linkExited(HyperlinkEvent e) { } }); openUrlLink = toolkit.createImageHyperlink(urlComposite, SWT.NONE); openUrlLink.setImage(TasksUiImages.getImage(TasksUiImages.BROWSER_SMALL)); openUrlLink.setToolTipText("Open with Web Browser"); openUrlLink.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); openUrlLink.addHyperlinkListener(new IHyperlinkListener() { public void linkActivated(HyperlinkEvent e) { TasksUiUtil.openUrl(issueReportURL.getText(), false); } public void linkEntered(HyperlinkEvent e) { } public void linkExited(HyperlinkEvent e) { } }); toolkit.paintBordersFor(urlComposite); toolkit.paintBordersFor(statusComposite); } /** * Attempts to set the task pageTitle to the title from the specified url */ protected void retrieveTaskDescription(final String url) { try { RetrieveTitleFromUrlJob job = new RetrieveTitleFromUrlJob(issueReportURL.getText()) { @Override protected void setTitle(final String pageTitle) { summary.setText(pageTitle); TaskPlanningEditor.this.markDirty(true); } }; job.schedule(); } catch (RuntimeException e) { StatusHandler.fail(e, "could not open task web page", false); } } /** * Sets the Get Description button enabled or not depending on whether there is a URL specified */ protected void setButtonStatus() { String url = issueReportURL.getText(); if (url.length() > 10 && (url.startsWith("http://") || url.startsWith("https://"))) { // String defaultPrefix = // ContextCorePlugin.getDefault().getPreferenceStore().getString( // TaskListPreferenceConstants.DEFAULT_URL_PREFIX); // if (url.equals(defaultPrefix)) { // getDescButton.setEnabled(false); // } else { getDescLink.setEnabled(true); // } } else { getDescLink.setEnabled(false); } } private void createPlanningSection(Composite parent) { Section section = toolkit.createSection(parent, ExpandableComposite.TITLE_BAR | Section.TWISTIE); section.setText(LABEL_PLAN); section.setLayout(new GridLayout()); section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); section.setExpanded(true); section.addExpansionListener(new IExpansionListener() { public void expansionStateChanging(ExpansionEvent e) { form.reflow(true); } public void expansionStateChanged(ExpansionEvent e) { form.reflow(true); } }); Composite sectionClient = toolkit.createComposite(section); section.setClient(sectionClient); GridLayout layout = new GridLayout(); layout.numColumns = 3; layout.horizontalSpacing = 15; layout.makeColumnsEqualWidth = false; sectionClient.setLayout(layout); GridData clientDataLayout = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); sectionClient.setLayoutData(clientDataLayout); Composite nameValueComp = makeComposite(sectionClient, 3); Label label = toolkit.createLabel(nameValueComp, LABEL_SCHEDULE); label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); datePicker = new DatePicker(nameValueComp, SWT.FLAT, DatePicker.LABEL_CHOOSE); Calendar calendar = Calendar.getInstance(); if (task.getScheduledForDate() != null) { calendar.setTime(task.getScheduledForDate()); datePicker.setDate(calendar); } datePicker.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE)); datePicker.addPickerSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent arg0) { task.setReminded(false); TaskPlanningEditor.this.markDirty(true); } public void widgetDefaultSelected(SelectionEvent arg0) { // ignore } }); datePicker.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); toolkit.adapt(datePicker, true, true); toolkit.paintBordersFor(nameValueComp); ImageHyperlink clearScheduledDate = toolkit.createImageHyperlink(nameValueComp, SWT.NONE); clearScheduledDate.setImage(TasksUiImages.getImage(TasksUiImages.REMOVE)); clearScheduledDate.setToolTipText(CLEAR); clearScheduledDate.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { datePicker.setDate(null); task.setReminded(false); TaskPlanningEditor.this.markDirty(true); } }); nameValueComp = makeComposite(sectionClient, 3); label = toolkit.createLabel(nameValueComp, LABEL_DUE); label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); dueDatePicker = new DatePicker(nameValueComp, SWT.FLAT, DatePicker.LABEL_CHOOSE); calendar = Calendar.getInstance(); if (task.getDueDate() != null) { calendar.setTime(task.getDueDate()); dueDatePicker.setDate(calendar); } dueDatePicker.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WHITE)); dueDatePicker.addPickerSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { TaskPlanningEditor.this.markDirty(true); } }); dueDatePicker.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); toolkit.adapt(dueDatePicker, true, true); toolkit.paintBordersFor(nameValueComp); ImageHyperlink clearDueDate = toolkit.createImageHyperlink(nameValueComp, SWT.NONE); clearDueDate.setImage(TasksUiImages.getImage(TasksUiImages.REMOVE)); clearDueDate.setToolTipText(CLEAR); clearDueDate.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { dueDatePicker.setDate(null); TaskPlanningEditor.this.markDirty(true); } }); if (task != null && !(task instanceof LocalTask)) { AbstractRepositoryConnectorUi connector = TasksUiPlugin.getConnectorUi(task.getConnectorKind()); if (connector != null && connector.supportsDueDates(task)) { dueDatePicker.setEnabled(false); clearDueDate.setEnabled(false); } } // Estimated time nameValueComp = makeComposite(sectionClient, 3); label = toolkit.createLabel(nameValueComp, "Estimated hours:"); label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); estimated = new Spinner(nameValueComp, SWT.FLAT); toolkit.adapt(estimated, true, true); estimated.setSelection(task.getEstimateTimeHours()); estimated.setDigits(0); estimated.setMaximum(100); estimated.setMinimum(0); estimated.setIncrement(1); estimated.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { TaskPlanningEditor.this.markDirty(true); } }); estimated.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); toolkit.paintBordersFor(nameValueComp); GridData estimatedDataLayout = new GridData(); estimatedDataLayout.widthHint = 30; estimated.setLayoutData(estimatedDataLayout); ImageHyperlink clearEstimated = toolkit.createImageHyperlink(nameValueComp, SWT.NONE); clearEstimated.setImage(TasksUiImages.getImage(TasksUiImages.REMOVE)); clearEstimated.setToolTipText(CLEAR); clearEstimated.addHyperlinkListener(new HyperlinkAdapter() { @Override public void linkActivated(HyperlinkEvent e) { estimated.setSelection(0); TaskPlanningEditor.this.markDirty(true); } }); // Active Time nameValueComp = makeComposite(sectionClient, 3); // GridDataFactory.fillDefaults().span(2, 1).align(SWT.LEFT, // SWT.DEFAULT).applyTo(nameValueComp); label = toolkit.createLabel(nameValueComp, "Active:"); label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE)); label.setToolTipText(DESCRIPTION_ESTIMATED); String elapsedTimeString = NO_TIME_ELAPSED; try { elapsedTimeString = DateUtil.getFormattedDuration(TasksUiPlugin.getTaskActivityManager().getElapsedTime( task), true); if (elapsedTimeString.equals("")) elapsedTimeString = NO_TIME_ELAPSED; } catch (RuntimeException e) { StatusHandler.fail(e, "Could not format elapsed time", true); } final Text elapsedTimeText = new Text(nameValueComp, SWT.READ_ONLY | SWT.FLAT); elapsedTimeText.setText(elapsedTimeString); GridData td = new GridData(GridData.FILL_HORIZONTAL); td.widthHint = 120; elapsedTimeText.setLayoutData(td); elapsedTimeText.setEditable(false); // Refresh Button Button timeRefresh = toolkit.createButton(nameValueComp, "Refresh", SWT.PUSH | SWT.CENTER); // timeRefresh.setImage(TaskListImages.getImage(TaskListImages.REFRESH)); timeRefresh.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { String elapsedTimeString = NO_TIME_ELAPSED; try { elapsedTimeString = DateUtil.getFormattedDuration(TasksUiPlugin.getTaskActivityManager() .getElapsedTime(task), true); if (elapsedTimeString.equals("")) { elapsedTimeString = NO_TIME_ELAPSED; } } catch (RuntimeException e1) { StatusHandler.fail(e1, "Could not format elapsed time", true); } elapsedTimeText.setText(elapsedTimeString); } }); toolkit.paintBordersFor(sectionClient); } private Composite makeComposite(Composite parent, int col) { Composite nameValueComp = toolkit.createComposite(parent); GridLayout layout = new GridLayout(3, false); layout.marginHeight = 3; nameValueComp.setLayout(layout); return nameValueComp; } private void createNotesSection(Composite parent) { Section section = toolkit.createSection(parent, ExpandableComposite.TITLE_BAR); section.setText(LABEL_NOTES); section.setExpanded(true); section.setLayout(new GridLayout()); section.setLayoutData(new GridData(GridData.FILL_BOTH)); // section.addExpansionListener(new IExpansionListener() { // public void expansionStateChanging(ExpansionEvent e) { // form.reflow(true); // } // // public void expansionStateChanged(ExpansionEvent e) { // form.reflow(true); // } // }); Composite container = toolkit.createComposite(section); section.setClient(container); container.setLayout(new GridLayout()); GridData notesData = new GridData(GridData.FILL_BOTH); notesData.grabExcessVerticalSpace = true; container.setLayoutData(notesData); TaskRepository repository = null; if (task != null && !(task instanceof LocalTask)) { AbstractTask repositoryTask = task; repository = TasksUiPlugin.getRepositoryManager().getRepository(repositoryTask.getConnectorKind(), repositoryTask.getRepositoryUrl()); } noteEditor = addTextEditor(repository, container, task.getNotes(), true, SWT.FLAT | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); noteEditor.getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); GridDataFactory.fillDefaults().minSize(SWT.DEFAULT, NOTES_MINSIZE).grab(true, true).applyTo( noteEditor.getControl()); noteEditor.getControl().setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); noteEditor.setEditable(true); noteEditor.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { if (!task.getNotes().equals(noteEditor.getTextWidget().getText())) { markDirty(true); } } }); // commentViewer.addSelectionChangedListener(new // ISelectionChangedListener() { // // public void selectionChanged(SelectionChangedEvent event) { // getSite().getSelectionProvider().setSelection(commentViewer.getSelection()); // // }}); toolkit.paintBordersFor(container); } private String getTaskDateString(AbstractTask task) { if (task == null) return ""; if (task.getCompletionDate() == null) return ""; String completionDateString = ""; try { completionDateString = DateFormat.getDateInstance(DateFormat.LONG).format(task.getCompletionDate()); } catch (RuntimeException e) { StatusHandler.fail(e, "Could not format date", true); return completionDateString; } return completionDateString; } // TODO: unused, delete? void createResourcesSection(Composite parent) { Section section = toolkit.createSection(parent, ExpandableComposite.TITLE_BAR | Section.TWISTIE); section.setText("Resources"); section.setLayout(new GridLayout()); section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); section.addExpansionListener(new IExpansionListener() { public void expansionStateChanging(ExpansionEvent e) { form.reflow(true); } public void expansionStateChanged(ExpansionEvent e) { form.reflow(true); } }); Composite container = toolkit.createComposite(section); section.setClient(container); GridLayout layout = new GridLayout(); layout.numColumns = 2; container.setLayout(layout); container.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); toolkit.createLabel(container, "Task context file:"); File contextFile = ContextCorePlugin.getContextManager().getFileForContext(task.getHandleIdentifier()); if (contextFile != null) { pathText = toolkit.createText(container, contextFile.getAbsolutePath(), SWT.NONE); pathText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); GridDataFactory.fillDefaults().hint(400, SWT.DEFAULT).applyTo(pathText); pathText.setEditable(false); pathText.setEnabled(true); } toolkit.paintBordersFor(container); } public void setParentEditor(TaskEditor parentEditor) { this.parentEditor = parentEditor; } @Override public void dispose() { TasksUiPlugin.getTaskListManager().getTaskList().removeChangeListener(TASK_LIST_LISTENER); } @Override public String toString() { return "(info editor for task: " + task + ")"; } /** for testing - should cause dirty state */ public void setNotes(String notes) { this.noteEditor.getTextWidget().setText(notes); } /** for testing - should cause dirty state */ public void setDescription(String desc) { this.summary.setText(desc); } /** for testing */ public String getDescription() { return this.summary.getText(); } /** for testing */ public String getFormTitle() { return form.getText(); } }
false
false
null
null
diff --git a/src/main/java/zombiefu/creature/Monster.java b/src/main/java/zombiefu/creature/Monster.java index 586078a..9239434 100755 --- a/src/main/java/zombiefu/creature/Monster.java +++ b/src/main/java/zombiefu/creature/Monster.java @@ -1,133 +1,133 @@ package zombiefu.creature; import jade.core.Actor; import zombiefu.items.Weapon; import jade.util.datatype.ColoredChar; import jade.util.datatype.Coordinate; import jade.util.datatype.Direction; import java.util.List; import java.util.Set; import zombiefu.exception.NoPlaceToMoveException; import zombiefu.exception.WeaponHasNoMunitionException; import zombiefu.exception.TargetNotFoundException; import zombiefu.exception.NoDirectionGivenException; import zombiefu.exception.NoEnemyHitException; import zombiefu.exception.TargetIsNotInThisWorldException; import zombiefu.fight.Attack; import zombiefu.fight.ProjectileBresenham; import zombiefu.items.WeaponType; import zombiefu.ki.CircularHabitat; import zombiefu.player.Player; import zombiefu.util.ZombieGame; import zombiefu.util.ZombieTools; /** * Creature, which attacks the player. */ public class Monster extends NonPlayer { private Weapon waffe; protected int ectsYield; private Set<Actor> dropOnDeath; public Monster(ColoredChar face, String name, AttributeSet attSet, Weapon waffe, int ectsYield, Set<Actor> dropOnDeath, double maxDistance, int chaseDistance) { super(face, name, attSet, maxDistance); this.waffe = waffe; this.ectsYield = ectsYield; this.dropOnDeath = dropOnDeath; this.sichtweite = chaseDistance; } private boolean canHitTarget(Coordinate c) { if (x() != c.x() && y() != c.y()) { // Nicht in einer Linie. return false; } List<Coordinate> path = new ProjectileBresenham(getActiveWeapon().getRange()).getPartialPath(world(), pos(), c); - return path.get(path.size() - 1).equals(c); + return path.isEmpty() ? false: path.get(path.size() - 1).equals(c); } @Override protected void pleaseAct() { if (habitat == null) { habitat = new CircularHabitat(this, maxDistance); } try { Coordinate pos = getPlayerPosition(); if (positionIsVisible(pos)) { if (getActiveWeapon().getTyp().isRanged() && canHitTarget(pos)) { System.out.println("hier bin ich"); try { new Attack(this, pos().directionTo(pos)).perform(); return; } catch (NoEnemyHitException ex) { ex.close(); return; } } if (getActiveWeapon().getTyp() == WeaponType.UMKREIS && pos().distance(getPlayerPosition()) <= getActiveWeapon().getBlastRadius()) { try { new Attack(this, null).perform(); return; } catch (NoEnemyHitException ex) { ex.close(); return; } } // Gegner nicht aus der Ferne angreifen, also in seine Richtung. moveToCoordinate(getPlayerPosition()); return; } } catch (TargetIsNotInThisWorldException | TargetNotFoundException | WeaponHasNoMunitionException ex) { } try { moveRandomly(); } catch (NoPlaceToMoveException ex) { ZombieTools.log(getName() + ": Cannot move - doing nothing"); } } @Override public Weapon getActiveWeapon() { return waffe; } @Override public void kill(Creature killer) { for (Actor it : dropOnDeath) { world().addActor(it, pos()); } if (ZombieGame.getPlayer() == killer) { ZombieGame.getPlayer().giveECTS(ectsYield); } expire(); ZombieGame.newMessage(killer.getName() + " hat " + getName() + " getötet."); } @Override protected Direction getAttackDirection() throws NoDirectionGivenException { // TODO: Überprüfen, ob Gegner wirklich in einer Linie ist try { return getDirectionTo(getPlayerPosition()); } catch (TargetNotFoundException | TargetIsNotInThisWorldException e) { throw new NoDirectionGivenException(); } } @Override protected boolean isEnemy(Creature enemy) { return enemy instanceof Player; } @Override public boolean hasUnlimitedMunition() { return true; } } diff --git a/src/main/java/zombiefu/player/Discipline.java b/src/main/java/zombiefu/player/Discipline.java index 08482b2..8da70ac 100644 --- a/src/main/java/zombiefu/player/Discipline.java +++ b/src/main/java/zombiefu/player/Discipline.java @@ -1,59 +1,59 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package zombiefu.player; import java.util.HashMap; /** * * @author tomas */ public enum Discipline { //HP, a, v, geschick, geld*100, Bonusitems (Faust + ein Wasser hat jeder sowieso) - POLITICAL_SCIENCE(100, 5, 6, 7, 500, "weapon(Totquatschen)"), // Was anderes + POLITICAL_SCIENCE(100, 5, 6, 7, 500, "weapon(Morgenstern)"), // Was anderes COMPUTER_SCIENCE(100, 5, 6, 7, 500, "weapon(Laptop) food(Mate)x4"), MEDICINE(130, 4, 6, 6, 1000, "weapon(Narkose) food(Anabolika)x1"), PHILOSOPHY(110, 6, 6, 6, 20, "weapon(Totquatschen)"), PHYSICS(100, 7, 7, 5, 500, "weapon(Induktionskanone)"), BUSINESS(100, 3, 3, 3, 8000, "weapon(Besen) food(MensaAktion)"), CHEMISTRY(100, 8, 6, 5, 500, "weapon(Saeurebombe)"), SPORTS(110, 9, 5, 4, 500, "weapon(RoundhouseKick) food(Anabolika)x2"), MATHEMATICS(120, 6, 4, 7, 500, "food(Kaffee)x5"); // Fehlt private HashMap<Attribute, Integer> baseAttributes; private String baseItems; private int baseMoney; private Discipline(int hp, int att, int def, int dex, int money, String items) { baseMoney = money; baseItems = items; baseAttributes = new HashMap<>(); baseAttributes.put(Attribute.MAXHP, hp); baseAttributes.put(Attribute.ATTACK, att); baseAttributes.put(Attribute.DEFENSE, def); baseAttributes.put(Attribute.DEXTERITY, dex); } public static Discipline getTypeFromString(String string) { for (Discipline d : Discipline.values()) { if (d.toString().equals(string)) { return d; } } throw new IllegalArgumentException("Ungültige Discipline-Name: " + string); } public int getBaseAttribute(Attribute att) { return baseAttributes.get(att); } public String getItems() { return baseItems; } public int getMoney() { return baseMoney; } }
false
false
null
null
diff --git a/web/src/main/java/org/eurekastreams/web/client/ui/common/stream/FollowDialogContent.java b/web/src/main/java/org/eurekastreams/web/client/ui/common/stream/FollowDialogContent.java index a01133631..e4168ebba 100644 --- a/web/src/main/java/org/eurekastreams/web/client/ui/common/stream/FollowDialogContent.java +++ b/web/src/main/java/org/eurekastreams/web/client/ui/common/stream/FollowDialogContent.java @@ -1,188 +1,188 @@ /* * Copyright (c) 2009-2011 Lockheed Martin Corporation * * 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.eurekastreams.web.client.ui.common.stream; import org.eurekastreams.web.client.model.BaseActivitySubscriptionModel; import org.eurekastreams.web.client.model.GadgetModel; import org.eurekastreams.web.client.model.StreamBookmarksModel; import org.eurekastreams.web.client.model.requests.AddGadgetToStartPageRequest; import org.eurekastreams.web.client.ui.common.dialog.BaseDialogContent; import org.eurekastreams.web.client.ui.pages.master.StaticResourceBundle; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; /** * Dialog content for creating or editing a stream view. */ public class FollowDialogContent extends BaseDialogContent { /** * Stream to URL transformer. * */ private static final StreamToUrlTransformer STREAM_URL_TRANSFORMER = new StreamToUrlTransformer(); /** * Container flow panel. */ private final FlowPanel container = new FlowPanel(); /** * Main flow panel. */ private final FlowPanel body = new FlowPanel(); /** * Tips flow panel. */ private final FlowPanel tips = new FlowPanel(); /** * Default constructor. - * + * * @param inStreamName * the stream name. * @param streamRequest * the stream request. * @param inStreamId * the stream id. * @param inSubscribeModel * Model for subscribing to activity on the stream. * @param inEntityUniqueId * Unique ID of entity owning the stream. */ public FollowDialogContent(final String inStreamName, final String streamRequest, final Long inStreamId, final BaseActivitySubscriptionModel inSubscribeModel, final String inEntityUniqueId) { Label saveButton = new Label(""); Label closeButton = new Label("No Thanks"); closeButton.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { close(); } }); body.add(new Label("You are now following the:")); Label streamTitle = new Label(inStreamName + " Stream"); streamTitle.addStyleName(StaticResourceBundle.INSTANCE.coreCss().title()); body.add(streamTitle); FlowPanel options = new FlowPanel(); Label optionsText = new Label("Below are additional ways to subscribe:"); options.add(optionsText); final CheckBox addToStartPage = new CheckBox("Add this Stream to my Start Page"); final CheckBox bookmarkStream = new CheckBox("Bookmark this stream"); final CheckBox notifyViaEmail = new CheckBox("Notify me via Email"); saveButton.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { if (addToStartPage.getValue()) { GadgetModel.getInstance().insert( new AddGadgetToStartPageRequest("{d7a58391-5375-4c76-b5fc-a431c42a7555}", null, STREAM_URL_TRANSFORMER.getUrl(null, streamRequest))); } if (bookmarkStream.getValue()) { StreamBookmarksModel.getInstance().insert(inStreamId); } if (notifyViaEmail.getValue()) { inSubscribeModel.insert(inEntityUniqueId); } close(); } }); options.add(addToStartPage); options.add(bookmarkStream); options.add(notifyViaEmail); body.add(options); FlowPanel buttonPanel = new FlowPanel(); buttonPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().followDialogButtonPanel()); saveButton.addStyleName(StaticResourceBundle.INSTANCE.coreCss().saveChangesButton()); buttonPanel.add(saveButton); buttonPanel.add(closeButton); body.add(buttonPanel); container.add(body); Label tipsTitle = new Label("Tips"); tips.add(tipsTitle); tips.add(new Label("These options allow you to control over how to access the activity of this stream.")); tips.add(new Label( - "Don't worry, these selections are not permantent. You can always change them in the future.")); + "Don't worry, these selections are not permanent. You can always change them in the future.")); container.add(tips); body.addStyleName(StaticResourceBundle.INSTANCE.coreCss().followDialogBody()); tips.addStyleName(StaticResourceBundle.INSTANCE.coreCss().followDialogTips()); } /** * Gets the body panel. * * @return the body. */ public Widget getBody() { return container; } /** * Gets the CSS name. * * @return the class. */ @Override public String getCssName() { return StaticResourceBundle.INSTANCE.coreCss().followDialog(); } /** * Gets the title. * * @return the title. */ public String getTitle() { return "Subscribe"; } }
false
false
null
null
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/CVSDateFormatter.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/CVSDateFormatter.java index fbcca8608..a9a31aad8 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/CVSDateFormatter.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/util/CVSDateFormatter.java @@ -1,91 +1,106 @@ /******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials + * 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.team.internal.ccvs.core.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * Utility class for converting timestamps used in Entry file lines. The format - * required in the Entry file is ISO C asctime() function (Sun Apr 7 01:29:26 1996). + * required in the Entry file is ISO C asctime() function (Sun Apr 7 01:29:26 1996). * <p> * To be compatible with asctime(), the day field in the entryline format is * padded with a space and not a zero. Most other CVS clients use string comparison * for timestamps based on the result of the C function asctime(). * </p> */ public class CVSDateFormatter { - private static final String ENTRYLINE_FORMAT = "E MMM d HH:mm:ss yyyy"; //$NON-NLS-1$ + private static final String ENTRYLINE_FORMAT = "E MMM dd HH:mm:ss yyyy"; //$NON-NLS-1$ private static final String SERVER_FORMAT = "dd MMM yyyy HH:mm:ss";//$NON-NLS-1$ + private static final int ENTRYLINE_TENS_DAY_OFFSET = 8; private static final SimpleDateFormat serverFormat = new SimpleDateFormat(SERVER_FORMAT, Locale.US); private static SimpleDateFormat entryLineFormat = new SimpleDateFormat(ENTRYLINE_FORMAT, Locale.US); static { entryLineFormat.setTimeZone(TimeZone.getTimeZone("GMT")); //$NON-NLS-1$ } static synchronized public Date serverStampToDate(String text) throws ParseException { serverFormat.setTimeZone(getTimeZone(text)); Date date = serverFormat.parse(text); return date; } static synchronized public String dateToServerStamp(Date date) { serverFormat.setTimeZone(TimeZone.getTimeZone("GMT"));//$NON-NLS-1$ return serverFormat.format(date) + " -0000"; //$NON-NLS-1$ } - static public Date entryLineToDate(String text) throws ParseException { + static synchronized public Date entryLineToDate(String text) throws ParseException { + try { + if (text.charAt(ENTRYLINE_TENS_DAY_OFFSET) == ' ') { + StringBuffer buf = new StringBuffer(text); + buf.setCharAt(ENTRYLINE_TENS_DAY_OFFSET, '0'); + text = buf.toString(); + } + } catch (StringIndexOutOfBoundsException e) { + throw new ParseException(e.getMessage(), ENTRYLINE_TENS_DAY_OFFSET); + } return entryLineFormat.parse(text); } - static public String dateToEntryLine(Date date) { - return entryLineFormat.format(date); + static synchronized public String dateToEntryLine(Date date) { + if (date == null) return ""; //$NON-NLS-1$ + String passOne = entryLineFormat.format(date); + if (passOne.charAt(ENTRYLINE_TENS_DAY_OFFSET) != '0') return passOne; + StringBuffer passTwo = new StringBuffer(passOne); + passTwo.setCharAt(ENTRYLINE_TENS_DAY_OFFSET, ' '); + return passTwo.toString(); } static synchronized public String dateToNotifyServer(Date date) { serverFormat.setTimeZone(TimeZone.getTimeZone("GMT"));//$NON-NLS-1$ return serverFormat.format(date) + " GMT"; //$NON-NLS-1$ } /* * Converts timezone text from date string from CVS server and * returns a timezone representing the received timezone. * Timezone string is of the following format: [-|+]MMSS */ static private TimeZone getTimeZone(String dateFromServer) { if (dateFromServer.lastIndexOf("0000") != -1) //$NON-NLS-1$ return TimeZone.getTimeZone("GMT");//$NON-NLS-1$ String tz = null; StringBuffer resultTz = new StringBuffer("GMT");//$NON-NLS-1$ if (dateFromServer.indexOf("-") != -1) {//$NON-NLS-1$ resultTz.append("-");//$NON-NLS-1$ tz = dateFromServer.substring(dateFromServer.indexOf("-"));//$NON-NLS-1$ } else if (dateFromServer.indexOf("+") != -1) {//$NON-NLS-1$ resultTz.append('+'); tz = dateFromServer.substring(dateFromServer.indexOf("+"));//$NON-NLS-1$ } try { if(tz!=null) { resultTz.append(tz.substring(1, 3) /*hours*/ + ":" + tz.substring(3, 5) /*minutes*/);//$NON-NLS-1$ return TimeZone.getTimeZone(resultTz.toString()); } } catch(IndexOutOfBoundsException e) { return TimeZone.getTimeZone("GMT");//$NON-NLS-1$ } return TimeZone.getTimeZone("GMT");//$NON-NLS-1$ } }
false
false
null
null
diff --git a/src/fi/mikuz/boarder/gui/ColorChanger.java b/src/fi/mikuz/boarder/gui/ColorChanger.java index f68d705..92d63d8 100644 --- a/src/fi/mikuz/boarder/gui/ColorChanger.java +++ b/src/fi/mikuz/boarder/gui/ColorChanger.java @@ -1,306 +1,308 @@ /* ========================================================================= * * Boarder * * http://boarder.mikuz.org/ * * ========================================================================= * * Copyright (C) 2013 Boarder * * * * 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 fi.mikuz.boarder.gui; +import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.media.AudioManager; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import android.widget.Toast; import com.thoughtworks.xstream.XStream; import fi.mikuz.boarder.R; import fi.mikuz.boarder.app.BoarderActivity; import fi.mikuz.boarder.component.soundboard.GraphicalSound; import fi.mikuz.boarder.component.soundboard.GraphicalSoundboard; import fi.mikuz.boarder.util.XStreamUtil; import fi.mikuz.boarder.util.editor.SoundNameDrawing; public class ColorChanger extends BoarderActivity implements OnSeekBarChangeListener, ColorPickerDialog.OnColorChangedListener { private String TAG = "ColorChanger"; private String mParent; private GraphicalSound mSound; private GraphicalSoundboard mGsb; private boolean mChangingSoundColor = true; private TextView mAlphaValueText, mRedValueText, mGreenValueText, mBlueValueText; private SeekBar alphaBar, redBar, greenBar, blueBar; private View mPreview; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setVolumeControlStream(AudioManager.STREAM_MUSIC); Bundle extras = getIntent().getExtras(); mParent = extras.getString("parentKey"); if (mParent.equals("changeBackgroundColor")) mChangingSoundColor = false; XStream xstream = XStreamUtil.graphicalBoardXStream(); if (mChangingSoundColor) mSound = (GraphicalSound) xstream.fromXML(extras.getString(XStreamUtil.SOUND_KEY)); mGsb = (GraphicalSoundboard) xstream.fromXML(extras.getString(XStreamUtil.SOUNDBOARD_KEY)); LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.color_changer, (ViewGroup) findViewById(R.id.root)); mPreview = layout.findViewById(R.id.preview); mAlphaValueText = (TextView) layout.findViewById(R.id.alphaValueText); mRedValueText = (TextView) layout.findViewById(R.id.redValueText); mGreenValueText = (TextView) layout.findViewById(R.id.greenValueText); mBlueValueText = (TextView) layout.findViewById(R.id.blueValueText); alphaBar = (SeekBar) layout.findViewById(R.id.alphaBar); redBar = (SeekBar) layout.findViewById(R.id.redBar); greenBar = (SeekBar) layout.findViewById(R.id.greenBar); blueBar = (SeekBar) layout.findViewById(R.id.blueBar); alphaBar.setOnSeekBarChangeListener(this); redBar.setOnSeekBarChangeListener(this); greenBar.setOnSeekBarChangeListener(this); blueBar.setOnSeekBarChangeListener(this); int initialColor = 0; if (mParent.equals("changeNameColor")) { initialColor = Integer.valueOf(mSound.getNameTextColor()); } else if (mParent.equals("changeinnerPaintColor")) { initialColor = Integer.valueOf(mSound.getNameFrameInnerColor()); } else if (mParent.equals("changeBorderPaintColor")) { initialColor = Integer.valueOf(mSound.getNameFrameBorderColor()); } else if (mParent.equals("changeBackgroundColor")) { initialColor = Integer.valueOf(mGsb.getBackgroundColor()); } alphaBar.setProgress(Color.alpha(initialColor)); redBar.setProgress(Color.red(initialColor)); greenBar.setProgress(Color.green(initialColor)); blueBar.setProgress(Color.blue(initialColor)); setContentView(layout); ViewTreeObserver vto = mPreview.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (mChangingSoundColor) setNamePreviewPosition(); drawPreview(); } }); } @Override public void colorChanged(int color) { redBar.setProgress(Color.red(color)); greenBar.setProgress(Color.green(color)); blueBar.setProgress(Color.blue(color)); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.color_changer_bottom, menu); if (!mChangingSoundColor) { menu.setGroupVisible(R.id.copy, false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_pick_color: if (mParent.equals("changeNameColor")) { Dialog colorDialog = new ColorPickerDialog(this, this, Integer.valueOf(mSound.getNameTextColor())); colorDialog.show(); } else if (mParent.equals("changeinnerPaintColor")) { Dialog colorDialog = new ColorPickerDialog(this, this, Integer.valueOf(mSound.getNameFrameInnerColor())); colorDialog.show(); } else if (mParent.equals("changeBorderPaintColor")) { Dialog colorDialog = new ColorPickerDialog(this, this, Integer.valueOf(mSound.getNameFrameBorderColor())); colorDialog.show(); } else if (mParent.equals("changeBackgroundColor")) { Dialog colorDialog = new ColorPickerDialog(this, this, Integer.valueOf(mGsb.getBackgroundColor())); colorDialog.show(); } return true; case R.id.menu_save_color: Bundle bundle = new Bundle(); bundle.putBoolean("copyKey", false); bundle.putInt("colorKey", Color.argb(alphaBar.getProgress(), redBar.getProgress(), greenBar.getProgress(), blueBar.getProgress())); Intent intent = new Intent(); intent.putExtras(bundle); setResult(RESULT_OK, intent); finish(); return true; case R.id.menu_cancel_color: finish(); return true; case R.id.menu_copy_color: Toast.makeText(getApplicationContext(), "Select a sound to copy", Toast.LENGTH_LONG).show(); Bundle copyBundle = new Bundle(); copyBundle.putBoolean("copyKey", true); Intent copyIntent = new Intent(); copyIntent.putExtras(copyBundle); setResult(RESULT_OK, copyIntent); finish(); return true; default: return super.onOptionsItemSelected(item); } } public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { update(); } @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) {} private void update() { String alphaValue = Float.toString(alphaBar.getProgress()); mAlphaValueText.setText(alphaValue.substring(0, alphaValue.indexOf('.'))); String redValue = Float.toString(redBar.getProgress()); mRedValueText.setText(redValue.substring(0, redValue.indexOf('.'))); String greenValue = Float.toString(greenBar.getProgress()); mGreenValueText.setText(greenValue.substring(0, greenValue.indexOf('.'))); String blueValue = Float.toString(blueBar.getProgress()); mBlueValueText.setText(blueValue.substring(0, blueValue.indexOf('.'))); if (mParent.equals("changeNameColor")) { mSound.setNameTextColor(alphaBar.getProgress(), redBar.getProgress(), greenBar.getProgress(), blueBar.getProgress()); } else if (mParent.equals("changeinnerPaintColor")) { mSound.setNameFrameInnerColor(alphaBar.getProgress(), redBar.getProgress(), greenBar.getProgress(), blueBar.getProgress()); } else if (mParent.equals("changeBorderPaintColor")) { mSound.setNameFrameBorderColor(alphaBar.getProgress(), redBar.getProgress(), greenBar.getProgress(), blueBar.getProgress()); } else if (mParent.equals("changeBackgroundColor")) { mGsb.setBackgroundColor(alphaBar.getProgress(), redBar.getProgress(), greenBar.getProgress(), blueBar.getProgress()); } drawPreview(); } private void setNamePreviewPosition() { SoundNameDrawing soundNameDrawing = new SoundNameDrawing(mSound); RectF nameFrameRect = soundNameDrawing.getNameFrameRect(); float padding = 10; if (nameFrameRect.width()+padding > (float) mPreview.getWidth()) { float xScale = (float) mPreview.getWidth()/nameFrameRect.width(); mSound.setNameSize(mSound.getNameSize()*xScale-padding*xScale); soundNameDrawing = new SoundNameDrawing(mSound); nameFrameRect = soundNameDrawing.getNameFrameRect(); } if (nameFrameRect.height()+padding > (float) mPreview.getHeight()) { float yScale = (float) mPreview.getHeight()/nameFrameRect.height(); mSound.setNameSize(mSound.getNameSize()*yScale-padding*yScale); soundNameDrawing = new SoundNameDrawing(mSound); nameFrameRect = soundNameDrawing.getNameFrameRect(); } mSound.setNameFrameX((float) mPreview.getWidth()/2-nameFrameRect.width()/2); mSound.setNameFrameY(0); } + @SuppressLint("WrongCall") private void drawPreview() { if (mPreview.getWidth() == 0 || mPreview.getHeight() == 0) { Log.d(TAG, "Waiting for layout to initialize"); } else { Bitmap bitmap = Bitmap.createBitmap(mPreview.getWidth(), mPreview.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); new PreviewDrawer(this).onDraw(canvas); mPreview.setBackgroundDrawable(new BitmapDrawable(getResources(), bitmap)); } } public class PreviewDrawer extends SurfaceView { public PreviewDrawer(Context context) { super(context); } @Override public void onDraw(Canvas canvas) { canvas.drawColor(mGsb.getBackgroundColor()); if (mChangingSoundColor) { float NAME_DRAWING_SCALE = SoundNameDrawing.NAME_DRAWING_SCALE; canvas.scale(1/NAME_DRAWING_SCALE, 1/NAME_DRAWING_SCALE); SoundNameDrawing soundNameDrawing = new SoundNameDrawing(mSound); Paint nameTextPaint = soundNameDrawing.getBigCanvasNameTextPaint(); Paint borderPaint = soundNameDrawing.getBorderPaint(); Paint innerPaint = soundNameDrawing.getInnerPaint(); RectF bigCanvasNameFrameRect = soundNameDrawing.getBigCanvasNameFrameRect(); canvas.drawRoundRect(bigCanvasNameFrameRect, 2*NAME_DRAWING_SCALE, 2*NAME_DRAWING_SCALE, innerPaint); canvas.drawRoundRect(bigCanvasNameFrameRect, 2*NAME_DRAWING_SCALE, 2*NAME_DRAWING_SCALE, borderPaint); int i = 0; for (String row : mSound.getName().split("\n")) { canvas.drawText(row, (mSound.getNameFrameX()+2)*NAME_DRAWING_SCALE, mSound.getNameFrameY()*NAME_DRAWING_SCALE+(i+1)*mSound.getNameSize()*NAME_DRAWING_SCALE, nameTextPaint); i++; } canvas.scale(NAME_DRAWING_SCALE, NAME_DRAWING_SCALE); } } } }
false
false
null
null
diff --git a/hazelcast/src/main/java/com/hazelcast/impl/Entries.java b/hazelcast/src/main/java/com/hazelcast/impl/Entries.java index db3d578a..58efc18e 100644 --- a/hazelcast/src/main/java/com/hazelcast/impl/Entries.java +++ b/hazelcast/src/main/java/com/hazelcast/impl/Entries.java @@ -1,219 +1,217 @@ /* * Copyright (c) 2008-2012, Hazel Bilisim Ltd. 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; import com.hazelcast.core.Instance; import com.hazelcast.core.MapEntry; import com.hazelcast.core.MultiMap; import com.hazelcast.core.Prefix; import com.hazelcast.impl.base.KeyValue; import com.hazelcast.impl.base.Pairs; import com.hazelcast.nio.Data; import com.hazelcast.query.Predicate; import java.util.*; import static com.hazelcast.impl.ClusterOperation.*; public class Entries extends AbstractSet { - final Collection<Map.Entry> colKeyValues; - final String name; - final ClusterOperation operation; - final boolean checkValue; - final Predicate predicate; - private ConcurrentMapManager concurrentMapManager; + private final Collection<Map.Entry> colKeyValues; + private final String name; + private final ClusterOperation operation; + private final boolean checkValue; + private final ConcurrentMapManager concurrentMapManager; public Entries(ConcurrentMapManager concurrentMapManager, String name, ClusterOperation operation, Predicate predicate) { this.concurrentMapManager = concurrentMapManager; this.name = name; this.operation = operation; - this.predicate = predicate; if (name.startsWith(Prefix.MULTIMAP)) { colKeyValues = new LinkedList<Map.Entry>(); } else { colKeyValues = new HashSet<Map.Entry>(); } TransactionImpl txn = ThreadContext.get().getCallContext().getTransaction(); this.checkValue = (Instance.InstanceType.MAP == BaseManager.getInstanceType(name)) && (operation == CONCURRENT_MAP_ITERATE_VALUES || operation == CONCURRENT_MAP_ITERATE_ENTRIES); if (txn != null) { List<Map.Entry> entriesUnderTxn = txn.newEntries(name); if (entriesUnderTxn != null) { if (predicate != null) { for (Map.Entry entry : entriesUnderTxn) { if (predicate.apply((MapEntry) entry)) { colKeyValues.add(entry); } } } else { colKeyValues.addAll(entriesUnderTxn); } } } } public int size() { return colKeyValues.size(); } public Iterator iterator() { return new EntryIterator(colKeyValues.iterator()); } public void clearEntries() { colKeyValues.clear(); } public void addEntries(Pairs pairs) { if (pairs == null) return; if (pairs.getKeyValues() == null) return; TransactionImpl txn = ThreadContext.get().getCallContext().getTransaction(); for (KeyValue entry : pairs.getKeyValues()) { if (txn != null) { Object key = entry.getKey(); if (txn.has(name, key)) { Data value = txn.get(name, key); if (value != null) { colKeyValues.add(BaseManager.createSimpleMapEntry(concurrentMapManager.node.factory, name, key, value)); } } else { entry.setName(concurrentMapManager.node.factory, name); colKeyValues.add(entry); } } else { entry.setName(concurrentMapManager.node.factory, name); colKeyValues.add(entry); } } } public Collection<Map.Entry> getKeyValues() { return colKeyValues; } class EntryIterator implements Iterator { final Iterator<Map.Entry> it; Map.Entry entry = null; boolean calledHasNext = false; boolean calledNext = false; boolean hasNext = false; public EntryIterator(Iterator<Map.Entry> it) { super(); this.it = it; } public boolean hasNext() { if (calledHasNext && !calledNext) { return hasNext; } calledNext = false; calledHasNext = true; hasNext = setHasNext(); return hasNext; } public boolean setHasNext() { if (!it.hasNext()) { return false; } entry = it.next(); if (checkValue && entry.getValue() == null) { return hasNext(); } return true; } public Object next() { if (!calledHasNext) { hasNext(); } calledHasNext = false; calledNext = true; if (operation == CONCURRENT_MAP_ITERATE_KEYS || operation == CONCURRENT_MAP_ITERATE_KEYS_ALL) { return entry.getKey(); } else if (operation == CONCURRENT_MAP_ITERATE_VALUES) { return entry.getValue(); } else if (operation == CONCURRENT_MAP_ITERATE_ENTRIES) { return entry; } else throw new RuntimeException("Unknown iteration type " + operation); } public void remove() { if (BaseManager.getInstanceType(name) == Instance.InstanceType.MULTIMAP) { if (operation == CONCURRENT_MAP_ITERATE_KEYS) { ((MultiMap) concurrentMapManager.node.factory.getOrCreateProxyByName(name)).remove(entry.getKey(), null); } else { ((MultiMap) concurrentMapManager.node.factory.getOrCreateProxyByName(name)).remove(entry.getKey(), entry.getValue()); } } else { ((IRemoveAwareProxy) concurrentMapManager.node.factory.getOrCreateProxyByName(name)).removeKey(entry.getKey()); } it.remove(); } } public boolean add(Object o) { throw new UnsupportedOperationException(); } public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean containsAll(Collection c) { throw new UnsupportedOperationException(); } public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } public Object[] toArray() { return toArray(null); } public Object[] toArray(Object[] a) { List values = new ArrayList(); Iterator it = iterator(); while (it.hasNext()) { Object obj = it.next(); if (obj != null) { values.add(obj); } } if (a == null) { return values.toArray(); } else { return values.toArray(a); } } } diff --git a/hazelcast/src/main/java/com/hazelcast/impl/SetProxy.java b/hazelcast/src/main/java/com/hazelcast/impl/SetProxy.java index 1ee64cdb..7091c64a 100644 --- a/hazelcast/src/main/java/com/hazelcast/impl/SetProxy.java +++ b/hazelcast/src/main/java/com/hazelcast/impl/SetProxy.java @@ -1,24 +1,24 @@ /* * Copyright (c) 2008-2012, Hazel Bilisim Ltd. 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; import com.hazelcast.core.ISet; -public interface SetProxy<E> extends ISet<E>, HazelcastInstanceAwareInstance { +public interface SetProxy<E> extends ISet<E>, IRemoveAwareProxy, HazelcastInstanceAwareInstance { MProxy getMProxy(); } diff --git a/hazelcast/src/main/java/com/hazelcast/impl/SetProxyImpl.java b/hazelcast/src/main/java/com/hazelcast/impl/SetProxyImpl.java index eeed2623..441eec70 100644 --- a/hazelcast/src/main/java/com/hazelcast/impl/SetProxyImpl.java +++ b/hazelcast/src/main/java/com/hazelcast/impl/SetProxyImpl.java @@ -1,234 +1,244 @@ /* * Copyright (c) 2008-2012, Hazel Bilisim Ltd. 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; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.ItemListener; import com.hazelcast.core.Prefix; import com.hazelcast.nio.DataSerializable; import java.io.*; import java.util.AbstractCollection; import java.util.Iterator; public class SetProxyImpl extends AbstractCollection implements SetProxy, DataSerializable, HazelcastInstanceAwareInstance { String name = null; private transient SetProxy base = null; private transient FactoryImpl factory = null; public SetProxyImpl() { } SetProxyImpl(String name, FactoryImpl factory) { this.name = name; this.factory = factory; this.base = new SetProxyReal(); } public SetProxy getBase() { return base; } public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { this.factory = (FactoryImpl) hazelcastInstance; } private void ensure() { factory.initialChecks(); if (base == null) { base = (SetProxy) factory.getOrCreateProxyByName(name); } } public Object getId() { ensure(); return base.getId(); } @Override public String toString() { return "Set [" + getName() + "]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SetProxyImpl that = (SetProxyImpl) o; return !(name != null ? !name.equals(that.name) : that.name != null); } @Override public int hashCode() { return name != null ? name.hashCode() : 0; } public int size() { ensure(); return base.size(); } public boolean contains(Object o) { ensure(); return base.contains(o); } public Iterator iterator() { ensure(); return base.iterator(); } public boolean add(Object o) { ensure(); return base.add(o); } public boolean remove(Object o) { ensure(); return base.remove(o); } public void clear() { ensure(); base.clear(); } public InstanceType getInstanceType() { ensure(); return base.getInstanceType(); } public void destroy() { factory.destroyInstanceClusterWide(name, null); } public void writeData(DataOutput out) throws IOException { out.writeUTF(name); } public void readData(DataInput in) throws IOException { name = in.readUTF(); } private void writeObject(ObjectOutputStream out) throws IOException { writeData(out); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { readData(in); } public String getName() { return name.substring(Prefix.SET.length()); } public void addItemListener(ItemListener itemListener, boolean includeValue) { ensure(); base.addItemListener(itemListener, includeValue); } public void removeItemListener(ItemListener itemListener) { ensure(); base.removeItemListener(itemListener); } public MProxy getMProxy() { ensure(); return base.getMProxy(); } + public boolean removeKey(final Object key) { + ensure(); + return base.removeKey(key); + } + class SetProxyReal extends AbstractCollection implements SetProxy { final MProxy mapProxy; public SetProxyReal() { mapProxy = new MProxyImpl(name, factory); } public Object getId() { return name; } @Override public boolean equals(Object o) { return SetProxyImpl.this.equals(o); } @Override public int hashCode() { return SetProxyImpl.this.hashCode(); } public InstanceType getInstanceType() { return BaseManager.getInstanceType(name); } public void addItemListener(ItemListener listener, boolean includeValue) { mapProxy.addGenericListener(listener, null, includeValue, getInstanceType()); } public void removeItemListener(ItemListener listener) { mapProxy.removeGenericListener(listener, null); } public String getName() { return SetProxyImpl.this.getName(); } @Override public boolean add(Object obj) { return mapProxy.add(obj); } @Override public boolean remove(Object obj) { return mapProxy.removeKey(obj); } @Override public boolean contains(Object obj) { return mapProxy.containsKey(obj); } @Override public Iterator iterator() { return mapProxy.keySet().iterator(); } @Override public int size() { return mapProxy.size(); } @Override public void clear() { mapProxy.clear(); } public void destroy() { factory.destroyInstanceClusterWide(name, null); } public MProxy getMProxy() { return mapProxy; } + public boolean removeKey(final Object key) { + return mapProxy.removeKey(key); + } + public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { } + } }
false
false
null
null
diff --git a/src/edu/sc/seis/sod/NetworkArm.java b/src/edu/sc/seis/sod/NetworkArm.java index 586fe5960..0ae83f8ae 100644 --- a/src/edu/sc/seis/sod/NetworkArm.java +++ b/src/edu/sc/seis/sod/NetworkArm.java @@ -1,528 +1,529 @@ package edu.sc.seis.sod; import edu.sc.seis.sod.subsetter.*; import edu.sc.seis.sod.database.*; import org.w3c.dom.*; import org.apache.log4j.*; import edu.sc.seis.sod.subsetter.networkArm.*; import edu.sc.seis.fissuresUtil.chooser.*; import edu.iris.Fissures.IfNetwork.*; import edu.iris.Fissures.network.*; import edu.iris.Fissures.model.*; import java.util.*; /** * NetworkArm.java * * * Created: Wed Mar 20 13:30:06 2002 * * @author <a href="mailto:">Srinivasa Telukutla</a> * @version */ public class NetworkArm { /** * Creates a new <code>NetworkArm</code> instance. * * @param config an <code>Element</code> value * @exception ConfigurationException if an error occurs */ public NetworkArm (Element config) throws ConfigurationException { if ( ! config.getTagName().equals("networkArm")) { throw new IllegalArgumentException("Configuration element must be a NetworkArm tag"); } this.config = config; processConfig(); // processConfig(config); } /** * Describe <code>processConfig</code> method here. * * @exception ConfigurationException if an error occurs */ protected void processConfig() throws ConfigurationException { networkDatabase = DatabaseManager.getDatabaseManager(Start.getProperties(), "postgres").getNetworkDatabase(); NodeList children = config.getChildNodes(); Node node; for (int i=0; i<children.getLength(); i++) { node = children.item(i); logger.debug(node.getNodeName()); if (node instanceof Element) { if (((Element)node).getTagName().equals("description")) { // skip description element continue; } Object sodElement = SodUtil.load((Element)node,"edu.sc.seis.sod.subsetter.networkArm"); if(sodElement instanceof edu.sc.seis.sod.subsetter.networkArm.NetworkFinder) networkFinderSubsetter = (edu.sc.seis.sod.subsetter.networkArm.NetworkFinder)sodElement; else if(sodElement instanceof NetworkIdSubsetter) { networkIdSubsetter = (edu.sc.seis.sod.NetworkIdSubsetter)sodElement; } else if(sodElement instanceof NetworkAttrSubsetter) { networkAttrSubsetter = (NetworkAttrSubsetter)sodElement; } else if(sodElement instanceof StationIdSubsetter)stationIdSubsetter = (StationIdSubsetter)sodElement; else if(sodElement instanceof StationSubsetter) stationSubsetter = (StationSubsetter)sodElement; else if(sodElement instanceof SiteIdSubsetter) siteIdSubsetter = (SiteIdSubsetter)sodElement; else if(sodElement instanceof SiteSubsetter) siteSubsetter = (SiteSubsetter)sodElement; else if(sodElement instanceof ChannelIdSubsetter) channelIdSubsetter = (ChannelIdSubsetter)sodElement; else if(sodElement instanceof ChannelSubsetter) channelSubsetter = (ChannelSubsetter)sodElement; else if(sodElement instanceof NetworkArmProcess) networkArmProcess = (NetworkArmProcess)sodElement; } // end of if (node instanceof Element) } // end of for (int i=0; i<children.getSize(); i++) } /* *This function starts the processing of the network Arm. *It gets all the NetworkAccesses and network ids from them *and checks if the networkId is accepted by the networkIdSubsetter. **/ /** * Describe <code>processNetworkArm</code> method here. * * @exception Exception if an error occurs */ public void processNetworkArm() throws Exception{ channelList = new ArrayList(); NetworkDC netdc = networkFinderSubsetter.getNetworkDC(); finder = netdc.a_finder(); edu.iris.Fissures.IfNetwork.NetworkAccess[] allNets = finder.retrieve_all(); networkIds = new NetworkId[allNets.length]; for(int counter = 0; counter < allNets.length; counter++) { if (allNets[counter] != null) { NetworkAttr attr = allNets[counter].get_attributes(); networkIds[counter] = attr.get_id(); if(networkIdSubsetter.accept(networkIds[counter], null)) { handleNetworkAttrSubsetter(allNets[counter], attr); } else { failure.info("Fail "+attr.get_code()); } // end of else } // end of if (allNets[counter] != null) } successfulChannels = new Channel[channelList.size()]; successfulChannels = (Channel[]) channelList.toArray(successfulChannels); } /** * Describe <code>handleNetworkAttrSubsetter</code> method here. * * @param networkAccess a <code>NetworkAccess</code> value * @param networkAttr a <code>NetworkAttr</code> value * @exception Exception if an error occurs */ public void handleNetworkAttrSubsetter(NetworkAccess networkAccess, NetworkAttr networkAttr) throws Exception{ try { //System.out.println("The stationIdSubsetter is not null"); if(networkAttrSubsetter.accept(networkAttr, null)) { Station[] stations = networkAccess.retrieve_stations(); for(int subCounter = 0; subCounter < stations.length; subCounter++) { handleStationIdSubsetter(networkAccess, stations[subCounter]); } } else { failure.info("Fail NetworkAttr"+networkAttr.get_code()); } } catch (org.omg.CORBA.UNKNOWN e) { logger.warn("Caught exception, network is: "+NetworkIdUtil.toString(networkAttr.get_id()), e); throw e; } // end of try-catch } /** * Describe <code>handleStationIdSubsetter</code> method here. * * @param networkAccess a <code>NetworkAccess</code> value * @param station a <code>Station</code> value * @exception Exception if an error occurs */ public void handleStationIdSubsetter(NetworkAccess networkAccess, Station station) throws Exception{ try { if(stationIdSubsetter.accept(station.get_id(), null)) { handleStationSubsetter(networkAccess, station); } else { failure.info("Fail StationId"+station.get_code()); } } catch (org.omg.CORBA.UNKNOWN e) { logger.warn("Caught exception, station is: "+StationIdUtil.toString(station.get_id()), e); throw e; } // end of try-catch } /** * Describe <code>handleStationSubsetter</code> method here. * * @param networkAccess a <code>NetworkAccess</code> value * @param station a <code>Station</code> value * @exception Exception if an error occurs */ public void handleStationSubsetter(NetworkAccess networkAccess, Station station) throws Exception{ if(stationSubsetter.accept(networkAccess, station, null)) { Channel[] channels = networkAccess.retrieve_for_station(station.get_id()); for(int subCounter = 0; subCounter < channels.length; subCounter++) { handleSiteIdSubsetter(networkAccess, channels[subCounter]); } } else { failure.info("Fail Station"+station.get_code()); } } /** * Describe <code>handleSiteIdSubsetter</code> method here. * * @param networkAccess a <code>NetworkAccess</code> value * @param channel a <code>Channel</code> value * @exception Exception if an error occurs */ public void handleSiteIdSubsetter(NetworkAccess networkAccess, Channel channel) throws Exception{ if(siteIdSubsetter.accept(channel.my_site.get_id(), null)) { handleSiteSubsetter(networkAccess, channel); } else { failure.info("Fail SiteId "+SiteIdUtil.toString(channel.my_site.get_id())); } } /** * Describe <code>handleSiteSubsetter</code> method here. * * @param networkAccess a <code>NetworkAccess</code> value * @param channel a <code>Channel</code> value * @exception Exception if an error occurs */ public void handleSiteSubsetter(NetworkAccess networkAccess, Channel channel) throws Exception{ if(siteSubsetter.accept(networkAccess, channel.my_site, null)) { handleChannelIdSubsetter(networkAccess, channel); } else { failure.info("Fail Site "+SiteIdUtil.toString(channel.my_site.get_id())); } } /** * Describe <code>handleChannelIdSubsetter</code> method here. * * @param networkAccess a <code>NetworkAccess</code> value * @param channel a <code>Channel</code> value * @exception Exception if an error occurs */ public void handleChannelIdSubsetter(NetworkAccess networkAccess, Channel channel) throws Exception{ if(channelIdSubsetter.accept(channel.get_id(), null)) { handleChannelSubsetter(networkAccess, channel); } else { failure.info("Fail ChannelId"+ChannelIdUtil.toStringNoDates(channel.get_id())); } } /** * Describe <code>handleChannelSubsetter</code> method here. * * @param networkAccess a <code>NetworkAccess</code> value * @param channel a <code>Channel</code> value * @exception Exception if an error occurs */ public void handleChannelSubsetter(NetworkAccess networkAccess, Channel channel) throws Exception{ if(channelSubsetter.accept(networkAccess, channel, null)) { handleNetworkArmProcess(networkAccess, channel); } else { failure.info("Fail Channel "+ChannelIdUtil.toStringNoDates(channel.get_id())); } } /** * Describe <code>handleNetworkArmProcess</code> method here. * * @param networkAccess a <code>NetworkAccess</code> value * @param channel a <code>Channel</code> value * @exception Exception if an error occurs */ public void handleNetworkArmProcess(NetworkAccess networkAccess, Channel channel) throws Exception{ networkArmProcess.process(networkAccess, channel, null); } - public Channel getChannel(int dbid) { + public synchronized Channel getChannel(int dbid) { return networkDatabase.getChannel(dbid); } - public NetworkAccess getNetworkAccess(int dbid) { + public synchronized NetworkAccess getNetworkAccess(int dbid) { return networkDatabase.getNetworkAccess(dbid); } - public int getSiteDbId(int channelid) { + public synchronized int getSiteDbId(int channelid) { return networkDatabase.getSiteDbId(channelid); } - public int getStationDbId(int siteid) { + public synchronized int getStationDbId(int siteid) { return networkDatabase.getStationDbId(siteid); } - public int getNetworkDbId(int stationid) { + public synchronized int getNetworkDbId(int stationid) { return networkDatabase.getNetworkDbId(stationid); } public boolean isRefreshIntervalValid() { RefreshInterval refreshInterval = networkFinderSubsetter.getRefreshInterval(); edu.iris.Fissures.Time databaseTime = networkDatabase.getTime(networkFinderSubsetter.getSourceName(), networkFinderSubsetter.getDNSName()); //if the networktimeconfig is null or //at every time of restart or startup //get the networks over the net. if(databaseTime == null || lastDate == null) return false; if(refreshInterval == null) return true; Date currentDate = Calendar.getInstance().getTime(); MicroSecondDate lastTime = new MicroSecondDate(databaseTime); MicroSecondDate currentTime = new MicroSecondDate(databaseTime); TimeInterval timeInterval = currentTime.difference(lastTime); timeInterval = (TimeInterval)timeInterval.convertTo(UnitImpl.MINUTE); int minutes = (int)timeInterval.value; if(minutes <= refreshInterval.getValue()) { return true; } return false; } public NetworkDbObject[] getSuccessfulNetworks() throws Exception { if(isRefreshIntervalValid()) { //get from the database. //if in cache return cache //here check the database time and //decide to see whether to get the network information // over the net or from the database. // if it can be decided that the database contains all the network information // then go ahead and get from the database else get over the net. if(lastDate == null) { //not in the cache.. lastDate = Calendar.getInstance().getTime(); networkDbObjects = networkDatabase.getNetworks(); } return networkDbObjects; } //get from Network. ArrayList arrayList = new ArrayList(); NetworkDC netdc = networkFinderSubsetter.getNetworkDC(); finder = netdc.a_finder(); edu.iris.Fissures.IfNetwork.NetworkAccess[] allNets = finder.retrieve_all(); networkIds = new NetworkId[allNets.length]; for(int counter = 0; counter < allNets.length; counter++) { if (allNets[counter] != null) { NetworkAttr attr = allNets[counter].get_attributes(); networkIds[counter] = attr.get_id(); if(networkIdSubsetter.accept(networkIds[counter], null)) { //handleNetworkAttrSubsetter(allNets[counter], attr); if(networkAttrSubsetter.accept(attr, null)) { int dbid = networkDatabase.putNetwork(networkFinderSubsetter.getSourceName(), networkFinderSubsetter.getDNSName(), allNets[counter]); NetworkDbObject networkDbObject = new NetworkDbObject(dbid, allNets[counter]); arrayList.add(networkDbObject); } } else { failure.info("Fail "+attr.get_code()); } // end of else } // end of if (allNets[counter] != null) } lastDate = Calendar.getInstance().getTime(); networkDatabase.setTime(networkFinderSubsetter.getSourceName(), networkFinderSubsetter.getDNSName(), new MicroSecondDate(lastDate).getFissuresTime()); networkDbObjects = new NetworkDbObject[arrayList.size()]; networkDbObjects = (NetworkDbObject[]) arrayList.toArray(networkDbObjects); return networkDbObjects; } public StationDbObject[] getSuccessfulStations(NetworkDbObject networkDbObject) { if(networkDbObject.stationDbObjects != null) { System.out.println("returning from the cache"); return networkDbObject.stationDbObjects; } ArrayList arrayList = new ArrayList(); try { Station[] stations = networkDbObject.getNetworkAccess().retrieve_stations(); for(int subCounter = 0; subCounter < stations.length; subCounter++) { // handleStationIdSubsetter(networkAccess, stations[subCounter]); if(stationIdSubsetter.accept(stations[subCounter].get_id(), null)) { if(stationSubsetter.accept(networkDbObject.getNetworkAccess(), stations[subCounter], null)) { int dbid = networkDatabase.putStation(networkDbObject, stations[subCounter]); StationDbObject stationDbObject = new StationDbObject(dbid, stations[subCounter]); arrayList.add(stationDbObject); } } } } catch(Exception e) { e.printStackTrace(); } StationDbObject[] rtnValues = new StationDbObject[arrayList.size()]; rtnValues = (StationDbObject[]) arrayList.toArray(rtnValues); networkDbObject.stationDbObjects = rtnValues; return rtnValues; } public SiteDbObject[] getSuccessfulSites(NetworkDbObject networkDbObject, StationDbObject stationDbObject) { if(stationDbObject.siteDbObjects != null) { System.out.println("returning from the cache"); return stationDbObject.siteDbObjects; } ArrayList arrayList = new ArrayList(); NetworkAccess networkAccess = networkDbObject.getNetworkAccess(); Station station = stationDbObject.getStation(); try { Channel[] channels = networkAccess.retrieve_for_station(station.get_id()); for(int subCounter = 0; subCounter < channels.length; subCounter++) { //handleSiteIdSubsetter(networkAccess, channels[subCounter]); if(siteIdSubsetter.accept(channels[subCounter].my_site.get_id(), null)) { if(siteSubsetter.accept(networkAccess, channels[subCounter].my_site, null)) { // int addFlag = networkDatabase.getSiteDbId(stationDbObject, // channels[subCounter].my_site); // if(addFlag != -1) { // if(!arrayList.contains // continue; // } int dbid = networkDatabase.putSite(stationDbObject, channels[subCounter].my_site); SiteDbObject siteDbObject = new SiteDbObject(dbid, channels[subCounter].my_site); if(!containsSite(siteDbObject, arrayList)) { arrayList.add(siteDbObject); } } } } } catch(Exception e) { e.printStackTrace(); } SiteDbObject[] rtnValues = new SiteDbObject[arrayList.size()]; rtnValues = (SiteDbObject[]) arrayList.toArray(rtnValues); stationDbObject.siteDbObjects = rtnValues; System.out.println(" THE LENFGHT OF THE SITES IS ***************** "+rtnValues.length); return rtnValues; } private boolean containsSite(SiteDbObject siteDbObject, ArrayList arrayList) { for(int counter = 0; counter < arrayList.size(); counter++) { SiteDbObject tempObject = (SiteDbObject) arrayList.get(counter); if(tempObject.getDbId() == siteDbObject.getDbId()) return true; } return false; } public ChannelDbObject[] getSuccessfulChannels(NetworkDbObject networkDbObject, SiteDbObject siteDbObject) { if(siteDbObject.channelDbObjects != null) { System.out.println("returning from the cache"); return siteDbObject.channelDbObjects; } ArrayList arrayList = new ArrayList(); NetworkAccess networkAccess = networkDbObject.getNetworkAccess(); Site site = siteDbObject.getSite(); try { Channel[] channels = networkAccess.retrieve_for_station(site.my_station.get_id()); for(int subCounter = 0; subCounter < channels.length; subCounter++) { if(!isSameSite(site, channels[subCounter].my_site)) continue; if(channelIdSubsetter.accept(channels[subCounter].get_id(), null)) { if(channelSubsetter.accept(networkAccess, channels[subCounter], null)) { int dbid = networkDatabase.putChannel(siteDbObject, channels[subCounter]); ChannelDbObject channelDbObject = new ChannelDbObject(dbid, channels[subCounter]); arrayList.add(channelDbObject); handleNetworkArmProcess(networkAccess, channels[subCounter]); } } } } catch(Exception e) { e.printStackTrace(); } ChannelDbObject[] values = new ChannelDbObject[arrayList.size()]; values = (ChannelDbObject[]) arrayList.toArray(values); siteDbObject.channelDbObjects = values; System.out.println("******* The elenght of the successful channels is "+values.length); + // if(siteDbObject.getDbId() == 5) System.exit(0); return values; } private boolean isSameSite(Site givenSite, Site tempSite) { SiteId givenSiteId = givenSite.get_id(); SiteId tempSiteId = tempSite.get_id(); if(givenSiteId.site_code.equals(tempSiteId.site_code)) { MicroSecondDate givenDate = new MicroSecondDate(givenSiteId.begin_time); MicroSecondDate tempDate = new MicroSecondDate(tempSiteId.begin_time); if(tempDate.equals(givenDate)) return true; } return false; } private Element config = null; private edu.sc.seis.sod.subsetter.networkArm.NetworkFinder networkFinderSubsetter = null; private edu.sc.seis.sod.NetworkIdSubsetter networkIdSubsetter = new NullNetworkIdSubsetter(); private NetworkAttrSubsetter networkAttrSubsetter = new NullNetworkAttrSubsetter(); private StationIdSubsetter stationIdSubsetter = new NullStationIdSubsetter(); private StationSubsetter stationSubsetter = new NullStationSubsetter(); private SiteIdSubsetter siteIdSubsetter = new NullSiteIdSubsetter(); private SiteSubsetter siteSubsetter = new NullSiteSubsetter(); private ChannelIdSubsetter channelIdSubsetter = new NullChannelIdSubsetter(); private ChannelSubsetter channelSubsetter = new NullChannelSubsetter(); private NetworkArmProcess networkArmProcess = new NullNetworkProcess(); private edu.iris.Fissures.IfNetwork.NetworkFinder finder = null; private NetworkId[] networkIds; private ArrayList channelList; private Channel[] successfulChannels = new Channel[0]; private NetworkDbObject[] networkDbObjects; private static java.util.Date lastDate = null; private NetworkDatabase networkDatabase; static Category logger = Category.getInstance(NetworkArm.class.getName()); static Category failure = Category.getInstance(NetworkArm.class.getName()+".failure"); }// NetworkArm
false
false
null
null
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java index e73f57a..d03a805 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java @@ -1,55 +1,44 @@ package com.earth2me.essentials.commands; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.earth2me.essentials.Essentials; import com.earth2me.essentials.User; public class Commandkickall extends EssentialsCommand { public Commandkickall() { super("kickall"); } @Override public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { - if (args.length < 1) - { - user.sendMessage("§7Usage: /" + commandLabel + "<reason>"); - return; - } - - for (Player p : server.getOnlinePlayers()) { if (server.getOnlinePlayers().length == 1 && p.getName().equalsIgnoreCase(user.getName())) { user.sendMessage("§7Only you online..."); return; } else { if (!p.getName().equalsIgnoreCase(user.getName())) { - p.kickPlayer(args.length < 1 ? args[0] : "Kicked from server"); + p.kickPlayer(args.length < 1 ? getFinalArg(args, 0) : "Kicked from server"); } } } } @Override public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { - if (args.length < 1) + for (Player p : server.getOnlinePlayers()) { - sender.sendMessage("Usage: /" + commandLabel + "<reason>"); - return; + p.kickPlayer(args.length < 1 ? getFinalArg(args, 0) : "Kicked from server"); } - - for (Player p : server.getOnlinePlayers()) - p.kickPlayer(args.length < 1 ? args[0] : "Kicked from server"); } }
false
false
null
null
diff --git a/src/plugins/XMLSpider/XMLSpider.java b/src/plugins/XMLSpider/XMLSpider.java index cf53ba3..cca454a 100644 --- a/src/plugins/XMLSpider/XMLSpider.java +++ b/src/plugins/XMLSpider/XMLSpider.java @@ -1,789 +1,789 @@ /* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package plugins.XMLSpider; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.db4o.ObjectContainer; import plugins.XMLSpider.db.Config; import plugins.XMLSpider.db.Page; import plugins.XMLSpider.db.PerstRoot; import plugins.XMLSpider.db.Status; import plugins.XMLSpider.db.Term; import plugins.XMLSpider.db.TermPosition; import plugins.XMLSpider.org.garret.perst.Storage; import plugins.XMLSpider.org.garret.perst.StorageFactory; import plugins.XMLSpider.web.WebInterface; import freenet.client.ClientMetadata; import freenet.client.FetchContext; import freenet.client.FetchException; import freenet.client.FetchResult; import freenet.client.InsertException; import freenet.client.async.BaseClientPutter; import freenet.client.async.ClientCallback; import freenet.client.async.ClientContext; import freenet.client.async.ClientGetter; import freenet.client.async.USKCallback; import freenet.clients.http.PageMaker; import freenet.clients.http.filter.ContentFilter; import freenet.clients.http.filter.FoundURICallback; import freenet.clients.http.filter.UnsafeContentTypeException; import freenet.keys.FreenetURI; import freenet.keys.USK; import freenet.l10n.L10n.LANGUAGE; import freenet.node.NodeClientCore; import freenet.node.RequestClient; import freenet.node.RequestStarter; import freenet.pluginmanager.FredPlugin; import freenet.pluginmanager.FredPluginHTTP; import freenet.pluginmanager.FredPluginL10n; import freenet.pluginmanager.FredPluginRealVersioned; import freenet.pluginmanager.FredPluginThreadless; import freenet.pluginmanager.FredPluginVersioned; import freenet.pluginmanager.PluginHTTPException; import freenet.pluginmanager.PluginRespirator; import freenet.support.Logger; import freenet.support.api.Bucket; import freenet.support.api.HTTPRequest; import freenet.support.io.NativeThread; import freenet.support.io.NullBucketFactory; /** * XMLSpider. Produces xml index for searching words. * In case the size of the index grows up a specific threshold the index is split into several subindices. * The indexing key is the md5 hash of the word. * * @author swati goyal * */ public class XMLSpider implements FredPlugin, FredPluginThreadless, FredPluginVersioned, FredPluginRealVersioned, FredPluginL10n, USKCallback, RequestClient { public Config getConfig() { return getRoot().getConfig(); } // Set config asynchronously public void setConfig(Config config) { getRoot().setConfig(config); // hack -- may cause race condition. but this is more user friendly callbackExecutor.execute(new SetConfigCallback(config)); } /** Document ID of fetching documents */ protected Map<Page, ClientGetter> runningFetch = Collections.synchronizedMap(new HashMap<Page, ClientGetter>()); /** * Lists the allowed mime types of the fetched page. */ protected Set<String> allowedMIMETypes; static int dbVersion = 37; static int version = 38; public static final String pluginName = "XML spider " + version; public String getVersion() { return version + "(" + dbVersion + ") r" + Version.getSvnRevision(); } public long getRealVersion() { return version; } private FetchContext ctx; private ClientContext clientContext; private boolean stopped = true; private NodeClientCore core; private PageMaker pageMaker; private PluginRespirator pr; /** * Adds the found uri to the list of to-be-retrieved uris. <p>Every usk uri added as ssk. * @param uri the new uri that needs to be fetched for further indexing */ public void queueURI(FreenetURI uri, String comment, boolean force) { String sURI = uri.toString(); String lowerCaseURI = sURI.toLowerCase(Locale.US); for (String ext : getRoot().getConfig().getBadlistedExtensions()) if (lowerCaseURI.endsWith(ext)) return; // be smart if (uri.isUSK()) { if (uri.getSuggestedEdition() < 0) uri = uri.setSuggestedEdition((-1) * uri.getSuggestedEdition()); try { uri = ((USK.create(uri)).getSSK()).getURI(); (clientContext.uskManager).subscribe(USK.create(uri), this, false, this); } catch (Exception e) { } } db.beginThreadTransaction(Storage.EXCLUSIVE_TRANSACTION); boolean dbTransactionEnded = false; try { Page page = getRoot().getPageByURI(uri, true, comment); if (force && page.getStatus() != Status.QUEUED) { page.setStatus(Status.QUEUED); page.setComment(comment); } db.endThreadTransaction(); dbTransactionEnded = true; } catch (RuntimeException e) { Logger.error(this, "Runtime Exception: " + e, e); throw e; } finally { if (!dbTransactionEnded) { Logger.minor(this, "rollback transaction", new Exception("debug")); db.rollbackThreadTransaction(); } } } public void startSomeRequests() { ArrayList<ClientGetter> toStart = null; synchronized (this) { if (stopped) return; synchronized (runningFetch) { int running = runningFetch.size(); int maxParallelRequests = getRoot().getConfig().getMaxParallelRequests(); if (running >= maxParallelRequests * 0.8) return; // Prepare to start toStart = new ArrayList<ClientGetter>(maxParallelRequests - running); db.beginThreadTransaction(Storage.COOPERATIVE_TRANSACTION); getRoot().sharedLockPages(Status.QUEUED); try { Iterator<Page> it = getRoot().getPages(Status.QUEUED); while (running + toStart.size() < maxParallelRequests && it.hasNext()) { Page page = it.next(); if (runningFetch.containsKey(page)) continue; try { ClientGetter getter = makeGetter(page); Logger.minor(this, "Starting " + getter + " " + page); toStart.add(getter); runningFetch.put(page, getter); } catch (MalformedURLException e) { Logger.error(this, "IMPOSSIBLE-Malformed URI: " + page, e); page.setStatus(Status.FAILED); } } } finally { getRoot().unlockPages(Status.QUEUED); db.endThreadTransaction(); } } } for (ClientGetter g : toStart) { try { g.start(null, clientContext); Logger.minor(this, g + " started"); } catch (FetchException e) { g.getClientCallback().onFailure(e, g, null); } } } private class ClientGetterCallback implements ClientCallback { final Page page; public ClientGetterCallback(Page page) { this.page = page; } public void onFailure(FetchException e, ClientGetter state, ObjectContainer container) { if (stopped) return; callbackExecutor.execute(new OnFailureCallback(e, state, page)); Logger.minor(this, "Queued OnFailure: " + page + " (q:" + callbackExecutor.getQueue().size() + ")"); } public void onFailure(InsertException e, BaseClientPutter state, ObjectContainer container) { // Ignore } public void onFetchable(BaseClientPutter state, ObjectContainer container) { // Ignore } public void onGeneratedURI(FreenetURI uri, BaseClientPutter state, ObjectContainer container) { // Ignore } public void onMajorProgress(ObjectContainer container) { // Ignore } public void onSuccess(final FetchResult result, final ClientGetter state, ObjectContainer container) { if (stopped) return; callbackExecutor.execute(new OnSuccessCallback(result, state, page)); Logger.minor(this, "Queued OnSuccess: " + page + " (q:" + callbackExecutor.getQueue().size() + ")"); } public void onSuccess(BaseClientPutter state, ObjectContainer container) { // Ignore } public String toString() { return super.toString() + ":" + page; } } private ClientGetter makeGetter(Page page) throws MalformedURLException { ClientGetter getter = new ClientGetter(new ClientGetterCallback(page), new FreenetURI(page.getURI()), ctx, getPollingPriorityProgress(), this, null, null); return getter; } protected class OnFailureCallback implements Runnable { private FetchException e; private ClientGetter state; private Page page; OnFailureCallback(FetchException e, ClientGetter state, Page page) { this.e = e; this.state = state; this.page = page; } public void run() { onFailure(e, state, page); } } protected class OnSuccessCallback implements Runnable { private FetchResult result; private ClientGetter state; private Page page; OnSuccessCallback(FetchResult result, ClientGetter state, Page page) { this.result = result; this.state = state; this.page = page; } public void run() { onSuccess(result, state, page); } } public synchronized void scheduleMakeIndex() { if (writeIndexScheduled || writingIndex) return; callbackExecutor.execute(new MakeIndexCallback()); writeIndexScheduled = true; } protected class MakeIndexCallback implements Runnable { public void run() { try { synchronized (this) { writingIndex = true; } db.gc(); indexWriter.makeIndex(getRoot()); synchronized (this) { writingIndex = false; writeIndexScheduled = false; } } catch (Exception e) { Logger.error(this, "Could not generate index: "+e, e); } finally { synchronized (this) { writingIndex = false; notifyAll(); } } } } // Set config asynchronously protected class SetConfigCallback implements Runnable { private Config config; SetConfigCallback(Config config) { this.config = config; } public void run() { synchronized (getRoot()) { getRoot().setConfig(config); startSomeRequests(); } } } protected class StartSomeRequestsCallback implements Runnable { StartSomeRequestsCallback() { } public void run() { try { Thread.sleep(30000); } catch (InterruptedException e) { // ignore } startSomeRequests(); } } protected static class CallbackPrioritizer implements Comparator<Runnable> { public int compare(Runnable o1, Runnable o2) { if (o1.getClass() == o2.getClass()) return 0; return getPriority(o1) - getPriority(o2); } private int getPriority(Runnable r) { if (r instanceof SetConfigCallback) return 0; else if (r instanceof MakeIndexCallback) return 1; else if (r instanceof OnFailureCallback) return 2; else if (r instanceof OnSuccessCallback) return 3; else if (r instanceof StartSomeRequestsCallback) return 4; return -1; } } // this is java.util.concurrent.Executor, not freenet.support.Executor // always run with one thread --> more thread cause contention and slower! public ThreadPoolExecutor callbackExecutor = new ThreadPoolExecutor( // 1, 1, 600, TimeUnit.SECONDS, // new PriorityBlockingQueue<Runnable>(5, new CallbackPrioritizer()), // new ThreadFactory() { public Thread newThread(Runnable r) { Thread t = new NativeThread(r, "XMLSpider", NativeThread.NORM_PRIORITY - 1, true); t.setDaemon(true); t.setContextClassLoader(XMLSpider.this.getClass().getClassLoader()); return t; } }); /** * Processes the successfully fetched uri for further outlinks. * * @param result * @param state * @param page */ // single threaded protected void onSuccess(FetchResult result, ClientGetter state, Page page) { synchronized (this) { if (stopped) return; } FreenetURI uri = state.getURI(); ClientMetadata cm = result.getMetadata(); Bucket data = result.asBucket(); String mimeType = cm.getMIMEType(); boolean dbTransactionEnded = false; db.beginThreadTransaction(Storage.EXCLUSIVE_TRANSACTION); try { /* * instead of passing the current object, the pagecallback object for every page is * passed to the content filter this has many benefits to efficiency, and allows us to * identify trivially which page is being indexed. (we CANNOT rely on the base href * provided). */ PageCallBack pageCallBack = new PageCallBack(page); Logger.minor(this, "Successful: " + uri + " : " + page.getId()); try { ContentFilter.filter(data, new NullBucketFactory(), mimeType, uri.toURI("http://127.0.0.1:8888/"), pageCallBack); } catch (UnsafeContentTypeException e) { // wrong mime type page.setStatus(Status.SUCCEEDED); db.endThreadTransaction(); dbTransactionEnded = true; Logger.minor(this, "UnsafeContentTypeException " + uri + " : " + page.getId(), e); return; // Ignore } catch (IOException e) { // ugh? Logger.error(this, "Bucket error?: " + e, e); return; } catch (Exception e) { // we have lots of invalid html on net - just normal, not error Logger.normal(this, "exception on content filter for " + page, e); return; } page.setStatus(Status.SUCCEEDED); db.endThreadTransaction(); dbTransactionEnded = true; Logger.minor(this, "Filtered " + uri + " : " + page.getId()); } catch (RuntimeException e) { // other runtime exceptions Logger.error(this, "Runtime Exception: " + e, e); throw e; } finally { try { data.free(); synchronized (this) { runningFetch.remove(page); } if (!stopped) startSomeRequests(); } finally { if (!dbTransactionEnded) { Logger.minor(this, "rollback transaction", new Exception("debug")); db.rollbackThreadTransaction(); db.beginThreadTransaction(Storage.EXCLUSIVE_TRANSACTION); page.setStatus(Status.FAILED); db.endThreadTransaction(); } } } } protected void onFailure(FetchException fe, ClientGetter state, Page page) { Logger.minor(this, "Failed: " + page + " : " + state, fe); synchronized (this) { if (stopped) return; } boolean dbTransactionEnded = false; db.beginThreadTransaction(Storage.EXCLUSIVE_TRANSACTION); try { synchronized (page) { if (fe.newURI != null) { // redirect, mark as succeeded queueURI(fe.newURI, "redirect from " + state.getURI(), false); page.setStatus(Status.SUCCEEDED); } else if (fe.isFatal()) { // too many tries or fatal, mark as failed page.setStatus(Status.FAILED); } else { // requeue at back page.setStatus(Status.QUEUED); } } db.endThreadTransaction(); dbTransactionEnded = true; } catch (Exception e) { Logger.error(this, "Unexcepected exception in onFailure(): " + e, e); throw new RuntimeException("Unexcepected exception in onFailure()", e); } finally { runningFetch.remove(page); if (!dbTransactionEnded) { Logger.minor(this, "rollback transaction", new Exception("debug")); db.rollbackThreadTransaction(); } } startSomeRequests(); } private boolean writingIndex; private boolean writeIndexScheduled; protected IndexWriter indexWriter; public IndexWriter getIndexWriter() { return indexWriter; } public void terminate(){ Logger.normal(this, "XMLSpider terminating"); synchronized (this) { try { Runtime.getRuntime().removeShutdownHook(exitHook); } catch (IllegalStateException e) { // shutting down, ignore } stopped = true; for (Map.Entry<Page, ClientGetter> me : runningFetch.entrySet()) { ClientGetter getter = me.getValue(); Logger.minor(this, "Canceling request" + getter); - getter.cancel(); + getter.cancel(null, clientContext); } runningFetch.clear(); callbackExecutor.shutdownNow(); } try { callbackExecutor.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException e) {} try { db.close(); } catch (Exception e) {} webInterface.unload(); Logger.normal(this, "XMLSpider terminated"); } public class ExitHook implements Runnable { public void run() { Logger.normal(this, "XMLSpider exit hook called"); terminate(); } } private Thread exitHook = new Thread(new ExitHook()); public synchronized void runPlugin(PluginRespirator pr) { this.core = pr.getNode().clientCore; this.pr = pr; pageMaker = pr.getPageMaker(); Runtime.getRuntime().addShutdownHook(exitHook); /* Initialize Fetch Context */ this.ctx = pr.getHLSimpleClient().getFetchContext(); ctx.maxSplitfileBlockRetries = 1; ctx.maxNonSplitfileRetries = 1; ctx.maxTempLength = 2 * 1024 * 1024; ctx.maxOutputLength = 2 * 1024 * 1024; allowedMIMETypes = new HashSet<String>(); allowedMIMETypes.add("text/html"); allowedMIMETypes.add("text/plain"); allowedMIMETypes.add("application/xhtml+xml"); ctx.allowedMIMETypes = new HashSet<String>(allowedMIMETypes); clientContext = pr.getNode().clientCore.clientContext; stopped = false; // Initial Database db = initDB(); indexWriter = new IndexWriter(); webInterface = new WebInterface(this, pr.getHLSimpleClient(), pr.getToadletContainer()); webInterface.load(); FreenetURI[] initialURIs = core.getBookmarkURIs(); for (int i = 0; i < initialURIs.length; i++) queueURI(initialURIs[i], "bookmark", false); callbackExecutor.execute(new StartSomeRequestsCallback()); } private WebInterface webInterface; /** * creates the callback object for each page. *<p>Used to create inlinks and outlinks for each page separately. * @author swati * */ public class PageCallBack implements FoundURICallback{ protected final Page page; protected final boolean logDEBUG = Logger.shouldLog(Logger.DEBUG, this); // per instance, allow changing on the fly PageCallBack(Page page) { this.page = page; page.clearTermPosition(); } public void foundURI(FreenetURI uri){ // Ignore } public void foundURI(FreenetURI uri, boolean inline){ if (stopped) throw new RuntimeException("plugin stopping"); if (logDEBUG) Logger.debug(this, "foundURI " + uri + " on " + page); queueURI(uri, "Added from " + page.getURI(), false); } protected Integer lastPosition = null; public void onText(String s, String type, URI baseURI){ if (stopped) throw new RuntimeException("plugin stopping"); if (logDEBUG) Logger.debug(this, "onText on " + page.getId() + " (" + baseURI + ")"); if ("title".equalsIgnoreCase(type) && (s != null) && (s.length() != 0) && (s.indexOf('\n') < 0)) { /* * title of the page */ page.setPageTitle(s); type = "title"; } else type = null; /* * determine the position of the word in the retrieved page * FIXME - replace with a real tokenizor */ String[] words = s.split("[^\\p{L}\\{N}]+"); if(lastPosition == null) lastPosition = 1; for (int i = 0; i < words.length; i++) { String word = words[i]; if ((word == null) || (word.length() == 0)) continue; word = word.toLowerCase(); try{ if(type == null) addWord(word, lastPosition + i); else addWord(word, -1 * (i + 1)); } catch (Exception e){} } if(type == null) { lastPosition = lastPosition + words.length; } } private void addWord(String word, int position) throws Exception { if (logDEBUG) Logger.debug(this, "addWord on " + page.getId() + " (" + word + "," + position + ")"); if (word.length() < 3) return; Term term = getTermByWord(word, true); TermPosition termPos = page.getTermPosition(term, true); termPos.addPositions(position); } } public void onFoundEdition(long l, USK key, ObjectContainer container, ClientContext context, boolean metadata, short codec, byte[] data, boolean newKnownGood, boolean newSlotToo) { FreenetURI uri = key.getURI(); /*- * FIXME this code don't make sense * (1) runningFetchesByURI contain SSK, not USK * (2) onFoundEdition always have the edition set * if(runningFetchesByURI.containsKey(uri)) runningFetchesByURI.remove(uri); uri = key.getURI().setSuggestedEdition(l); */ queueURI(uri, "USK found edition", true); startSomeRequests(); } public short getPollingPriorityNormal() { return (short) Math.min(RequestStarter.MINIMUM_PRIORITY_CLASS, getRoot().getConfig().getRequestPriority() + 1); } public short getPollingPriorityProgress() { return getRoot().getConfig().getRequestPriority(); } protected Storage db; /** * Initializes Database */ private Storage initDB() { Storage db = StorageFactory.getInstance().createStorage(); db.setProperty("perst.object.cache.kind", "pinned"); db.setProperty("perst.object.cache.init.size", 8192); db.setProperty("perst.alternative.btree", true); db.setProperty("perst.string.encoding", "UTF-8"); db.setProperty("perst.concurrent.iterator", true); db.open("XMLSpider-" + dbVersion + ".dbs"); PerstRoot root = (PerstRoot) db.getRoot(); if (root == null) PerstRoot.createRoot(db); return db; } public PerstRoot getRoot() { return (PerstRoot) db.getRoot(); } protected Page getPageByURI(FreenetURI uri) { return getRoot().getPageByURI(uri, false, null); } protected Page getPageById(long id) { return getRoot().getPageById(id); } // language for I10N private LANGUAGE language; protected Term getTermByWord(String word, boolean create) { return getRoot().getTermByWord(word, create); } public String getString(String key) { // TODO return a translated string return key; } public void setLanguage(LANGUAGE newLanguage) { language = newLanguage; } public PageMaker getPageMaker() { return pageMaker; } public List<Page> getRunningFetch() { synchronized (runningFetch) { return new ArrayList<Page>(runningFetch.keySet()); } } public boolean isWriteIndexScheduled() { return writeIndexScheduled; } public boolean isWritingIndex() { return writingIndex; } public PluginRespirator getPluginRespirator() { return pr; } public boolean persistent() { return false; } public void removeFrom(ObjectContainer container) { throw new UnsupportedOperationException(); } }
true
false
null
null
diff --git a/src/test/java/com/sonyericsson/jenkins/plugins/externalresource/dispatcher/data/ExternalResourceTest.java b/src/test/java/com/sonyericsson/jenkins/plugins/externalresource/dispatcher/data/ExternalResourceTest.java index dde4dbf..92b3625 100644 --- a/src/test/java/com/sonyericsson/jenkins/plugins/externalresource/dispatcher/data/ExternalResourceTest.java +++ b/src/test/java/com/sonyericsson/jenkins/plugins/externalresource/dispatcher/data/ExternalResourceTest.java @@ -1,241 +1,249 @@ /* * The MIT License * * Copyright 2011 Sony Ericsson Mobile Communications. All rights reserved. * Copyright 2012 Sony Mobile Communications AB. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.sonyericsson.jenkins.plugins.externalresource.dispatcher.data; import com.sonyericsson.hudson.plugins.metadata.model.JsonUtils; import com.sonyericsson.hudson.plugins.metadata.model.MetadataJobProperty; import com.sonyericsson.hudson.plugins.metadata.model.MetadataNodeProperty; import com.sonyericsson.hudson.plugins.metadata.model.values.MetadataValue; import com.sonyericsson.hudson.plugins.metadata.model.values.TreeStructureUtil; import com.sonyericsson.jenkins.plugins.externalresource.dispatcher.Constants; import com.sonyericsson.jenkins.plugins.externalresource.dispatcher.MockUtils; import hudson.model.Hudson; import net.sf.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.LinkedList; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import static com.sonyericsson.jenkins.plugins.externalresource.dispatcher.Constants.JSON_ATTR_ENABLED; import static com.sonyericsson.jenkins.plugins.externalresource.dispatcher.Constants.JSON_ATTR_ID; import static com.sonyericsson.jenkins.plugins.externalresource.dispatcher.Constants.JSON_ATTR_LOCKED; import static com.sonyericsson.jenkins.plugins.externalresource.dispatcher.Constants.JSON_ATTR_RESERVED; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; //CS IGNORE MagicNumber FOR NEXT 200 LINES. REASON: Test data. /** * Tests for {@link ExternalResource} and it's descriptor. * * @author Robert Sandell &lt;robert.sandell@sonyericsson.com&gt; */ @RunWith(PowerMockRunner.class) public class ExternalResourceTest { //CS IGNORE LineLength FOR NEXT 4 LINES. REASON: JavaDoc /** * Tests {@link com.sonyericsson.jenkins.plugins.externalresource.dispatcher.data.ExternalResource.ExternalResourceDescriptor#appliesTo(hudson.model.Descriptor)} * that it doesn't apply to a Job. */ @Test public void testAppliesToJob() { ExternalResource.ExternalResourceDescriptor descriptor = new ExternalResource.ExternalResourceDescriptor(); assertFalse(descriptor.appliesTo(new MetadataJobProperty.MetaDataJobPropertyDescriptor())); } //CS IGNORE LineLength FOR NEXT 4 LINES. REASON: JavaDoc /** * Tests {@link com.sonyericsson.jenkins.plugins.externalresource.dispatcher.data.ExternalResource.ExternalResourceDescriptor#appliesTo(hudson.model.Descriptor)} * that it doesn't apply to a node. */ @Test public void testAppliesToBuild() { ExternalResource.ExternalResourceDescriptor descriptor = new ExternalResource.ExternalResourceDescriptor(); assertFalse(descriptor.appliesTo(new MetadataNodeProperty.MetadataNodePropertyDescriptor())); } /** * Tests {@link Lease#createInstance(long, int, String)}. When the slave timeZone is in Japan and the local server * is here. */ @Test public void testLeaseCreateInstanceJapan() { // Given a time of 10am in Japan, get the server time Calendar japanCal = new GregorianCalendar(TimeZone.getTimeZone("Japan")); japanCal.set(Calendar.HOUR_OF_DAY, 10); // 0..23 japanCal.set(Calendar.MINUTE, 0); japanCal.set(Calendar.SECOND, 0); long japanOffsetMs = japanCal.getTimeZone().getRawOffset(); if (japanCal.getTimeZone().inDaylightTime(japanCal.getTime())) { japanOffsetMs += japanCal.getTimeZone().getDSTSavings(); } int seconds = (int)TimeUnit.MILLISECONDS.toSeconds(japanOffsetMs); Lease lease = Lease.createInstance(japanCal.getTimeInMillis(), seconds, "Japan RuleZ"); Calendar local = new GregorianCalendar(); long localOffsetMs = local.getTimeZone().getRawOffset(); if (local.getTimeZone().inDaylightTime(local.getTime())) { localOffsetMs += local.getTimeZone().getDSTSavings(); } int localOffset = (int)TimeUnit.MILLISECONDS.toHours(localOffsetMs); int japanOffset = (int)TimeUnit.SECONDS.toHours(seconds); - assertEquals(10 - japanOffset + localOffset, lease.getServerTime().get(Calendar.HOUR_OF_DAY)); + //"time in zone B" = ("time in zone A" - "UTC offset for zone A" + "UTC offset for zone B") % 24. + int resultTime = 10 - japanOffset + localOffset; + if (resultTime < 0) + resultTime += 24; + assertEquals(resultTime, lease.getServerTime().get(Calendar.HOUR_OF_DAY)); } /** * Tests {@link Lease#createInstance(long, int, String)}. When the slave timeZone is PST and the local server is * here. */ @Test public void testLeaseCreateInstanceSf() { // Given a time of 9am in San Francisco, get the server time Calendar sfCal = new GregorianCalendar(TimeZone.getTimeZone("PST")); sfCal.set(Calendar.HOUR_OF_DAY, 9); // 0..23 sfCal.set(Calendar.MINUTE, 0); sfCal.set(Calendar.SECOND, 0); int seconds = (int)TimeUnit.MILLISECONDS.toSeconds(sfCal.getTimeZone().getRawOffset()); Lease lease = Lease.createInstance(sfCal.getTimeInMillis(), seconds, "SF RuleZ"); Calendar local = new GregorianCalendar(); int localOffset = (int)TimeUnit.MILLISECONDS.toHours(local.getTimeZone().getRawOffset()); int sfOffset = (int)TimeUnit.SECONDS.toHours(seconds); - - assertEquals(9 - sfOffset + localOffset, lease.getServerTime().get(Calendar.HOUR_OF_DAY)); + + //"time in zone B" = ("time in zone A" - "UTC offset for zone A" + "UTC offset for zone B") % 24. + int resultTime = 9 - sfOffset + localOffset; + if (resultTime < 0) + resultTime += 24; + assertEquals(resultTime, lease.getServerTime().get(Calendar.HOUR_OF_DAY)); } /** * Tests {@link ExternalResource#toJson()}. */ @PrepareForTest(Hudson.class) @Test public void testToJson() { Hudson hudson = MockUtils.mockHudson(); MockUtils.mockMetadataValueDescriptors(hudson); String name = "name"; String description = "description"; String id = "id"; ExternalResource resource = new ExternalResource(name, description, id, true, new LinkedList<MetadataValue>()); String me = "me"; resource.setReserved( new StashInfo(StashInfo.StashType.INTERNAL, me, new Lease(Calendar.getInstance(), "iso"), "key")); TreeStructureUtil.addValue(resource, "value", "descript", "some", "path"); JSONObject json = resource.toJson(); assertEquals(name, json.getString(JsonUtils.NAME)); assertEquals(id, json.getString(JSON_ATTR_ID)); assertTrue(json.getBoolean(JSON_ATTR_ENABLED)); assertTrue(json.getJSONObject(JSON_ATTR_LOCKED).isNullObject()); JSONObject reserved = json.getJSONObject(JSON_ATTR_RESERVED); assertNotNull(reserved); assertEquals(StashInfo.StashType.INTERNAL.name(), reserved.getString(Constants.JSON_ATTR_TYPE)); assertEquals(me, reserved.getString(Constants.JSON_ATTR_STASHED_BY)); assertEquals(1, json.getJSONArray(JsonUtils.CHILDREN).size()); } /** * Tests {@link ExternalResource#clone()}. * * @throws CloneNotSupportedException if it fails. */ @Test public void testClone() throws CloneNotSupportedException { String name = "name"; String description = "description"; String id = "id"; ExternalResource resource = new ExternalResource(name, description, id, true, new LinkedList<MetadataValue>()); String me = "me"; resource.setReserved( new StashInfo(StashInfo.StashType.INTERNAL, me, new Lease(Calendar.getInstance(), "iso"), "key")); TreeStructureUtil.addValue(resource, "value", "descript", "some", "path"); ExternalResource other = resource.clone(); assertEquals(name, other.getName()); assertEquals(id, other.getId()); assertNotNull(other.getReserved()); assertNotSame(resource.getReserved(), other.getReserved()); assertEquals(resource.getReserved().getStashedBy(), other.getReserved().getStashedBy()); assertNotSame(resource.getReserved().getLease(), other.getReserved().getLease()); assertEquals(resource.getReserved().getLease().getSlaveIsoTime(), other.getReserved().getLease().getSlaveIsoTime()); assertNotSame(TreeStructureUtil.getPath(resource, "some", "path"), TreeStructureUtil.getPath(other, "some", "path")); assertEquals(TreeStructureUtil.getPath(resource, "some", "path").getValue(), TreeStructureUtil.getPath(other, "some", "path").getValue()); assertTrue(other.isEnabled()); } /** * Tests {@link ExternalResource#isEnabled()} when enables is set to null (not set). */ @Test public void testIsEnabledNotSet() { ExternalResource resource = new ExternalResource("name", "description", "id", null, null); assertTrue(resource.isEnabled()); } /** * Tests {@link ExternalResource#isEnabled()} when enables is set to false. */ @Test public void testIsEnabledFalse() { ExternalResource resource = new ExternalResource("name", "description", "id", null, null); resource.setEnabled(false); assertFalse(resource.isEnabled()); } /** * Tests {@link ExternalResource#isEnabled()} when enables is set to true. */ @Test public void testIsEnabledTrue() { ExternalResource resource = new ExternalResource("name", "description", "id", null, null); resource.setEnabled(true); assertTrue(resource.isEnabled()); } }
false
false
null
null
diff --git a/src/openmap/com/bbn/openmap/util/propertyEditor/Inspector.java b/src/openmap/com/bbn/openmap/util/propertyEditor/Inspector.java index fe1f6ff6..1cb24b52 100644 --- a/src/openmap/com/bbn/openmap/util/propertyEditor/Inspector.java +++ b/src/openmap/com/bbn/openmap/util/propertyEditor/Inspector.java @@ -1,454 +1,453 @@ /* * File: Inspector.java * Date: Jul 2001 * Author: Kai Lessmann <klessman@intevation.de> * Copyright 2001 Intevation GmbH, Germany * * This file is Free Software to be included into OpenMap * under its Free Software license. * Permission is granted to use, modify and redistribute. * * Intevation hereby grants BBN a royalty free, worldwide right and license * to use, copy, distribute and make Derivative Works * of this Free Software created by Kai Lessmann * and sublicensing rights of any of the foregoing. * */ package com.bbn.openmap.util.propertyEditor; import com.bbn.openmap.*; import com.bbn.openmap.gui.WindowSupport; import com.bbn.openmap.layer.shape.*; // for main import com.bbn.openmap.util.Debug; import com.bbn.openmap.util.PropUtils; import com.bbn.openmap.util.propertyEditor.*; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.beans.*; /** * Class to inspect a PropertyConsumer. Used by the LayerAddPanel * class to interactively configure a Layer object before it gets * added to the map. This class should suffice to "inspect" any * PropertyConsumer on a very basic level, handling is more convinient * if property editor classes are available. The behavior of the * Inspector is configured through properties; the propertiesInfo * object of a PropertyConsumer may contain a initPropertiesProperty * which determines which properties are to be shown and in which * order, in a space seperated list, i.e. * * <code> * initPropertiesProperty=class prettyName shapeFile * * </code> * If this property is not defined, then all the properties will be * displayed, in alphabetical order. * * For each property there may be a editorProperty entry giving a * PropertyEditor class to instanciate as an editor for the property, * i.e. * <code> * shapeFile.editor=com.bbn.openmap.util.propertyEditor.FilePropertyEditor * </code>. */ public class Inspector implements ActionListener { /** A simple TextField as a String editor. */ protected final String defaultEditorClass = "com.bbn.openmap.util.propertyEditor.TextPropertyEditor"; /** * The PropertyConsumer being inspected. Set in * inspectPropertyConsumer. */ PropertyConsumer propertyConsumer = null; /** Handle to the GUI. Used for setVisible(true/false). */ protected WindowSupport windowSupport = null; /** Action command for the cancelButton. */ // public so it can be referenced from the actionListener public final static String cancelCommand = "cancelCommand"; /** The action command for the doneButton. */ // public so it can be referenced from the actionListener public final static String doneCommand = "doneCommand"; /** * Hashtable containing property names, and their editors. Used * to fetch user inputs for configuring a property consumer. */ protected Hashtable editors = null; /** * Handle to call back the object that invokes this * Inspector. */ protected ActionListener actionListener = null; /** * Flag to print out the properties. Used when the Inspector is * in stand-alone mode, so that the properties are directed to * stdout. */ protected boolean print = false; /** * Set an Actionlistener for callbacks. Once a Layer object is * configured, ie the "Add" button has been clicked, an * ActionListener that invoked this Inspector can register here to * be notified. */ public void addActionListener(java.awt.event.ActionListener al) { actionListener = al; } /** Does nothing. */ public Inspector() {} /** Sets the actionListener. */ public Inspector(ActionListener al) { actionListener = al; } /** * Inspect and configure a PropertyConsumer object. Main method * of this class. The argument PropertyConsumer is inspected * through the ProperyConsumer interface, the properties are * displayed to be edited. */ public void inspectPropertyConsumer(PropertyConsumer propertyConsumer) { String prefix = propertyConsumer.getPropertyPrefix(); // construct GUI if (windowSupport != null) { windowSupport.killWindow(); windowSupport = null; } JComponent comp = createPropertyGUI(propertyConsumer); windowSupport = new WindowSupport(comp, "Inspector - " + prefix); windowSupport.setMaxSize(-1, 500); windowSupport.displayInWindow(); } public Vector sortKeys(Collection keySet) { Vector vector = new Vector(keySet.size()); // OK, ok, this isn't the most efficient way to do this, but // it's simple. Shouldn't matter for what we are using it // for... Iterator it = keySet.iterator(); while (it.hasNext()) { String key = (String) it.next(); int size = vector.size(); for (int i = 0; i <= size; i++) { if (i == size) { // System.out.println("Adding " + key + " at " + i); vector.add(key); break; } else { int compare = key.compareTo((String)vector.elementAt(i)); if (compare < 0) { // System.out.println(key + " goes before " + // vector.elementAt(i) + " at " + i); vector.add(i, key); break; } } } } return vector; } /** * Creates a JComponent with the properties to be changed. This * component is suitable for inclusion into a GUI. * @param pc The property consumer to create a gui for. * @return JComponent, a panel holding the interface to set the * properties. */ public JComponent createPropertyGUI(PropertyConsumer pc) { // fill variables this.propertyConsumer = pc; Properties props = new Properties(); props = pc.getProperties(props); Properties info = new Properties(); info = pc.getPropertyInfo(info); String prefix = pc.getPropertyPrefix(); return createPropertyGUI(prefix, props, info); } /** * Creates a JComponent with the properties to be changed. This * component is suitable for inclusion into a GUI. Don't use this * method directly! Use the createPropertyGUI(PropertyConsumer) * instead. You will get a NullPointerException if you use this * method without setting the PropertyConsumer in the Inspector. * * @param prefix the property prefix for the property consumer. * Received from the PropertyConsumer.getPropertyPrefix() method. * Properties that start with this prefix will have the prefix * removed from the display, so the GUI will only show the actual * property name. * @param props the properties received from the * PropertyConsumer.getProperties() method. * @param info the properties received from the * PropertyConsumer.getPropertyInfo() method, containing * descriptions and any specific PropertyEditors that should be * used for a particular property named in the * PropertyConsumer.getProperties() properties. * @return JComponent, a panel holding the interface to set the * properties. */ public JComponent createPropertyGUI( String prefix, Properties props, Properties info) { if (Debug.debugging("inspectordetail")) { - Debug.output("Inspector creating GUI for " + prefix + "\n" + - props + "\n" + info); + Debug.output("Inspector creating GUI for " + prefix + "\nPROPERTIES " + + props + "\nPROP INFO " + info); } // collect the info needed... Collection keySet = props.keySet(); String propertyList = info.getProperty(PropertyConsumer.initPropertiesProperty); Vector sortedKeys; if (propertyList != null) { Vector propertiesToShow = PropUtils.parseSpacedMarkers(propertyList); for (int i=0; i < propertiesToShow.size(); i++) { propertiesToShow.set(i, prefix + "." + propertiesToShow.get(i)); } sortedKeys = propertiesToShow; } else { // otherwise, show them all, in alphabetical order sortedKeys = sortKeys(keySet); } int num = sortedKeys.size(); - editors = new Hashtable(num); - Iterator it = sortedKeys.iterator(); - JButton doneButton = null, cancelButton = null; JPanel component = new JPanel(); component.setLayout(new BorderLayout()); JPanel propertyPanel = new JPanel(); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(2, 20, 2, 20); propertyPanel.setLayout(gridbag); int i = 0; - - while (it.hasNext()) { // iterate properties + for (Iterator it = sortedKeys.iterator();it.hasNext();) { // iterate properties String prop = (String)it.next(); String marker = prop; if (prefix != null && prop.startsWith(prefix)) { marker = prop.substring(prefix.length()+1); } if (marker.startsWith(".")) { marker = marker.substring(1); } - String editorClass = info.getProperty(marker + "." + PropertyConsumer.EditorProperty); + String editorMarker = marker + PropertyConsumer.ScopedEditorProperty; + String editorClass = info.getProperty(editorMarker); if (editorClass == null) { editorClass = defaultEditorClass; } // instantiate PropertyEditor Class propertyEditorClass = null; PropertyEditor editor = null; try { propertyEditorClass = Class.forName(editorClass); editor = (PropertyEditor)propertyEditorClass.newInstance(); editors.put(prop, editor); } catch(Exception e) { e.printStackTrace(); editorClass = null; } Component editorFace = null; if (editor != null && editor.supportsCustomEditor()) { editorFace = editor.getCustomEditor(); } else { editorFace = new JLabel("Does not support custom editor"); } if (editor != null) { Object propVal = props.get(prop); if (Debug.debugging("inspector")) { Debug.output("Inspector loading " + prop + "(" + propVal + ")"); } editor.setValue(propVal); } // Customized labels for each property, instead of the // abbreviated nature of the true property names. - String labelText = (String)info.get(marker + PropertyConsumer.LabelEditorProperty); + String labelMarker = marker + PropertyConsumer.LabelEditorProperty; + String labelText = info.getProperty(labelMarker); if (labelText == null) { labelText = marker; } - JLabel label = new JLabel(marker + ":"); + JLabel label = new JLabel(labelText + ":"); label.setHorizontalAlignment(SwingConstants.RIGHT); c.gridx = 0; c.gridy = i++; c.weightx = 0; c.fill = GridBagConstraints.NONE; c.anchor = GridBagConstraints.EAST; gridbag.setConstraints(label, c); propertyPanel.add(label); c.gridx = 1; c.anchor = GridBagConstraints.WEST; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1f; gridbag.setConstraints(editorFace, c); propertyPanel.add(editorFace); String toolTip = (String)info.get(marker); label.setToolTipText(toolTip==null ? "No further information available." : toolTip); } // create the palette's scroll pane JScrollPane scrollPane = new JScrollPane( propertyPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT); scrollPane.setAlignmentY(Component.TOP_ALIGNMENT); component.add(scrollPane, BorderLayout.CENTER); JPanel buttons = new JPanel(); if (print) { doneButton = new JButton("Print"); cancelButton = new JButton("Quit"); } else { doneButton = new JButton("OK"); cancelButton = new JButton("Cancel"); } doneButton.addActionListener(this); doneButton.setActionCommand(doneCommand); cancelButton.addActionListener(this); cancelButton.setActionCommand(cancelCommand); buttons.add(doneButton); buttons.add(cancelButton); component.add(buttons, BorderLayout.SOUTH); component.validate(); return component; } /** * Implement the ActionListener interface. The actions * registering here should be generated by the two buttons in the * Inspector GUI. */ public void actionPerformed(ActionEvent e) { final String actionCommand = e.getActionCommand(); String prefix = propertyConsumer.getPropertyPrefix(); if (actionCommand == doneCommand) {// confirmed Properties props = collectProperties(); if (!print) { windowSupport.killWindow(); propertyConsumer.setProperties(prefix, props); if (actionListener != null) { actionListener.actionPerformed(e); } } else { Collection keys = props.keySet(); Iterator it = keys.iterator(); while (it.hasNext()) { String next = (String)it.next(); System.out.println(next + "=" + props.get(next)); } } } else if (actionCommand == cancelCommand) {// canceled if (actionListener != null && actionListener != this) { actionListener.actionPerformed(e); } propertyConsumer = null; // to be garb. coll'd windowSupport.killWindow(); if (print) { System.exit(0); } } } /** Extracts properties from textfield[]. */ public Properties collectProperties() { Properties props = new Properties(); Iterator values = editors.keySet().iterator(); while (values.hasNext()) { String key = (String) values.next(); PropertyEditor editor = (PropertyEditor)editors.get(key); if (editor != null) { String stuff = editor.getAsText(); // If it's not defined with text, don't put it in the // properties. The layer should handle this and use // its default settings. if (!stuff.equals("")) { props.put(key, stuff); } } } return props; } public void setPrint(boolean p) { print = p; } public boolean getPrint() { return print; } public WindowSupport getWindowSupport() { return windowSupport; } /** test cases. */ public static void main(String[] args) { + Debug.init(); String name = (args.length<1)?"com.bbn.openmap.layer.shape.ShapeLayer":args[0]; PropertyConsumer propertyconsumer = null; try { Class c = Class.forName(name); propertyconsumer = (PropertyConsumer)c.newInstance(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } Properties props=new Properties(), info=new Properties(); System.out.println("Inspecting " + name); String pp = name.substring(name.lastIndexOf(".") + 1); propertyconsumer.setPropertyPrefix(pp.toLowerCase()); props = propertyconsumer.getProperties(props); info = propertyconsumer.getPropertyInfo(info); Inspector inspector = new Inspector(); inspector.setPrint(true); inspector.addActionListener(inspector); inspector.inspectPropertyConsumer(propertyconsumer); } }
false
false
null
null
diff --git a/src/com/sun/jini/tool/ClassDep.java b/src/com/sun/jini/tool/ClassDep.java index 2b586d65..371bcaa8 100644 --- a/src/com/sun/jini/tool/ClassDep.java +++ b/src/com/sun/jini/tool/ClassDep.java @@ -1,1685 +1,1685 @@ /* * 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.sun.jini.tool; import sun.tools.java.BinaryClass; import sun.tools.java.ClassDeclaration; import sun.tools.java.ClassFile; import sun.tools.java.ClassNotFound; import sun.tools.java.ClassPath; import sun.tools.java.Constants; import sun.tools.java.Environment; import sun.tools.java.Identifier; import sun.tools.java.MemberDefinition; import sun.tools.java.Package; import sun.tools.java.Type; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.StringTokenizer; import java.util.SortedSet; import java.util.TreeSet; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.IOException; /** * Tool used to analyze a set of classes and determine on what other classes * they directly or indirectly depend. Typically this tool is used to * compute the necessary and sufficient set of classes to include in a JAR * file, for use in the class path of a client or service, or for use in the * codebase of a client or service. The tool starts with a set of "root" * classes and recursively computes a dependency graph, finding all of the * classes referenced directly by the root classes, finding all of the * classes referenced in turn by those classes, and so on, until no new * classes are found or until classes that are not of interest are * found. The normal output of the tool is a list of all of the classes in * the dependency graph. The output from this command can be used as input * to the <code>jar</code> tool, to create a JAR file containing precisely * those classes. * <p> * The following items are discussed below: * <ul> * <li><a href="#running">Running the Tool</a> * <li><a href="#processing">Processing Options</a> * <li><a href="#output">Output Options and Arguments</a> * <li><a href="#examples">Examples</a> * </ul> * * <a name="running"></a> * <h3>Running the Tool</h3> * * The command line for running the tool has the form: * <blockquote><pre> * java -jar <var><b>install_dir</b></var>/lib/classdep.jar \ * -cp <var><b>input_classpath</b></var> <var><b>processing_options</b></var> <var><b>output_options</b></var> * </pre></blockquote> * <p> * where <var><b>install_dir</b></var> is the directory where the Apache River release * is installed. * Note that the options for this tool can be specified in any order, and * can be intermixed. * * <p> * The <code>-cp</code> class path value, * <var><b>input_classpath</b></var>, * is an argument to the <code>ClassDep</code> tool itself and should * include all of the classes that might need to be included in the * dependency analysis. Typically this will include all of your application * classes, classes from the Apache River release, and any other classes on which * your classes might depend. It is safe to include more classes than are * actually necessary (since the purpose of this tool is, after all, to * determine which subset of these classes is actually necessary), but it is * not necessary to include any classes that are part of the Java 2 SDK. * The class path should be in the form of a list of directories or JAR * files, delimited by a colon (":") on UNIX platforms and a semi-colon * (";") on Microsoft Windows platforms. The order of locations in the path * does not matter. If you use JAR files, any <code>Class-Path</code> * manifest entries in those JAR files are ignored, so you must include the * values of those manifest entries explicitly in the path, or errors may * result. For example, if you include <code>jini-ext.jar</code> then you * should explicitly include <code>jini-core.jar</code> as well, because * <code>jini-core.jar</code> is in the <code>Class-Path</code> manifest * entry of <code>jini-ext.jar</code>.</dd> * * <a name="processing"></a> * <h3>Processing Options</h3> * * The root classes of the dependency graph can be specified by any * combination of individual classes and directories of classes. Each of * these options can be used any number of times, and are illustrated in the * <a href="#examples">Examples</a> section of this page. * <p> * In general, you only need to specify concrete classes as roots, not * interface types. When analyzing classes for the class path of an * application, you typically need to include the top-level class (the one * with the <code>main</code> method). When analyzing classes for the * codebase of a service, you typically need to include the top-level proxy * classes used by the service, any trust verifier classes for those * proxies, and any custom entry classes used by the service for lookup * service attributes. Also when analyzing classes for the codebase of a * service, if the service's proxy can return leases, registration objects, * or other proxies, or if your service generates events, and if those * objects are only referenced by interface type in the top-level proxy, not * by concrete class, then you also need to include the concrete classes of * those other objects. In all cases, you typically need to include any stub * classes that you generated with the <code>rmic</code> tool. * <p> * <dl> * <dt><b><var>class</var></b> * <dd>This option specifies the fully qualified name of an individual class * to include as a root of the dependency graph. This option can be * specified zero or more times. Each class you specify with this option * needs to be in a package that is defined to be "inside" the graph (as * described further below).</dd> * <p> * <dt><b><var>directory</var></b> * <dd>This option specifies the root directory of a tree of compiled class * files, all of which are to be included as roots of the dependency * graph. This option can be specified zero or more times. The directory * must be one of the directories specified in * <var><b>input_classpath</b></var>, * or a subdirectory of one, and must contain at least one filename * separator character. Each class in the tree needs to be in a package that * is defined to be "inside" the graph (as described further below). * <p> * <dt><b><var>directory</var></b> * <dd>This option specifies the root directory of a tree of compiled class * files that are considered as root for the dependency checking. This option * can be specified zero or more times. The actual behavior depends on whether * the <code>-newdirbehavior</code> options is specified. The directory must * contain at least one filename separator character and be one of the * directories specified in <var><b>input_classpath</b></var>, or when the old * behavior is effective it can be a subdirectory of one of the directories on * the <var><b>input_classpath</b></var>. Each class in the tree needs to be in * a package that is defined to be "inside" the graph (as described further * below). * <p> * When the <code>-newdirbehavior</code> options is set the <code>-inroot</code> * and <code>-outroot</code> options can be used to include/exclude particular * subtrees from the potential set of roots. When the old behavior is effective * all classes are considered as root, but can be excluded through the * <code>-prune</code> option. * <p> * <dl> * <dt><b><code>-inroot</code> <var>package-prefix</var></b> (only valid with * <code>-newdirbehavior</code>) * <dd>Specifies a package namespace to include when selecting roots from the * directory trees. Any classes found in this package or a subpackage of it are * considered as root for the dependency checking, unless they are explicitly * excluded using <code>-out</code>, <code>-skip</code> or <code>-outroot</code> * options. If not specified all found classes are considered roots. This option * can be specified zero or more times. Note that the argument to * <code>-inroot</code> is a package namespace (delimited by "."), not a * directory.</dd> * </dl> * <p> * <dl> * <dt><b><code>-outroot</code> <var>package-prefix</var></b> (only valid with * <code>-newdirbehavior</code>) * <dd>Specifies a package namespace to exclude when selecting roots from the * directory trees. Within the directory trees as specified by the * <code>rootdir</code> element, any classes that are in the given package or a * subpackage of it are not treated as roots. This option can be specified zero * or more times. Note that the argument to <code>-outroot</code> is a package * namespace (delimited by "."), not a directory.</dd> * </dl> * <p> * <dl> * <dt><b><code>-prune</code> <var>package-prefix</var></b> (old behavior only) * <dd>Specifies a package namespace to exclude when selecting roots from * directory trees. Within the directory trees, any classes that are in the * given package or a subpackage of it are not treated as roots. Note that * this option has <i>no</i> effect on whether the classes in question end * up "inside" or "outside" the dependency graph (as defined further below); * it simply controls their use as roots. This option can be specified zero * or more times. Note that the argument to <code>-prune</code> is a package * namespace (delimited by "."), not a directory.</dd> * </dl> * <p> * The <code>-skip</code> option (described further below) can be used to * exclude specific classes from the set of roots. * </dd> * </dl> * <p> * Starting with the root classes, a dependency graph is constructed by * examining the compiled class file for a class, finding all of the classes * it references, and then in turn examining those classes. The extent of * the graph is determined by which packages are defined to be "inside" the * graph and which are defined to be "outside" the graph. If a referenced * class is in a package that is defined to be outside the graph, that class * is not included in the graph, and none of classes that it references are * examined. All of the root classes must be in packages that are defined to * be "inside" the graph. * <p> * The inside and outside packages are specified by using the following * options. Each of these options may be specified zero or more times. Some * variations are illustrated in the <a href="#examples">Examples</a> section * of this page. * <p> * <dl> * <dt><b><code>-in</code> <var>package-prefix</var></b> * <dd>Specifies a namespace of "inside" packages. Any classes in this * package or a subpackage of it are included in the dependency graph (and * hence are to be included in your JAR file), unless they are explicitly * excluded using <code>-out</code> or <code>-skip</code> options. This * option can be specified zero or more times. If no <code>-in</code> * options are specified, the default is that all packages are considered to * be inside packages. Note that the argument to <code>-in</code> is a * namespace, so none of its subpackages need to be specified as an argument * to <code>-in</code>. * <p> * If you use this option, you will likely need to use it multiple * times. For example, if your application classes are in the * <code>com.corp.foo</code> namespace, and you also use some classes in the * <code>com.sun.jini</code> and <code>net.jini</code> namespaces, then you * might specify: * <pre>-in com.corp.foo -in com.sun.jini -in net.jini</pre> * </dd> * <p> * <dt><b><code>-out</code> <var>package-prefix</var></b> * <dd>Specifies a namespace of "outside" packages. Any classes in this * package or a subpackage of it are excluded from the dependency graph (and * hence are to be excluded from your JAR file). This option can be * specified zero or more times. If you specify <code>-in</code> options, * then each <code>-out</code> namespace should be a subspace of some * <code>-in</code> namespace. Note that the argument to <code>-out</code> * is a namespace, so none of its subpackages need to be specified as an * argument to <code>-out</code>. * <p> * If you use this option, you will likely need to use it multiple * times. For example, if you do not specify any <code>-in</code> options, * then all packages are considered inside the graph, including packages * defined in the Java 2 SDK that you typically want to exclude, so you * might exclude them by specifying: * <pre>-out java -out javax</pre> * As another example, if you have specified <code>-in com.corp.foo</code> * but you don't want to include any of the classes in the * <code>com.corp.foo.test</code> or <code>com.corp.foo.qa</code> namespaces * in the dependency graph, then you would specify: * <pre>-out com.corp.foo.test -out com.corp.foo.qa</pre> * </dd> * <p> * <dt><b><code>-skip</code> <var>class</var></b> * <dd>Specifies the fully qualified name of a specific class to exclude * from the dependency graph. This option allows an individual class to be * considered "outside" without requiring the entire package it is defined * in to be considered outside. This option can be specified zero or more * times. * </dd> * <p> * <dt><b><code>-outer</code></b> * <dd>By default, if a static nested class is included in the dependency * graph, all references from that static nested class to its immediate * lexically enclosing class are ignored (except when the static nested class * extends its outer class), to avoid inadvertent inclusion of the enclosing * class. (The default is chosen this way because the compiled class file of a * static nested class always contains a reference to the immediate lexically * enclosing class.) This option causes all such references to be considered * rather than ignored. Note that this option is needed very infrequently.</dd> * </dl> * <p> * <dt><b><code>-newdirbehavior</code></b> * <dd>This option causes the utility to select classes, to serve as root for * the dependency checking, from the directory argument based on the * <code>-inroot</code> and <code>-outroot</code> options specified. When * this option is set subdirectories of the specified directory are no longer * considered as root for finding classes. When this option is not set, the * default, the utility maintains the old behavior with respect to the semantics * for the directories passed in and the <code>-prune</code> option must be * used. You are advised to set this option as there are some edge cases for * which the old behavior won't work as expected, especially when no * <code>-in</code> options are set.</dd> * </dl> * * <a name="output"></a> * <h3>Output Options and Arguments</h3> * * The following options and arguments determine the content and format of * the output produced by this tool. These options do not affect the * dependency graph computation, only the information displayed in the * output as a result of the computation. Most of these options may be * specified multiple times. Some variations are illustrated in the * <a href="#examples">Examples</a> section of this page. * <dl> * <dt><b><code>-edges</code></b> * <dd>By default, the classes which are included in the dependency graph * are displayed in the output. This option specifies that instead, the * classes which are excluded from the dependency graph, but which are * directly referenced by classes in the dependency graph, should be * displayed in the output. These classes form the outside "edges" of the * dependency graph. * <p> * For example, you might exclude classes from the Java 2 SDK from the * dependency graph because you don't want to include them in your JAR file, * but you might be interested in knowing which classes from the Java 2 SDK * are referenced directly by the classes in your JAR file. The * <code>-edges</code> option can be used to display this information. * </dd> * <p> * <dt><b><code>-show</code> <var>package-prefix</var></b> * <dd>Displays the classes that are in the specified package or a * subpackage of it. This option can be specified zero or more times. If no * <code>-show</code> options are specified, the default is that all classes * in the dependency graph are displayed (or all edge classes, if * <code>-edges</code> is specified). Note that the argument to * <code>-show</code> is a namespace, so none of its subpackages need to be * specified as an argument to <code>-show</code>. * <p> * For example, to determine which classes from the Java 2 SDK your * application depends on, you might not specify any <code>-in</code> * options, but limit the output by specifying: * <pre>-show java -show javax</pre></dd> * <p> * <dt><b><code>-hide</code> <var>package-prefix</var></b> * <dd>Specifies a namespace of packages which should not be displayed. Any * classes in this package or a subpackage of it are excluded from the * output. This option can be specified zero or more times. If you specify * <code>-show</code> options, then each <code>-hide</code> namespace should * be a subspace of some <code>-show</code> namespace. Note that the * argument to <code>-hide</code> is a namespace, so none of its subpackages * need to be specified as an argument to <code>-hide</code>. * <p> * For example, to determine which non-core classes from the * <code>net.jini</code> namespace you use, you might specify: * <pre>-show net.jini -hide net.jini.core</pre></dd> * <p> * <dt><b><code>-files</code></b> * <dd>By default, fully qualified class names are displayed, with package * names delimited by ".". This option causes the output to be in filename * format instead, with package names delimited by filename separators and * with ".class" appended. For example, using this option on Microsoft * Windows platforms would produce output in the form of * <code>com\corp\foo\Bar.class</code> instead of * <code>com.corp.foo.Bar</code>. This option should be used to generate * output suitable as input to the <code>jar</code> tool. * <p> * For more information on the <code>jar</code> tool, see: * <ul> * <li><a href="http://java.sun.com/j2se/1.4/docs/tooldocs/solaris/jar.html"> * http://java.sun.com/j2se/1.4/docs/tooldocs/solaris/jar.html</a> * <li><a href="http://java.sun.com/j2se/1.4/docs/tooldocs/windows/jar.html"> * http://java.sun.com/j2se/1.4/docs/tooldocs/windows/jar.html</a> * <li><a href="http://java.sun.com/j2se/1.4/docs/guide/jar/jar.html"> * http://java.sun.com/j2se/1.4/docs/guide/jar/jar.html</a> * </ul> * </dd> * <p> * <dt><b><code>-tell</code> <var>class</var></b> * <dd>Specifies the fully qualified name of a class for which dependency * information is desired. This option causes the tool to display * information about every class in the dependency graph that references the * specified class. This information is sent to the error stream of the * tool, not to the normal output stream. This option can be specified zero * or more times. If this option is used, all other output options are * ignored, and the normal class output is not produced. This option is * useful for debugging. * </dd> * </dl> * * <a name="examples"></a> * <h3>Examples</h3> * * (The examples in this section assume you ran the Apache River release installer * with an "Install Set" selection that created the top-level * <code>classes</code> directory. Alternatively, if you have compiled from * the source code, substitute <code>source/classes</code> for * <code>classes</code> in the examples.) * <p> * The following example computes the classes required for a codebase JAR * file, starting with a smart proxy class and a stub class as roots, and * displays them in filename format. (A more complete example would include * additional roots for leases, registrations, events, and lookup service * attributes, and would exclude platform classes such as those in * <code>jsk-platform.jar</code>.) * <p> * <blockquote><pre> * java -jar <var><b>install_dir</b></var>/lib/classdep.jar \ * -cp <var><b>install_dir</b></var>/classes \ * com.sun.jini.reggie.RegistrarProxy com.sun.jini.reggie.RegistrarImpl_Stub \ * -in com.sun.jini -in net.jini \ * -files * </pre></blockquote> * <p> * The following example computes the classes required for a classpath JAR * file, starting with all of the classes in a directory as roots, and * displays them in class name format. (A more complete example would exclude * platform classes such as those in <code>jsk-platform.jar</code>.) * <p> * <blockquote><pre> * java -jar <var><b>install_dir</b></var>/lib/classdep.jar \ * -cp <var><b>install_dir</b></var>/classes \ * <var><b>install_dir</b></var>/classes/com/sun/jini/reggie \ * -in com.sun.jini -in net.jini * </pre></blockquote> * <p> * The following example computes the <code>com.sun.jini</code> classes used * by a service implementation, and displays the <code>net.jini</code> * classes that are immediately referenced by those classes. * <p> * <blockquote><pre> * java -jar <var><b>install_dir</b></var>/lib/classdep.jar \ * -cp <var><b>install_dir</b></var>/classes \ * com.sun.jini.reggie.RegistrarImpl \ * -in com.sun.jini \ * -edges \ * -show net.jini * </pre></blockquote> * <p> * The following example computes all of the classes used by a service * implementation that are not part of the Java 2 SDK, and displays the * classes that directly reference the class <code>java.awt.Image</code>. * <p> * <blockquote><pre> * java -jar <var><b>install_dir</b></var>/lib/classdep.jar \ * -cp <var><b>install_dir</b></var>/classes \ * com.sun.jini.reggie.RegistrarImpl \ * -out java -out javax \ * -tell java.awt.Image * </pre></blockquote> * <p> * The following example computes all of the classes to include in * <code>jini-ext.jar</code> and displays them in filename format. Note * that both <code>-out</code> and <code>-prune</code> options are needed * for the <code>net.jini.core</code> namespace; <code>-out</code> to * exclude classes from the dependency graph, and <code>-prune</code> to * prevent classes from being used as roots. * <p> * <blockquote><pre> * java -jar <var><b>install_dir</b></var>/lib/classdep.jar \ * -cp <var><b>install_dir</b></var>/classes \ * -in net.jini -out net.jini.core -in com.sun.jini \ * <var><b>install_dir</b></var>/classes/net/jini -prune net.jini.core \ * -files * </pre></blockquote> * * @author Sun Microsystems, Inc. */ public class ClassDep { /** * Container for all the classes that we have seen. */ private final HashSet seen = new HashSet(); /** * Object used to load our classes. */ private Env env; /** * If true class names are printed using * the system's File.separator, else the * fully qualified class name is printed. */ private boolean files = false; /** * Set of paths to find class definitions in order to determine * dependencies. */ private String classpath = ""; /** * Flag to determine whether there is interest * in dependencies that go outside the set of * interested classes. If false then outside, * references are ignored, if true they are noted. * i.e, if looking only under <code>net.jini.core.lease</code> * a reference to a class in <code>net.jini</code> is found it * will be noted if the flag is set to true, else * it will be ignored. <p> * <b>Note:</b> these edge case dependencies must be * included in the classpath in order to find their * definitions. */ private boolean edges = false; /** * Static inner classes have a dependency on their outer * parent class. Because the parent class may be really * big and may pull other classes along with it we allow the * choice to ignore the parent or not. If the flag is set to * true we pull in the parent class. If it is false we don't * look at the parent. The default is is to not include the * parent. <p> * <b>Note:</b> This is an optimization for those who plan * on doing work with the output of this utility. It does * not impact this utility, but the work done on its * generated output may have an impact. */ private boolean ignoreOuter = true; /** * Package set that we have interest to work in. */ private final ArrayList inside = new ArrayList(); /** * Package set to not work with. This is useful if * there is a subpackage that needs to be ignored. */ private final ArrayList outside = new ArrayList(); /** * Class set to look at for dependencies. These are * fully qualified names, ie, net.jini.core.lease.Lease. * This is a subset of the values in * <code>inside</code>. */ private final ArrayList classes = new ArrayList(); /** * Set of directories to find dependencies in. */ private final ArrayList roots = new ArrayList(); /** * Set of packages to skip over in the processing of dependencies. * This can be used in conjunction with <em>-out</em> option. */ private final ArrayList prunes = new ArrayList(); /** * Indicates whether the root directories specified for finding classes * for dependency checking must be traversed in the 'old' way, or that the * new behavior must be effective. */ private boolean newRootDirBehavior; /** * Set of packages to include when classes are found through the specified * root directories. */ private final ArrayList insideRoots = new ArrayList(); /** * Set of packages to exclude when classes are found through the specified * root directories. */ private final ArrayList outsideRoots = new ArrayList(); /** * Set of classes to skip over in the processing of dependencies. */ private final ArrayList skips = new ArrayList(); /** * Given a specific fully qualified classes, what other classes * in the roots list depend on it. This is more for debugging * purposes rather then normal day to day usage. */ private final ArrayList tells = new ArrayList(); /** * Only display found dependencies that fall under the provided * <code>roots</code> subset. */ private final ArrayList shows = new ArrayList(); /** * Suppress display of found dependencies that are under * the provided package prefixes subset. */ private final ArrayList hides = new ArrayList(); /** * Container for found dependency classes. */ private final SortedSet results = new TreeSet(); /** * Indicates whether a failure has been encountered during deep dependency * checking. */ private boolean failed; /** * No argument constructor. The user must fill in the * appropriate fields prior to asking for the processing * of dependencies. */ public ClassDep() { } /** * Constructor that takes command line arguments and fills in the * appropriate fields. See the description of this class * for a list and description of the acceptable arguments. */ public ClassDep(String[] cmdLine){ setupOptions(cmdLine); } /** * Take the given argument and add it to the provided container. * We make sure that each inserted package-prefix is unique. For * example if we had the following packages: * <ul> * <li>a.b * <li>a.bx * <li>a.b.c * </ul> * Looking for <code>a.b</code> should not match * <code>a.bx</code> and <code>a.b</code>, * just <code>a.b</code>. * * @param arg the package-prefix in string form * @param elts container to add elements to * */ private static void add(String arg, ArrayList elts) { if (!arg.endsWith(".")) arg = arg + '.'; if (".".equals(arg)) arg = null; elts.add(arg); } /** * See if the provided name is covered by package prefixes. * * @param n the name * @param elts the list of package prefixes * * @return the length of the first matching package prefix * */ private static int matches(String n, ArrayList elts) { for (int i = 0; i < elts.size(); i++) { String elt = (String)elts.get(i); /* * If we get a null element then see if we are looking * at an anonymous package. */ if (elt == null) { int j = n.indexOf('.'); /* * If we did not find a dot, or we have a space * at the beginning then we have an anonymous package. */ if (j < 0 || n.charAt(j + 1) == ' ') return 0; } else if (n.startsWith(elt)) return elt.length(); } return -1; } /** * See if a name is covered by in but not excluded by out. * * @param n the name * @param in the package prefixes to include * @param out the package prefixes to exclude * @return true if covered by in but not excluded by out */ private static boolean matches(String n, ArrayList in, ArrayList out) { int i = in.isEmpty() ? 0 : matches(n, in); return i >= 0 && matches(n, out) < i; } /** * Recursively traverse a given path, finding all the classes that * make up the set to work with. We take into account skips, * prunes, and out sets defined. * <p> * This implementation is here to maintain the old behavior with regard * to how root directories were interpreted. * * @param path path to traverse down from */ private void traverse(String path) { String apath = path; /* * We append File.separator to make sure that the path * is unique for the matching that we are going to do * next. */ if (!apath.startsWith(File.separator)) apath = File.separator + apath; for (int i = 0; i < prunes.size(); i++) { /* * If we are on a root path that needs to be * pruned leave this current recursive thread. */ if (apath.endsWith((String)prunes.get(i))) return; } /* * Get the current list of files at the current directory * we are in. If there are no files then leave this current * recursive thread. */ String[] files = new File(path).list(); if (files == null) return; outer: /* * Now, take the found list of files and iterate over them. */ for (int i = 0; i < files.length; i++) { String file = files[i]; /* * Now see if we have a ".class" file. * If we do not then we lets call ourselves again. * The assumption here is that we have a directory. If it * is a class file we would have already been throw out * by the empty directory contents test above. */ if (!file.endsWith(".class")) { traverse(path + File.separatorChar + file); } else { /* * We have a class file, so remove the ".class" from it * using the pattern: * * directory_name + File.Separator + filename = ".class" * * At this point the contents of the skip container follow * the pattern of: * * "File.Separator+DirectoryPath" * * with dots converted to File.Separators */ file = apath + File.separatorChar + file.substring(0, file.length() - 6); /* * See if there are any class files that need to be skipped. */ for (int j = 0; j < skips.size(); j++) { String skip = (String)skips.get(j); int k = file.indexOf(skip); if (k < 0) continue;//leave this current loop. k += skip.length(); /* * If we matched the entire class or if we have * a class with an inner class, skip it and go * on to the next outer loop. */ if (file.length() == k || file.charAt(k) == '$') continue outer; } /* * things to do: * prune when outside. * handle inside when its empty. * * Now see if we have classes within our working set "in". * If so add them to our working list "classes". */ for (int j = 0; j < inside.size(); j++) { if (inside.get(j) == null) continue; int k = file.indexOf(File.separatorChar + ((String)inside.get(j)).replace( '.', File.separatorChar)); if (k >= 0) { /* * Insert the class and make sure to replace * File.separators into dots. */ classes.add(file.substring(k + 1).replace( File.separatorChar, '.')); } } } } } /** * Recursively traverse a given path, finding all the classes that make up * the set of classes to work with. We take into account inroot and outroot * sets, skips, and the in and out sets defined. * * @param path path to traverse down from * @param rootPath path to the directory that serves as the root for the * class files found, any path component below the root is part of * the full qualified name of the class */ private void traverse(String path, String rootPath) { // get the current list of files at the current directory we are in. If // there are no files then leave this current recursive thread. String[] files = new File(path).list(); if (files == null) return; // determine the package name in File.Separators notation String packageName = path.substring(rootPath.length(), path.length()) + File.separatorChar; outer: //take the found list of files and iterate over them for (int i = 0; i < files.length; i++) { String file = files[i]; // see if we have a ".class" file. If not then we call ourselves // again, assuming it is a directory, if not the call will return. if (!file.endsWith(".class")) { traverse(path + File.separatorChar + file, rootPath); } else { // when we have in roots defined verify whether we are inside if (!insideRoots.isEmpty()) { boolean matched = false; for (int j = 0; j < insideRoots.size(); j++) { if (packageName.startsWith( (String) insideRoots.get(j))) { matched = true; break; } } if (!matched) { continue; } } // when we have out roots and we are at this level outside we // can break the recursion if (!outsideRoots.isEmpty()) { for (int j = 0; j < outsideRoots.size(); j++) { if (packageName.startsWith( (String) outsideRoots.get(j))) { return; } } } // determine the fully qualified class name, but with dots // converted to File.Separators and starting with a // File.Separators as well String className = packageName + file.substring(0, file.length() - 6); // see if there are any class files that need to be skipped, the // skip classes are in the above notation as well for (int j = 0; j < skips.size(); j++) { String skip = (String) skips.get(j); if (!className.startsWith(skip)) { continue; } // if we matched the entire class or if we have a class with // an inner class, skip it and go on to the next outer loop if (className.length() == skip.length() || className.charAt(skip.length()) == '$') continue outer; } // we found a class that satisfy all the criteria, convert it // to the proper notation classes.add(className.substring(1).replace(File.separatorChar, '.')); } } } /** * Depending on the part of the class file * that we are on the class types that we are * looking for can come in several flavors. * They can be embedded in arrays, they can * be labeled as Identifiers, or they can be * labeled as Types. This method handles * Types referenced by Identifiers. It'll take * the Type and proceed to get its classname * and then continue with the processing it * for dependencies. */ private void process(Identifier from, Type type) { while (type.isType(Constants.TC_ARRAY)) type = type.getElementType(); if (type.isType(Constants.TC_CLASS)) process(from, type.getClassName()); } /** * Depending on the part of the class file * that we are on the class types that we are * looking for can come in several flavors. * This method handles Identifiers and * Identifiers referenced from other Identifiers. * <p> * Several actions happen here with the goal of * generating the list of dependencies within the domain * space provided by the user. * These actions are: * <ul> * <li> printing out "-tell" output if user asks for it. * <li> extracting class types from the class file. * <ul> * <li> either in arrays or by * <li> themselves * </ul> * <li> noting classes we have already seen. * <li> traversing the remainder of the class file. * <li> resolving and looking for dependencies in * inner classes. * <li> saving found results for later use. * </ul> * * @param from the Identifier referenced from <code>id</code> * @param id the Identifier being looked at */ private void process(Identifier from, Identifier id) { /* * If <code>from</code> is not null see if the "id" that * references it is in our "tells" container. If there * is a match show the class. This is for debugging purposes, * in case you want to find out what classes use a particular class. */ if (from != null) { for (int i = 0; i < tells.size(); i++) { if (id.toString().equals((String)tells.get(i))) { if (tells.size() > 1) print("classdep.cause", id, from); else print("classdep.cause1", from); } } } /* * Having taken care of the "-tells" switch, lets * proceed with the rest by getting the id's string * representation. */ String n = id.toString(); /* * Remove any array definitions so we can get to the * fully qualified class name that we are seeking. */ if (n.charAt(0) == '[') { int i = 1; while (n.charAt(i) == '[') i++; /* * Now that we have removed possible array information * see if we have a Class definition e.g Ljava/lang/Object;. * If so, remove the 'L' and ';' and call ourselves * with this newly cleaned up Identifier. */ if (n.charAt(i) == 'L') process(from, Identifier.lookup(n.substring(i + 1, n.length() - 1))); /* * Pop out of our recursive path, since the real work * is being down in another recursive thread. */ return; } /* * If we have already seen the current Identifier, end this * thread of recursion. */ if (seen.contains(id)) return; /* * See if we have an empty set OR the Identifier is in our * "inside" set and the matched Identifier is not on the * "outside" set. * * If we are not in the "inside" set and we are not asking * for edges then pop out of this recursive thread. */ boolean in = matches(n, inside, outside); if (!in && !edges) return; /* * We have an actual Identifier, so at this point mark it * as seen, so we don't create another recursive thread if * we see it again. */ seen.add(id); /* * This is the test that decides whether this current * Identifier needs to be added to the list of dependencies * to save. * * "in" can be true in the following cases: * <ul> * <li>the in set is empty * <li>the Identifier is in the "in" set and not on the "out" set. * </ul> */ if (in != edges && matches(n, shows, hides)) results.add(Type.mangleInnerType(id).toString()); /* * If we are not in the "inside" set and we want edges * pop out of our recursive thread. */ if (!in && edges) return; /* * At this point we have either added an Identifier * to our save list, or we have not. In either case * we need get the package qualified name of this so * we can see if it has any nested classes. */ id = env.resolvePackageQualifiedName(id); BinaryClass cdef; try { cdef = (BinaryClass)env.getClassDefinition(id); cdef.loadNested(env); } catch (ClassNotFound e) { failed = true; print("classdep.notfound", id); return; } catch (IllegalArgumentException e) { failed = true; print("classdep.illegal", id, e.getMessage()); return; } catch (Exception e) { failed = true; print("classdep.failed", id); e.printStackTrace(); return; } /* * If the user asked to keep the outer parent for an * inner class then we'll get the list of dependencies * the inner class may have and iterate over then by * "processing" them as well. */ Identifier outer = null; if (ignoreOuter && cdef.isInnerClass() && cdef.isStatic()) outer = cdef.getOuterClass().getName(); for (Enumeration deps = cdef.getDependencies(); deps.hasMoreElements(); ) { ClassDeclaration cd = (ClassDeclaration) deps.nextElement(); /* * If we dont' want the outer parent class of an inner class * make this comparison, except when it is clear the outer class is * the super class of the static nested class. */ if (outer != cd.getName() || (outer != null && cdef.getSuperClass() == cd)) { process(id, cd.getName()); } } /* * Now we are going to walk the rest of the class file and see * if we can find any other class references. */ for (MemberDefinition mem = cdef.getFirstMember(); mem != null; mem = mem.getNextMember()) { if (mem.isVariable()) { process(id, mem.getType()); } else if (mem.isMethod() || mem.isConstructor()) { Type[] args = mem.getType().getArgumentTypes(); for (int i = 0; i < args.length; i++) { process(id, args[i]); } process(id, mem.getType().getReturnType()); } } } private static class Compare implements Comparator { public int compare(Object o1, Object o2) { if (o1 == null) return o2 == null ? 0 : 1; else return o2 == null ? -1 : ((Comparable) o2).compareTo(o1); } } /** * Method that takes the user provided switches that * logically define the domain in which to look for * dependencies. * <p> * Whether a failure has occurred during computing the dependent classes * can be found out with a call to {@link #hasFailed()}. * * @return array containing the dependent classes found in the format as * specified by the options passed in */ public String[] compute() { failed = false; if (!newRootDirBehavior) { if (!insideRoots.isEmpty()) { failed = true; print("classdep.invalidoption", "-newdirbehavior", "-inroot"); } if (!outsideRoots.isEmpty()) { failed = true; print("classdep.invalidoption", "-newdirbehavior", "-outroot"); } if (failed) { return new String[0]; } } /* sort ins and outs, longest first */ Comparator c = new Compare(); Collections.sort(inside, c); Collections.sort(outside, c); Collections.sort(shows, c); Collections.sort(hides, c); /* * Create the environment from which we are going to be * loading classes from. */ env = new Env(classpath); /* * Traverse the roots i.e the set of handed directories. */ for (int i = 0; i < roots.size(); i++) { /* * Get the classes that we want do to dependency checking on. */ if (newRootDirBehavior) { traverse((String)roots.get(i), (String)roots.get(i)); } else { traverse((String)roots.get(i)); } } for (int i = 0; i < classes.size(); i++) { process(null, Identifier.lookup((String)classes.get(i))); } if (!tells.isEmpty()) return new String[0]; return (String[])results.toArray(new String[results.size()]); } /** * Print out the usage for this utility. */ public static void usage() { print("classdep.usage", null); } /** * Set the classpath to use for finding our class definitions. */ public void setClassPath(String classpath) { this.classpath = classpath; } /** * Determines how to print out the fully qualified * class names. If <code>true</code> it will use * <code>File.separator</code>, else <code>.</code>'s * will be used. * If not set the default is <code>false</code>. */ public void setFiles(boolean files) { this.files = files; } /** * Add an entry into the set of package prefixes that * are to remain hidden from processing. */ public void addHides(String packagePrefix) { add(packagePrefix, hides); } /** * Add an entry into the working set of package prefixes * that will make up the working domain space. */ public void addInside(String packagePrefix) { add(packagePrefix, inside); } /** * Determines whether to include package references * that lie outside the declared set of interest. * <p> * If true edges will be processed as well, else * they will be ignored. If not set the default * will be <code>false</code>. * <p> * <b>Note:</b> These edge classes must included * in the classpath for this utility. */ public void setEdges(boolean edges) { this.edges = edges; } /** * Add an entry into the set of package prefixes * that will bypassed during dependency checking. * These entries should be subsets of the contents * on the inside set. */ public void addOutside(String packagePrefix) { add(packagePrefix, outside); } /** * Add an entry into the set of package prefixes * that will be skipped as part of the dependency * generation. * <p> * This method has no impact if the new behavior is effective for the * interpretation of the root directories for finding class files to * include for dependency checking. */ public void addPrune(String packagePrefix) { String arg = packagePrefix; if (arg.endsWith(".")) arg = arg.substring(0, arg.length() - 1); /* * Convert dots into File.separator for later usage. */ arg = File.separator + arg.replace('.', File.separatorChar); prunes.add(arg); } /** * Controls whether the behavior for finding class files in the specified * directories, if any, must be based on the old behavior (the default) or * the new behavior that solves some of the problems with the old behavior. */ public void setRootDirBehavior(boolean newBehavior) { newRootDirBehavior = newBehavior; } /** * Adds an entry into the set of package prefixes for which classes found * through the specified root directories will be considered for dependency * generation. * <p> * Adding entries without a call to {@link #setRootDirBehavior(boolean)} * with <code>true</code> as the argument will cause {@link #compute()} to * fail. */ public void addInsideRoot(String packagePrefix) { String arg = packagePrefix; if (arg.endsWith(".")) arg = arg.substring(0, arg.length() - 1); /* * Convert dots into File.separator for later usage. */ if (arg.trim().length() == 0) arg = File.separator; else arg = File.separator + arg.replace('.', File.separatorChar) + File.separator; insideRoots.add(arg); } /** * Adds an entry into the set of package prefixes for which classes found * through the specified root directories, and that are part of the inside * root namespace, will be skipped as part of the dependency generation. * <p> * Adding entries without a call to {@link #setRootDirBehavior(boolean)} * with <code>true</code> as the argument will cause {@link #compute()} to * fail. */ public void addOutsideRoot(String packagePrefix) { String arg = packagePrefix; if (arg.endsWith(".")) arg = arg.substring(0, arg.length() - 1); /* * Convert dots into File.separator for later usage. */ if (arg.trim().length() == 0) arg = File.separator; else arg = File.separator + arg.replace('.', File.separatorChar) + File.separator; outsideRoots.add(arg); } /** * Add an entry into the set of package prefixes * that we want to display. * This applies only to the final output, so this * set should be a subset of the inside set with * edges, if that was indicated. */ public void addShow(String packagePrefix) { add(packagePrefix, shows); } /** * Add an entry into the set of classes that * should be skipped during dependency generation. */ public void addSkip(String packagePrefix){ String arg = packagePrefix; if (arg.endsWith(".")) arg = arg.substring(0, arg.length() - 1); else seen.add(Identifier.lookup(arg)); /* * Convert dots into File.separator for later usage. */ arg = File.separator + arg.replace('.', File.separatorChar); skips.add(arg); } /** * Add an entry in to the set of classes whose dependents * that lie with the inside set are listed. This in * the converse of the rest of the utility and is meant * more for debugging purposes. */ public void addTells(String className) { tells.add(className); } /** * Add an entry into the set of directories to * look under for the classes that fall within * the working domain space as defined by the * intersection of the following sets: * inside,outside,prune,show, and hide. */ public void addRoots(String rootName) { if (rootName.endsWith(File.separator)) //remove trailing File.separator rootName = rootName.substring(0, rootName.length() - 1); //these are directories. roots.add(rootName); } /** * Add an entry into the set of classes that * dependencies are going to be computed on. */ public void addClasses(String className) { classes.add(className); } /** * If true classnames will be separated using * File.separator, else it will use dots. */ public boolean getFiles() { return files; } /** * Accessor method for the found dependencies. */ public String[] getResults() { String[] vals = (String[])results.toArray(new String[results.size()]); Arrays.sort(vals); return vals; } /** * Indicates whether computing the dependent classes as result of the last * call to {@link #compute()} resulted in one or more failures. * * @return <code>true</code> in case a failure has happened, such as a * class not being found, <code>false</code> otherwise */ public boolean hasFailed() { return failed; } /** * Convenience method for initializing an instance with specific * command line arguments. See the description of this class * for a list and description of the acceptable arguments. */ public void setupOptions(String[] args) { for (int i = 0; i < args.length ; i++ ) { String arg = args[i]; - if (args.equals("-newdirbehavior")) { + if (arg.equals("-newdirbehavior")) { newRootDirBehavior = true; } else if (arg.equals("-cp")) { i++; setClassPath(args[i]); } else if (arg.equals("-files")) { setFiles(true); } else if (arg.equals("-hide")) { i++; addHides(args[i]); } else if (arg.equals("-in")) { i++; addInside(args[i]); } else if (arg.equals("-edges")) { setEdges(true); } else if (arg.equals("-out")) { i++; addOutside(args[i]); } else if (arg.equals("-outer")) { ignoreOuter = false; } else if (arg.equals("-prune")) { i++; addPrune(args[i]); } else if (arg.equals("-inroot")) { i++; addInsideRoot(args[i]); } else if (arg.equals("-outroot")) { i++; addOutsideRoot(args[i]); } else if (arg.equals("-show")) { i++; addShow(args[i]); } else if (arg.equals("-skip")) { i++; addSkip(args[i]); } else if (arg.equals("-tell")) { i++; addTells(args[i]); } else if (arg.indexOf(File.separator) >= 0) { addRoots(arg); } else if (arg.startsWith("-")) { usage(); } else { addClasses(arg); } } } private static ResourceBundle resources; private static boolean resinit = false; /** * Get the strings from our resource localization bundle. */ private static synchronized String getString(String key) { if (!resinit) { resinit = true; try { resources = ResourceBundle.getBundle ("com.sun.jini.tool.resources.classdep"); } catch (MissingResourceException e) { e.printStackTrace(); } } if (resources != null) { try { return resources.getString(key); } catch (MissingResourceException e) { } } return null; } /** * Print out string according to resourceBundle format. */ private static void print(String key, Object val) { String fmt = getString(key); if (fmt == null) fmt = "no text found: \"" + key + "\" {0}"; System.err.println(MessageFormat.format(fmt, new Object[]{val})); } /** * Print out string according to resourceBundle format. */ private static void print(String key, Object val1, Object val2) { String fmt = getString(key); if (fmt == null) fmt = "no text found: \"" + key + "\" {0} {1}"; System.err.println(MessageFormat.format(fmt, new Object[]{val1, val2})); } /** * Command line interface for generating the list of classes that * a set of classes depends upon. See the description of this class * for a list and description of the acceptable arguments. */ public static void main(String[] args) { if (args.length == 0) { usage(); return; } ClassDep dep = new ClassDep(); //boolean files = false; dep.setupOptions(args); String[] vals = dep.compute(); for (int i = 0; i < vals.length; i++) { if (dep.getFiles()) System.out.println(vals[i].replace('.', File.separatorChar) + ".class"); else System.out.println(vals[i]); } } /** * Private class to load classes, resolve class names and report errors. * * @see sun.tools.java.Environment */ private static class Env extends Environment { private final ClassPath noPath = new ClassPath(""); private final ClassPath path; private final HashMap packages = new HashMap(); private final HashMap classes = new HashMap(); public Env(String classpath) { for (StringTokenizer st = new StringTokenizer(System.getProperty("java.ext.dirs"), File.pathSeparator); st.hasMoreTokens(); ) { String dir = st.nextToken(); String[] files = new File(dir).list(); if (files != null) { if (!dir.endsWith(File.separator)) { dir += File.separator; } for (int i = files.length; --i >= 0; ) { classpath = dir + files[i] + File.pathSeparator + classpath; } } } path = new ClassPath(System.getProperty("sun.boot.class.path") + File.pathSeparator + classpath); } /** * We don't use flags so we override Environments and * simply return 0. */ public int getFlags() { return 0; } /** * Take the identifier and see if the class that represents exists. * <code>true</code> if the identifier is found, <code>false</code> * otherwise. */ public boolean classExists(Identifier id) { if (id.isInner()) id = id.getTopName(); Type t = Type.tClass(id); try { ClassDeclaration c = (ClassDeclaration)classes.get(t); if (c == null) { Package pkg = getPackage(id.getQualifier()); return pkg.getBinaryFile(id.getName()) != null; } return c.getName().equals(id); } catch (IOException e) { return false; } } public ClassDeclaration getClassDeclaration(Identifier id) { return getClassDeclaration(Type.tClass(id)); } public ClassDeclaration getClassDeclaration(Type t) { ClassDeclaration c = (ClassDeclaration)classes.get(t); if (c == null) { c = new ClassDeclaration(t.getClassName()); classes.put(t, c); } return c; } public Package getPackage(Identifier pkg) throws IOException { Package p = (Package)packages.get(pkg); if (p == null) { p = new Package(noPath, path, pkg); packages.put(pkg, p); } return p; } BinaryClass loadFile(ClassFile file) throws IOException { DataInputStream in = new DataInputStream(new BufferedInputStream( file.getInputStream())); try { return BinaryClass.load(new Environment(this, file), in, ATT_ALLCLASSES); } catch (ClassFormatError e) { throw new IllegalArgumentException("ClassFormatError: " + file.getPath()); } catch (Exception e) { e.printStackTrace(); return null; } finally { in.close(); } } /** * Overridden method from Environment */ public void loadDefinition(ClassDeclaration c) { Identifier id = c.getName(); if (c.getStatus() != CS_UNDEFINED) throw new IllegalArgumentException("No file for: " + id); Package pkg; try { pkg = getPackage(id.getQualifier()); } catch (IOException e) { throw new IllegalArgumentException("IOException: " + e.getMessage()); } ClassFile file = pkg.getBinaryFile(id.getName()); if (file == null) throw new IllegalArgumentException("No file for: " + id.getName()); BinaryClass bc; try { bc = loadFile(file); } catch (IOException e) { throw new IllegalArgumentException("IOException: " + e.getMessage()); } if (bc == null) throw new IllegalArgumentException("No class in: " + file); if (!bc.getName().equals(id)) throw new IllegalArgumentException("Wrong class in: " + file); c.setDefinition(bc, CS_BINARY); bc.loadNested(this, ATT_ALLCLASSES); } private static ResourceBundle resources; private static boolean resinit = false; /** * Get the strings from javac resource localization bundle. */ private static synchronized String getString(String key) { if (!resinit) { try { resources = ResourceBundle.getBundle ("sun.tools.javac.resources.javac"); resinit = true; } catch (MissingResourceException e) { e.printStackTrace(); } } if (key.startsWith("warn.")) key = key.substring(5); try { return resources.getString("javac.err." + key); } catch (MissingResourceException e) { return null; } } public void error(Object source, long where, String err, Object arg1, Object arg2, Object arg3) { String fmt = getString(err); if (fmt == null) fmt = "no text found: \"" + err + "\" {0} {1} {2}"; output(MessageFormat.format(fmt, new Object[]{arg1, arg2, arg3})); } public void output(String msg) { System.err.println(msg); } } }
true
false
null
null
diff --git a/src/com/android/exchange/EasSyncService.java b/src/com/android/exchange/EasSyncService.java index 7805cb5..410d716 100644 --- a/src/com/android/exchange/EasSyncService.java +++ b/src/com/android/exchange/EasSyncService.java @@ -1,1859 +1,1862 @@ /* * Copyright (C) 2008-2009 Marc Blank * Licensed to 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.exchange; import com.android.email.SecurityPolicy; import com.android.email.SecurityPolicy.PolicySet; import com.android.email.mail.Address; import com.android.email.mail.AuthenticationFailedException; import com.android.email.mail.MeetingInfo; import com.android.email.mail.MessagingException; import com.android.email.mail.PackedString; import com.android.email.provider.EmailContent.Account; import com.android.email.provider.EmailContent.AccountColumns; import com.android.email.provider.EmailContent.Attachment; import com.android.email.provider.EmailContent.AttachmentColumns; import com.android.email.provider.EmailContent.HostAuth; import com.android.email.provider.EmailContent.Mailbox; import com.android.email.provider.EmailContent.MailboxColumns; import com.android.email.provider.EmailContent.Message; import com.android.email.service.EmailServiceProxy; import com.android.email.service.EmailServiceStatus; import com.android.exchange.adapter.AbstractSyncAdapter; import com.android.exchange.adapter.AccountSyncAdapter; import com.android.exchange.adapter.CalendarSyncAdapter; import com.android.exchange.adapter.ContactsSyncAdapter; import com.android.exchange.adapter.EmailSyncAdapter; import com.android.exchange.adapter.FolderSyncParser; import com.android.exchange.adapter.MeetingResponseParser; import com.android.exchange.adapter.PingParser; import com.android.exchange.adapter.ProvisionParser; import com.android.exchange.adapter.Serializer; import com.android.exchange.adapter.Tags; import com.android.exchange.adapter.Parser.EasParserException; import com.android.exchange.utility.CalendarUtilities; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import org.xmlpull.v1.XmlSerializer; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Entity; import android.database.Cursor; import android.os.Bundle; import android.os.RemoteException; import android.os.SystemClock; import android.provider.Calendar.Attendees; import android.provider.Calendar.Events; import android.util.Log; import android.util.Xml; import android.util.base64.Base64; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URLEncoder; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.HashMap; public class EasSyncService extends AbstractSyncService { private static final String EMAIL_WINDOW_SIZE = "5"; public static final String PIM_WINDOW_SIZE = "5"; private static final String WHERE_ACCOUNT_KEY_AND_SERVER_ID = MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SERVER_ID + "=?"; private static final String WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING = MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SYNC_INTERVAL + '=' + Mailbox.CHECK_INTERVAL_PING; private static final String AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX = " AND " + MailboxColumns.SYNC_INTERVAL + " IN (" + Mailbox.CHECK_INTERVAL_PING + ',' + Mailbox.CHECK_INTERVAL_PUSH + ") AND " + MailboxColumns.TYPE + "!=\"" + Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + '\"'; private static final String WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX = MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.SYNC_INTERVAL + '=' + Mailbox.CHECK_INTERVAL_PUSH_HOLD; static private final int CHUNK_SIZE = 16*1024; static private final String PING_COMMAND = "Ping"; static private final int COMMAND_TIMEOUT = 20*SECONDS; // Define our default protocol version as 2.5 (Exchange 2003) static private final String DEFAULT_PROTOCOL_VERSION = "2.5"; static private final String AUTO_DISCOVER_SCHEMA_PREFIX = "http://schemas.microsoft.com/exchange/autodiscover/mobilesync/"; static private final String AUTO_DISCOVER_PAGE = "/autodiscover/autodiscover.xml"; static private final int AUTO_DISCOVER_REDIRECT_CODE = 451; static public final String EAS_12_POLICY_TYPE = "MS-EAS-Provisioning-WBXML"; static public final String EAS_2_POLICY_TYPE = "MS-WAP-Provisioning-XML"; /** * We start with an 8 minute timeout, and increase/decrease by 3 minutes at a time. There's * no point having a timeout shorter than 5 minutes, I think; at that point, we can just let * the ping exception out. The maximum I use is 17 minutes, which is really an empirical * choice; too long and we risk silent connection loss and loss of push for that period. Too * short and we lose efficiency/battery life. * * If we ever have to drop the ping timeout, we'll never increase it again. There's no point * going into hysteresis; the NAT timeout isn't going to change without a change in connection, * which will cause the sync service to be restarted at the starting heartbeat and going through * the process again. */ static private final int PING_MINUTES = 60; // in seconds static private final int PING_FUDGE_LOW = 10; static private final int PING_STARTING_HEARTBEAT = (8*PING_MINUTES)-PING_FUDGE_LOW; static private final int PING_MIN_HEARTBEAT = (5*PING_MINUTES)-PING_FUDGE_LOW; static private final int PING_MAX_HEARTBEAT = (17*PING_MINUTES)-PING_FUDGE_LOW; static private final int PING_HEARTBEAT_INCREMENT = 3*PING_MINUTES; static private final int PING_FORCE_HEARTBEAT = 2*PING_MINUTES; static private final int PROTOCOL_PING_STATUS_COMPLETED = 1; // Fallbacks (in minutes) for ping loop failures static private final int MAX_PING_FAILURES = 1; static private final int PING_FALLBACK_INBOX = 5; static private final int PING_FALLBACK_PIM = 25; // MSFT's custom HTTP result code indicating the need to provision static private final int HTTP_NEED_PROVISIONING = 449; // Reasonable default public String mProtocolVersion = DEFAULT_PROTOCOL_VERSION; public Double mProtocolVersionDouble; protected String mDeviceId = null; private String mDeviceType = "Android"; private String mAuthString = null; private String mCmdString = null; public String mHostAddress; public String mUserName; public String mPassword; private boolean mSsl = true; private boolean mTrustSsl = false; public ContentResolver mContentResolver; private String[] mBindArguments = new String[2]; private ArrayList<String> mPingChangeList; private HttpPost mPendingPost = null; // The ping time (in seconds) private int mPingHeartbeat = PING_STARTING_HEARTBEAT; // The longest successful ping heartbeat private int mPingHighWaterMark = 0; // Whether we've ever lowered the heartbeat private boolean mPingHeartbeatDropped = false; // Whether a POST was aborted due to watchdog timeout private boolean mPostAborted = false; // Whether or not the sync service is valid (usable) public boolean mIsValid = true; public EasSyncService(Context _context, Mailbox _mailbox) { super(_context, _mailbox); mContentResolver = _context.getContentResolver(); if (mAccount == null) { mIsValid = false; return; } HostAuth ha = HostAuth.restoreHostAuthWithId(_context, mAccount.mHostAuthKeyRecv); if (ha == null) { mIsValid = false; return; } mSsl = (ha.mFlags & HostAuth.FLAG_SSL) != 0; mTrustSsl = (ha.mFlags & HostAuth.FLAG_TRUST_ALL_CERTIFICATES) != 0; } private EasSyncService(String prefix) { super(prefix); } public EasSyncService() { this("EAS Validation"); } @Override public void ping() { userLog("Alarm ping received!"); synchronized(getSynchronizer()) { if (mPendingPost != null) { userLog("Aborting pending POST!"); mPostAborted = true; mPendingPost.abort(); } } } @Override public void stop() { mStop = true; synchronized(getSynchronizer()) { if (mPendingPost != null) { mPendingPost.abort(); } } } /** * Determine whether an HTTP code represents an authentication error * @param code the HTTP code returned by the server * @return whether or not the code represents an authentication error */ protected boolean isAuthError(int code) { return (code == HttpStatus.SC_UNAUTHORIZED) || (code == HttpStatus.SC_FORBIDDEN); } /** * Determine whether an HTTP code represents a provisioning error * @param code the HTTP code returned by the server * @return whether or not the code represents an provisioning error */ protected boolean isProvisionError(int code) { return (code == HTTP_NEED_PROVISIONING) || (code == HttpStatus.SC_FORBIDDEN); } private void setupProtocolVersion(EasSyncService service, Header versionHeader) { String versions = versionHeader.getValue(); if (versions != null) { if (versions.contains("12.0")) { service.mProtocolVersion = "12.0"; } service.mProtocolVersionDouble = Double.parseDouble(service.mProtocolVersion); if (service.mAccount != null) { service.mAccount.mProtocolVersion = service.mProtocolVersion; } } } @Override public void validateAccount(String hostAddress, String userName, String password, int port, boolean ssl, boolean trustCertificates, Context context) throws MessagingException { try { userLog("Testing EAS: ", hostAddress, ", ", userName, ", ssl = ", ssl ? "1" : "0"); EasSyncService svc = new EasSyncService("%TestAccount%"); svc.mContext = context; svc.mHostAddress = hostAddress; svc.mUserName = userName; svc.mPassword = password; svc.mSsl = ssl; svc.mTrustSsl = trustCertificates; // We mustn't use the "real" device id or we'll screw up current accounts // Any string will do, but we'll go for "validate" svc.mDeviceId = "validate"; HttpResponse resp = svc.sendHttpClientOptions(); int code = resp.getStatusLine().getStatusCode(); userLog("Validation (OPTIONS) response: " + code); if (code == HttpStatus.SC_OK) { // No exception means successful validation Header commands = resp.getFirstHeader("MS-ASProtocolCommands"); Header versions = resp.getFirstHeader("ms-asprotocolversions"); if (commands == null || versions == null) { userLog("OPTIONS response without commands or versions; reporting I/O error"); throw new MessagingException(MessagingException.IOERROR); } // Make sure we've got the right protocol version set up setupProtocolVersion(svc, versions); // Run second test here for provisioning failures... Serializer s = new Serializer(); userLog("Try folder sync"); s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY).text("0") .end().end().done(); resp = svc.sendHttpClientPost("FolderSync", s.toByteArray()); code = resp.getStatusLine().getStatusCode(); // We'll get one of the following responses if policies are required by the server if (code == HttpStatus.SC_FORBIDDEN || code == HTTP_NEED_PROVISIONING) { // Get the policies and see if we are able to support them if (svc.canProvision() != null) { // If so, send the advisory Exception (the account may be created later) throw new MessagingException(MessagingException.SECURITY_POLICIES_REQUIRED); } else // If not, send the unsupported Exception (the account won't be created) throw new MessagingException( MessagingException.SECURITY_POLICIES_UNSUPPORTED); } userLog("Validation successful"); return; } if (isAuthError(code)) { userLog("Authentication failed"); throw new AuthenticationFailedException("Validation failed"); } else { // TODO Need to catch other kinds of errors (e.g. policy) For now, report the code. userLog("Validation failed, reporting I/O error: ", code); throw new MessagingException(MessagingException.IOERROR); } } catch (IOException e) { Throwable cause = e.getCause(); if (cause != null && cause instanceof CertificateException) { userLog("CertificateException caught: ", e.getMessage()); throw new MessagingException(MessagingException.GENERAL_SECURITY); } userLog("IOException caught: ", e.getMessage()); throw new MessagingException(MessagingException.IOERROR); } } /** * Gets the redirect location from the HTTP headers and uses that to modify the HttpPost so that * it can be reused * * @param resp the HttpResponse that indicates a redirect (451) * @param post the HttpPost that was originally sent to the server * @return the HttpPost, updated with the redirect location */ private HttpPost getRedirect(HttpResponse resp, HttpPost post) { Header locHeader = resp.getFirstHeader("X-MS-Location"); if (locHeader != null) { String loc = locHeader.getValue(); // If we've gotten one and it shows signs of looking like an address, we try // sending our request there if (loc != null && loc.startsWith("http")) { post.setURI(URI.create(loc)); return post; } } return null; } /** * Send the POST command to the autodiscover server, handling a redirect, if necessary, and * return the HttpResponse * * @param client the HttpClient to be used for the request * @param post the HttpPost we're going to send * @return an HttpResponse from the original or redirect server * @throws IOException on any IOException within the HttpClient code * @throws MessagingException */ private HttpResponse postAutodiscover(HttpClient client, HttpPost post) throws IOException, MessagingException { userLog("Posting autodiscover to: " + post.getURI()); HttpResponse resp = client.execute(post); int code = resp.getStatusLine().getStatusCode(); // On a redirect, try the new location if (code == AUTO_DISCOVER_REDIRECT_CODE) { post = getRedirect(resp, post); if (post != null) { userLog("Posting autodiscover to redirect: " + post.getURI()); return client.execute(post); } } else if (code == HttpStatus.SC_UNAUTHORIZED) { // 401 (Unauthorized) is for true auth errors when used in Autodiscover // 403 (and others) we'll just punt on throw new MessagingException(MessagingException.AUTHENTICATION_FAILED); } else if (code != HttpStatus.SC_OK) { // We'll try the next address if this doesn't work userLog("Code: " + code + ", throwing IOException"); throw new IOException(); } return resp; } /** * Use the Exchange 2007 AutoDiscover feature to try to retrieve server information using * only an email address and the password * * @param userName the user's email address * @param password the user's password * @return a HostAuth ready to be saved in an Account or null (failure) */ public Bundle tryAutodiscover(String userName, String password) throws RemoteException { XmlSerializer s = Xml.newSerializer(); ByteArrayOutputStream os = new ByteArrayOutputStream(1024); HostAuth hostAuth = new HostAuth(); Bundle bundle = new Bundle(); bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.NO_ERROR); try { // Build the XML document that's sent to the autodiscover server(s) s.setOutput(os, "UTF-8"); s.startDocument("UTF-8", false); s.startTag(null, "Autodiscover"); s.attribute(null, "xmlns", AUTO_DISCOVER_SCHEMA_PREFIX + "requestschema/2006"); s.startTag(null, "Request"); s.startTag(null, "EMailAddress").text(userName).endTag(null, "EMailAddress"); s.startTag(null, "AcceptableResponseSchema"); s.text(AUTO_DISCOVER_SCHEMA_PREFIX + "responseschema/2006"); s.endTag(null, "AcceptableResponseSchema"); s.endTag(null, "Request"); s.endTag(null, "Autodiscover"); s.endDocument(); String req = os.toString(); // Initialize the user name and password mUserName = userName; mPassword = password; // Make sure the authentication string is created (mAuthString) makeUriString("foo", null); // Split out the domain name int amp = userName.indexOf('@'); // The UI ensures that userName is a valid email address if (amp < 0) { throw new RemoteException(); } String domain = userName.substring(amp + 1); // There are up to four attempts here; the two URLs that we're supposed to try per the // specification, and up to one redirect for each (handled in postAutodiscover) // Try the domain first and see if we can get a response HttpPost post = new HttpPost("https://" + domain + AUTO_DISCOVER_PAGE); setHeaders(post, false); post.setHeader("Content-Type", "text/xml"); post.setEntity(new StringEntity(req)); HttpClient client = getHttpClient(COMMAND_TIMEOUT); HttpResponse resp; try { resp = postAutodiscover(client, post); } catch (ClientProtocolException e1) { return null; } catch (IOException e1) { // We catch the IOException here because we have an alternate address to try post.setURI(URI.create("https://autodiscover." + domain + AUTO_DISCOVER_PAGE)); // If we fail here, we're out of options, so we let the outer try catch the // IOException and return null resp = postAutodiscover(client, post); } // Get the "final" code; if it's not 200, just return null int code = resp.getStatusLine().getStatusCode(); userLog("Code: " + code); if (code != HttpStatus.SC_OK) return null; // At this point, we have a 200 response (SC_OK) HttpEntity e = resp.getEntity(); InputStream is = e.getContent(); try { // The response to Autodiscover is regular XML (not WBXML) // If we ever get an error in this process, we'll just punt and return null XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(is, "UTF-8"); int type = parser.getEventType(); if (type == XmlPullParser.START_DOCUMENT) { type = parser.next(); if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("Autodiscover")) { hostAuth = new HostAuth(); parseAutodiscover(parser, hostAuth); // On success, we'll have a server address and login if (hostAuth.mAddress != null && hostAuth.mLogin != null) { // Fill in the rest of the HostAuth hostAuth.mPassword = password; hostAuth.mPort = 443; hostAuth.mProtocol = "eas"; hostAuth.mFlags = HostAuth.FLAG_SSL | HostAuth.FLAG_AUTHENTICATE; bundle.putParcelable( EmailServiceProxy.AUTO_DISCOVER_BUNDLE_HOST_AUTH, hostAuth); } else { bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.UNSPECIFIED_EXCEPTION); } } } } } catch (XmlPullParserException e1) { // This would indicate an I/O error of some sort // We will simply return null and user can configure manually } // There's no reason at all for exceptions to be thrown, and it's ok if so. // We just won't do auto-discover; user can configure manually } catch (IllegalArgumentException e) { bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.UNSPECIFIED_EXCEPTION); } catch (IllegalStateException e) { bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.UNSPECIFIED_EXCEPTION); } catch (IOException e) { userLog("IOException in Autodiscover", e); bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.IOERROR); } catch (MessagingException e) { bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.AUTHENTICATION_FAILED); } return bundle; } void parseServer(XmlPullParser parser, HostAuth hostAuth) throws XmlPullParserException, IOException { boolean mobileSync = false; while (true) { int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals("Server")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("Type")) { if (parser.nextText().equals("MobileSync")) { mobileSync = true; } } else if (mobileSync && name.equals("Url")) { String url = parser.nextText().toLowerCase(); // This will look like https://<server address>/Microsoft-Server-ActiveSync // We need to extract the <server address> if (url.startsWith("https://") && url.endsWith("/microsoft-server-activesync")) { int lastSlash = url.lastIndexOf('/'); hostAuth.mAddress = url.substring(8, lastSlash); userLog("Autodiscover, server: " + hostAuth.mAddress); } } } } } void parseSettings(XmlPullParser parser, HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals("Settings")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("Server")) { parseServer(parser, hostAuth); } } } } void parseAction(XmlPullParser parser, HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals("Action")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("Error")) { // Should parse the error } else if (name.equals("Redirect")) { Log.d(TAG, "Redirect: " + parser.nextText()); } else if (name.equals("Settings")) { parseSettings(parser, hostAuth); } } } } void parseUser(XmlPullParser parser, HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals("User")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("EMailAddress")) { String addr = parser.nextText(); hostAuth.mLogin = addr; userLog("Autodiscover, login: " + addr); } else if (name.equals("DisplayName")) { String dn = parser.nextText(); userLog("Autodiscover, user: " + dn); } } } } void parseResponse(XmlPullParser parser, HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals("Response")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("User")) { parseUser(parser, hostAuth); } else if (name.equals("Action")) { parseAction(parser, hostAuth); } } } } void parseAutodiscover(XmlPullParser parser, HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("Autodiscover")) { break; } else if (type == XmlPullParser.START_TAG && parser.getName().equals("Response")) { parseResponse(parser, hostAuth); } } } private void doStatusCallback(long messageId, long attachmentId, int status) { try { SyncManager.callback().loadAttachmentStatus(messageId, attachmentId, status, 0); } catch (RemoteException e) { // No danger if the client is no longer around } } private void doProgressCallback(long messageId, long attachmentId, int progress) { try { SyncManager.callback().loadAttachmentStatus(messageId, attachmentId, EmailServiceStatus.IN_PROGRESS, progress); } catch (RemoteException e) { // No danger if the client is no longer around } } public File createUniqueFileInternal(String dir, String filename) { File directory; if (dir == null) { directory = mContext.getFilesDir(); } else { directory = new File(dir); } if (!directory.exists()) { directory.mkdirs(); } File file = new File(directory, filename); if (!file.exists()) { return file; } // Get the extension of the file, if any. int index = filename.lastIndexOf('.'); String name = filename; String extension = ""; if (index != -1) { name = filename.substring(0, index); extension = filename.substring(index); } for (int i = 2; i < Integer.MAX_VALUE; i++) { file = new File(directory, name + '-' + i + extension); if (!file.exists()) { return file; } } return null; } /** * Loads an attachment, based on the PartRequest passed in. The PartRequest is basically our * wrapper for Attachment * @param req the part (attachment) to be retrieved * @throws IOException */ protected void getAttachment(PartRequest req) throws IOException { Attachment att = req.mAttachment; Message msg = Message.restoreMessageWithId(mContext, att.mMessageKey); doProgressCallback(msg.mId, att.mId, 0); String cmd = "GetAttachment&AttachmentName=" + att.mLocation; HttpResponse res = sendHttpClientPost(cmd, null, COMMAND_TIMEOUT); int status = res.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { HttpEntity e = res.getEntity(); int len = (int)e.getContentLength(); InputStream is = res.getEntity().getContent(); File f = (req.mDestination != null) ? new File(req.mDestination) : createUniqueFileInternal(req.mDestination, att.mFileName); if (f != null) { // Ensure that the target directory exists File destDir = f.getParentFile(); if (!destDir.exists()) { destDir.mkdirs(); } FileOutputStream os = new FileOutputStream(f); // len > 0 means that Content-Length was set in the headers // len < 0 means "chunked" transfer-encoding if (len != 0) { try { mPendingRequest = req; byte[] bytes = new byte[CHUNK_SIZE]; int length = len; // Loop terminates 1) when EOF is reached or 2) if an IOException occurs // One of these is guaranteed to occur int totalRead = 0; userLog("Attachment content-length: ", len); while (true) { int read = is.read(bytes, 0, CHUNK_SIZE); // read < 0 means that EOF was reached if (read < 0) { userLog("Attachment load reached EOF, totalRead: ", totalRead); break; } // Keep track of how much we've read for progress callback totalRead += read; // Write these bytes out os.write(bytes, 0, read); // We can't report percentages if this is chunked; by definition, the // length of incoming data is unknown if (length > 0) { // Belt and suspenders check to prevent runaway reading if (totalRead > length) { errorLog("totalRead is greater than attachment length?"); break; } int pct = (totalRead * 100) / length; doProgressCallback(msg.mId, att.mId, pct); } } } finally { mPendingRequest = null; } } os.flush(); os.close(); // EmailProvider will throw an exception if we try to update an unsaved attachment if (att.isSaved()) { String contentUriString = (req.mContentUriString != null) ? req.mContentUriString : "file://" + f.getAbsolutePath(); ContentValues cv = new ContentValues(); cv.put(AttachmentColumns.CONTENT_URI, contentUriString); att.update(mContext, cv); doStatusCallback(msg.mId, att.mId, EmailServiceStatus.SUCCESS); } } } else { doStatusCallback(msg.mId, att.mId, EmailServiceStatus.MESSAGE_NOT_FOUND); } } /** * Send an email responding to a Message that has been marked as a meeting request. The message * will consist a little bit of event information and an iCalendar attachment * @param msg the meeting request email */ private void sendMeetingResponseMail(Message msg) { // Get the meeting information; we'd better have some... PackedString meetingInfo = new PackedString(msg.mMeetingInfo); if (meetingInfo == null) return; // This will come as "First Last" <box@server.blah>, so we use Address to // parse it into parts; we only need the email address part for the ics file Address[] addrs = Address.parse(meetingInfo.get(MeetingInfo.MEETING_ORGANIZER_EMAIL)); // It shouldn't be possible, but handle it anyway if (addrs.length != 1) return; String organizerEmail = addrs[0].getAddress(); String dtStamp = meetingInfo.get(MeetingInfo.MEETING_DTSTAMP); String dtStart = meetingInfo.get(MeetingInfo.MEETING_DTSTART); String dtEnd = meetingInfo.get(MeetingInfo.MEETING_DTEND); // What we're doing here is to create an Entity that looks like an Event as it would be // stored by CalendarProvider ContentValues entityValues = new ContentValues(); Entity entity = new Entity(entityValues); // Fill in times, location, title, and organizer entityValues.put("DTSTAMP", CalendarUtilities.convertEmailDateTimeToCalendarDateTime(dtStamp)); entityValues.put(Events.DTSTART, CalendarUtilities.parseEmailDateTimeToMillis(dtStart)); entityValues.put(Events.DTEND, CalendarUtilities.parseEmailDateTimeToMillis(dtEnd)); entityValues.put(Events.EVENT_LOCATION, meetingInfo.get(MeetingInfo.MEETING_LOCATION)); entityValues.put(Events.TITLE, meetingInfo.get(MeetingInfo.MEETING_TITLE)); entityValues.put(Events.ORGANIZER, organizerEmail); // Add ourselves as an attendee, using our account email address ContentValues attendeeValues = new ContentValues(); attendeeValues.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE); attendeeValues.put(Attendees.ATTENDEE_EMAIL, mAccount.mEmailAddress); entity.addSubValue(Attendees.CONTENT_URI, attendeeValues); // Add the organizer ContentValues organizerValues = new ContentValues(); organizerValues.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER); organizerValues.put(Attendees.ATTENDEE_EMAIL, organizerEmail); entity.addSubValue(Attendees.CONTENT_URI, organizerValues); // Create a message from the Entity we've built. The message will have fields like // to, subject, date, and text filled in. There will also be an "inline" attachment // which is in iCalendar format Message outgoingMsg = CalendarUtilities.createMessageForEntity(mContext, entity, Message.FLAG_OUTGOING_MEETING_ACCEPT, meetingInfo.get(MeetingInfo.MEETING_UID), mAccount); // Assuming we got a message back (we might not if the event has been deleted), send it if (outgoingMsg != null) { EasOutboxService.sendMessage(mContext, mAccount.mId, outgoingMsg); } } /** * Responds to a meeting request. The MeetingResponseRequest is basically our * wrapper for the meetingResponse service call * @param req the request (message id and response code) * @throws IOException */ protected void sendMeetingResponse(MeetingResponseRequest req) throws IOException { // Retrieve the message and mailbox; punt if either are null Message msg = Message.restoreMessageWithId(mContext, req.mMessageId); if (msg == null) return; Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, msg.mMailboxKey); if (mailbox == null) return; Serializer s = new Serializer(); s.start(Tags.MREQ_MEETING_RESPONSE).start(Tags.MREQ_REQUEST); s.data(Tags.MREQ_USER_RESPONSE, Integer.toString(req.mResponse)); s.data(Tags.MREQ_COLLECTION_ID, mailbox.mServerId); s.data(Tags.MREQ_REQ_ID, msg.mServerId); s.end().end().done(); HttpResponse res = sendHttpClientPost("MeetingResponse", s.toByteArray()); int status = res.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { HttpEntity e = res.getEntity(); int len = (int)e.getContentLength(); InputStream is = res.getEntity().getContent(); if (len != 0) { new MeetingResponseParser(is, this).parse(); sendMeetingResponseMail(msg); } } else if (isAuthError(status)) { throw new EasAuthenticationException(); } else { userLog("Meeting response request failed, code: " + status); throw new IOException(); } } @SuppressWarnings("deprecation") private String makeUriString(String cmd, String extra) throws IOException { // Cache the authentication string and the command string String safeUserName = URLEncoder.encode(mUserName); if (mAuthString == null) { String cs = mUserName + ':' + mPassword; mAuthString = "Basic " + Base64.encodeToString(cs.getBytes(), Base64.NO_WRAP); mCmdString = "&User=" + safeUserName + "&DeviceId=" + mDeviceId + "&DeviceType=" + mDeviceType; } String us = (mSsl ? (mTrustSsl ? "httpts" : "https") : "http") + "://" + mHostAddress + "/Microsoft-Server-ActiveSync"; if (cmd != null) { us += "?Cmd=" + cmd + mCmdString; } if (extra != null) { us += extra; } return us; } /** * Set standard HTTP headers, using a policy key if required * @param method the method we are going to send * @param usePolicyKey whether or not a policy key should be sent in the headers */ private void setHeaders(HttpRequestBase method, boolean usePolicyKey) { method.setHeader("Authorization", mAuthString); method.setHeader("MS-ASProtocolVersion", mProtocolVersion); method.setHeader("Connection", "keep-alive"); method.setHeader("User-Agent", mDeviceType + '/' + Eas.VERSION); if (usePolicyKey && (mAccount != null)) { String key = mAccount.mSecuritySyncKey; if (key == null || key.length() == 0) { return; } method.setHeader("X-MS-PolicyKey", key); } } private ClientConnectionManager getClientConnectionManager() { return SyncManager.getClientConnectionManager(); } private HttpClient getHttpClient(int timeout) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 15*SECONDS); HttpConnectionParams.setSoTimeout(params, timeout); HttpConnectionParams.setSocketBufferSize(params, 8192); HttpClient client = new DefaultHttpClient(getClientConnectionManager(), params); return client; } protected HttpResponse sendHttpClientPost(String cmd, byte[] bytes) throws IOException { return sendHttpClientPost(cmd, new ByteArrayEntity(bytes), COMMAND_TIMEOUT); } protected HttpResponse sendHttpClientPost(String cmd, HttpEntity entity) throws IOException { return sendHttpClientPost(cmd, entity, COMMAND_TIMEOUT); } protected HttpResponse sendPing(byte[] bytes, int heartbeat) throws IOException { Thread.currentThread().setName(mAccount.mDisplayName + ": Ping"); if (Eas.USER_LOG) { userLog("Send ping, timeout: " + heartbeat + "s, high: " + mPingHighWaterMark + 's'); } return sendHttpClientPost(PING_COMMAND, new ByteArrayEntity(bytes), (heartbeat+5)*SECONDS); } protected HttpResponse sendHttpClientPost(String cmd, HttpEntity entity, int timeout) throws IOException { HttpClient client = getHttpClient(timeout); boolean sleepAllowed = cmd.equals(PING_COMMAND); // Split the mail sending commands String extra = null; boolean msg = false; if (cmd.startsWith("SmartForward&") || cmd.startsWith("SmartReply&")) { int cmdLength = cmd.indexOf('&'); extra = cmd.substring(cmdLength); cmd = cmd.substring(0, cmdLength); msg = true; } else if (cmd.startsWith("SendMail&")) { msg = true; } String us = makeUriString(cmd, extra); HttpPost method = new HttpPost(URI.create(us)); // Send the proper Content-Type header // If entity is null (e.g. for attachments), don't set this header if (msg) { method.setHeader("Content-Type", "message/rfc822"); } else if (entity != null) { method.setHeader("Content-Type", "application/vnd.ms-sync.wbxml"); } setHeaders(method, !cmd.equals(PING_COMMAND)); method.setEntity(entity); synchronized(getSynchronizer()) { mPendingPost = method; if (sleepAllowed) { SyncManager.runAsleep(mMailboxId, timeout+(10*SECONDS)); } } try { return client.execute(method); } finally { synchronized(getSynchronizer()) { if (sleepAllowed) { SyncManager.runAwake(mMailboxId); } mPendingPost = null; } } } protected HttpResponse sendHttpClientOptions() throws IOException { HttpClient client = getHttpClient(COMMAND_TIMEOUT); String us = makeUriString("OPTIONS", null); HttpOptions method = new HttpOptions(URI.create(us)); setHeaders(method, false); return client.execute(method); } String getTargetCollectionClassFromCursor(Cursor c) { int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN); if (type == Mailbox.TYPE_CONTACTS) { return "Contacts"; } else if (type == Mailbox.TYPE_CALENDAR) { return "Calendar"; } else { return "Email"; } } /** * Negotiate provisioning with the server. First, get policies form the server and see if * the policies are supported by the device. Then, write the policies to the account and * tell SecurityPolicy that we have policies in effect. Finally, see if those policies are * active; if so, acknowledge the policies to the server and get a final policy key that we * use in future EAS commands and write this key to the account. * @return whether or not provisioning has been successful * @throws IOException */ private boolean tryProvision() throws IOException { // First, see if provisioning is even possible, i.e. do we support the policies required // by the server ProvisionParser pp = canProvision(); if (pp != null) { SecurityPolicy sp = SecurityPolicy.getInstance(mContext); // Get the policies from ProvisionParser PolicySet ps = pp.getPolicySet(); // Update the account with a null policyKey (the key we've gotten is // temporary and cannot be used for syncing) if (ps.writeAccount(mAccount, null, true, mContext)) { sp.updatePolicies(mAccount.mId); } if (pp.getRemoteWipe()) { // We've gotten a remote wipe command // First, we've got to acknowledge it, but wrap the wipe in try/catch so that // we wipe the device regardless of any errors in acknowledgment try { acknowledgeRemoteWipe(pp.getPolicyKey()); } catch (Exception e) { // Because remote wipe is such a high priority task, we don't want to // circumvent it if there's an exception in acknowledgment } // Then, tell SecurityPolicy to wipe the device sp.remoteWipe(); return false; } else if (sp.isActive(ps)) { // See if the required policies are in force; if they are, acknowledge the policies // to the server and get the final policy key String policyKey = acknowledgeProvision(pp.getPolicyKey()); if (policyKey != null) { // Write the final policy key to the Account and say we've been successful ps.writeAccount(mAccount, policyKey, true, mContext); return true; } } else { // Notify that we are blocked because of policies sp.policiesRequired(mAccount.mId); } } return false; } private String getPolicyType() { return (mProtocolVersionDouble >= 12.0) ? EAS_12_POLICY_TYPE : EAS_2_POLICY_TYPE; } // TODO This is Exchange 2007 only at this point /** * Obtain a set of policies from the server and determine whether those policies are supported * by the device. * @return the ProvisionParser (holds policies and key) if we receive policies and they are * supported by the device; null otherwise * @throws IOException */ private ProvisionParser canProvision() throws IOException { Serializer s = new Serializer(); s.start(Tags.PROVISION_PROVISION).start(Tags.PROVISION_POLICIES); s.start(Tags.PROVISION_POLICY).data(Tags.PROVISION_POLICY_TYPE, getPolicyType()) .end().end().end().done(); HttpResponse resp = sendHttpClientPost("Provision", s.toByteArray()); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { InputStream is = resp.getEntity().getContent(); ProvisionParser pp = new ProvisionParser(is, this); if (pp.parse()) { // If true, we received policies from the server; see if they are supported by // the framework; if so, return the ProvisionParser containing the policy set and // temporary key PolicySet ps = pp.getPolicySet(); if (SecurityPolicy.getInstance(mContext).isSupported(ps)) { return pp; } } } // On failures, simply return null return null; } // TODO This is Exchange 2007 only at this point /** * Acknowledge that we support the policies provided by the server, and that these policies * are in force. * @param tempKey the initial (temporary) policy key sent by the server * @return the final policy key, which can be used for syncing * @throws IOException */ private void acknowledgeRemoteWipe(String tempKey) throws IOException { acknowledgeProvisionImpl(tempKey, true); } private String acknowledgeProvision(String tempKey) throws IOException { return acknowledgeProvisionImpl(tempKey, false); } private String acknowledgeProvisionImpl(String tempKey, boolean remoteWipe) throws IOException { Serializer s = new Serializer(); s.start(Tags.PROVISION_PROVISION).start(Tags.PROVISION_POLICIES); s.start(Tags.PROVISION_POLICY); // Use the proper policy type, depending on EAS version s.data(Tags.PROVISION_POLICY_TYPE, getPolicyType()); s.data(Tags.PROVISION_POLICY_KEY, tempKey); s.data(Tags.PROVISION_STATUS, "1"); if (remoteWipe) { s.start(Tags.PROVISION_REMOTE_WIPE); s.data(Tags.PROVISION_STATUS, "1"); s.end(); } s.end(); // PROVISION_POLICY s.end().end().done(); // PROVISION_POLICIES, PROVISION_PROVISION HttpResponse resp = sendHttpClientPost("Provision", s.toByteArray()); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { InputStream is = resp.getEntity().getContent(); ProvisionParser pp = new ProvisionParser(is, this); if (pp.parse()) { // Return the final polic key from the ProvisionParser return pp.getPolicyKey(); } } // On failures, return null return null; } /** * Performs FolderSync * * @throws IOException * @throws EasParserException */ public void runAccountMailbox() throws IOException, EasParserException { // Initialize exit status to success mExitStatus = EmailServiceStatus.SUCCESS; try { try { SyncManager.callback() .syncMailboxListStatus(mAccount.mId, EmailServiceStatus.IN_PROGRESS, 0); } catch (RemoteException e1) { // Don't care if this fails } if (mAccount.mSyncKey == null) { mAccount.mSyncKey = "0"; userLog("Account syncKey INIT to 0"); ContentValues cv = new ContentValues(); cv.put(AccountColumns.SYNC_KEY, mAccount.mSyncKey); mAccount.update(mContext, cv); } boolean firstSync = mAccount.mSyncKey.equals("0"); if (firstSync) { userLog("Initial FolderSync"); } // When we first start up, change all mailboxes to push. ContentValues cv = new ContentValues(); cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_ACCOUNT_AND_SYNC_INTERVAL_PING, new String[] {Long.toString(mAccount.mId)}) > 0) { SyncManager.kick("change ping boxes to push"); } // Determine our protocol version, if we haven't already and save it in the Account // Also re-check protocol version at least once a day (in case of upgrade) if (mAccount.mProtocolVersion == null || ((System.currentTimeMillis() - mMailbox.mSyncTime) > DAYS)) { userLog("Determine EAS protocol version"); HttpResponse resp = sendHttpClientOptions(); int code = resp.getStatusLine().getStatusCode(); userLog("OPTIONS response: ", code); if (code == HttpStatus.SC_OK) { Header header = resp.getFirstHeader("MS-ASProtocolCommands"); userLog(header.getValue()); header = resp.getFirstHeader("ms-asprotocolversions"); String versions = header.getValue(); if (versions != null) { if (versions.contains("12.0")) { mProtocolVersion = "12.0"; } mProtocolVersionDouble = Double.parseDouble(mProtocolVersion); mAccount.mProtocolVersion = mProtocolVersion; // Save the protocol version cv.clear(); // Save the protocol version in the account cv.put(Account.PROTOCOL_VERSION, mProtocolVersion); mAccount.update(mContext, cv); cv.clear(); // Save the sync time of the account mailbox to current time cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis()); mMailbox.update(mContext, cv); userLog(versions); userLog("Using version ", mProtocolVersion); } else { errorLog("No protocol versions in OPTIONS response"); throw new IOException(); } } else { errorLog("OPTIONS command failed; throwing IOException"); throw new IOException(); } } // Change all pushable boxes to push when we start the account mailbox if (mAccount.mSyncInterval == Account.CHECK_INTERVAL_PUSH) { cv.clear(); cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH); if (mContentResolver.update(Mailbox.CONTENT_URI, cv, SyncManager.WHERE_IN_ACCOUNT_AND_PUSHABLE, new String[] {Long.toString(mAccount.mId)}) > 0) { userLog("Push account; set pushable boxes to push..."); } } while (!mStop) { userLog("Sending Account syncKey: ", mAccount.mSyncKey); Serializer s = new Serializer(); s.start(Tags.FOLDER_FOLDER_SYNC).start(Tags.FOLDER_SYNC_KEY) .text(mAccount.mSyncKey).end().end().done(); HttpResponse resp = sendHttpClientPost("FolderSync", s.toByteArray()); if (mStop) break; int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { HttpEntity entity = resp.getEntity(); int len = (int)entity.getContentLength(); if (len != 0) { InputStream is = entity.getContent(); // Returns true if we need to sync again if (new FolderSyncParser(is, new AccountSyncAdapter(mMailbox, this)) .parse()) { continue; } } } else if (isProvisionError(code)) { // If the sync error is a provisioning failure (perhaps the policies changed), // let's try the provisining procedure if (!tryProvision()) { // Set the appropriate failure status mExitStatus = EXIT_SECURITY_FAILURE; return; + } else { + // If we succeeded, try again... + continue; } } else if (isAuthError(code)) { mExitStatus = EXIT_LOGIN_FAILURE; return; } else { userLog("FolderSync response error: ", code); } // Change all push/hold boxes to push cv.clear(); cv.put(Mailbox.SYNC_INTERVAL, Account.CHECK_INTERVAL_PUSH); if (mContentResolver.update(Mailbox.CONTENT_URI, cv, WHERE_PUSH_HOLD_NOT_ACCOUNT_MAILBOX, new String[] {Long.toString(mAccount.mId)}) > 0) { userLog("Set push/hold boxes to push..."); } try { SyncManager.callback() .syncMailboxListStatus(mAccount.mId, mExitStatus, 0); } catch (RemoteException e1) { // Don't care if this fails } // Wait for push notifications. String threadName = Thread.currentThread().getName(); try { runPingLoop(); } catch (StaleFolderListException e) { // We break out if we get told about a stale folder list userLog("Ping interrupted; folder list requires sync..."); } finally { Thread.currentThread().setName(threadName); } } } catch (IOException e) { // We catch this here to send the folder sync status callback // A folder sync failed callback will get sent from run() try { if (!mStop) { SyncManager.callback() .syncMailboxListStatus(mAccount.mId, EmailServiceStatus.CONNECTION_ERROR, 0); } } catch (RemoteException e1) { // Don't care if this fails } throw e; } } void pushFallback(long mailboxId) { Mailbox mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId); ContentValues cv = new ContentValues(); int mins = PING_FALLBACK_PIM; if (mailbox.mType == Mailbox.TYPE_INBOX) { mins = PING_FALLBACK_INBOX; } cv.put(Mailbox.SYNC_INTERVAL, mins); mContentResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId), cv, null, null); errorLog("*** PING ERROR LOOP: Set " + mailbox.mDisplayName + " to " + mins + " min sync"); SyncManager.kick("push fallback"); } void runPingLoop() throws IOException, StaleFolderListException { int pingHeartbeat = mPingHeartbeat; userLog("runPingLoop"); // Do push for all sync services here long endTime = System.currentTimeMillis() + (30*MINUTES); HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>(); ArrayList<String> readyMailboxes = new ArrayList<String>(); ArrayList<String> notReadyMailboxes = new ArrayList<String>(); int pingWaitCount = 0; while ((System.currentTimeMillis() < endTime) && !mStop) { // Count of pushable mailboxes int pushCount = 0; // Count of mailboxes that can be pushed right now int canPushCount = 0; // Count of uninitialized boxes int uninitCount = 0; Serializer s = new Serializer(); Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId + AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX, null, null); notReadyMailboxes.clear(); readyMailboxes.clear(); try { // Loop through our pushed boxes seeing what is available to push while (c.moveToNext()) { pushCount++; // Two requirements for push: // 1) SyncManager tells us the mailbox is syncable (not running, not stopped) // 2) The syncKey isn't "0" (i.e. it's synced at least once) long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN); int pingStatus = SyncManager.pingStatus(mailboxId); String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); if (pingStatus == SyncManager.PING_STATUS_OK) { String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN); if ((syncKey == null) || syncKey.equals("0")) { // We can't push until the initial sync is done pushCount--; uninitCount++; continue; } if (canPushCount++ == 0) { // Initialize the Ping command s.start(Tags.PING_PING) .data(Tags.PING_HEARTBEAT_INTERVAL, Integer.toString(pingHeartbeat)) .start(Tags.PING_FOLDERS); } String folderClass = getTargetCollectionClassFromCursor(c); s.start(Tags.PING_FOLDER) .data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN)) .data(Tags.PING_CLASS, folderClass) .end(); readyMailboxes.add(mailboxName); } else if ((pingStatus == SyncManager.PING_STATUS_RUNNING) || (pingStatus == SyncManager.PING_STATUS_WAITING)) { notReadyMailboxes.add(mailboxName); } else if (pingStatus == SyncManager.PING_STATUS_UNABLE) { pushCount--; userLog(mailboxName, " in error state; ignore"); continue; } } } finally { c.close(); } if (Eas.USER_LOG) { if (!notReadyMailboxes.isEmpty()) { userLog("Ping not ready for: " + notReadyMailboxes); } if (!readyMailboxes.isEmpty()) { userLog("Ping ready for: " + readyMailboxes); } } // If we've waited 10 seconds or more, just ping with whatever boxes are ready // But use a shorter than normal heartbeat boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5); if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) { // If all pingable boxes are ready for push, send Ping to the server s.end().end().done(); pingWaitCount = 0; // If we've been stopped, this is a good time to return if (mStop) return; long pingTime = SystemClock.elapsedRealtime(); try { // Send the ping, wrapped by appropriate timeout/alarm if (forcePing) { userLog("Forcing ping after waiting for all boxes to be ready"); } HttpResponse res = sendPing(s.toByteArray(), forcePing ? PING_FORCE_HEARTBEAT : pingHeartbeat); int code = res.getStatusLine().getStatusCode(); userLog("Ping response: ", code); // Return immediately if we've been asked to stop during the ping if (mStop) { userLog("Stopping pingLoop"); return; } if (code == HttpStatus.SC_OK) { HttpEntity e = res.getEntity(); int len = (int)e.getContentLength(); InputStream is = res.getEntity().getContent(); if (len != 0) { int pingResult = parsePingResult(is, mContentResolver, pingErrorMap); // If our ping completed (status = 1), and we weren't forced and we're // not at the maximum, try increasing timeout by two minutes if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) { if (pingHeartbeat > mPingHighWaterMark) { mPingHighWaterMark = pingHeartbeat; userLog("Setting high water mark at: ", mPingHighWaterMark); } if ((pingHeartbeat < PING_MAX_HEARTBEAT) && !mPingHeartbeatDropped) { pingHeartbeat += PING_HEARTBEAT_INCREMENT; if (pingHeartbeat > PING_MAX_HEARTBEAT) { pingHeartbeat = PING_MAX_HEARTBEAT; } userLog("Increasing ping heartbeat to ", pingHeartbeat, "s"); } } } else { userLog("Ping returned empty result; throwing IOException"); throw new IOException(); } } else if (isAuthError(code)) { mExitStatus = EXIT_LOGIN_FAILURE; userLog("Authorization error during Ping: ", code); throw new IOException(); } } catch (IOException e) { String message = e.getMessage(); // If we get the exception that is indicative of a NAT timeout and if we // haven't yet "fixed" the timeout, back off by two minutes and "fix" it boolean hasMessage = message != null; userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]")); if (mPostAborted || (hasMessage && message.contains("reset by peer"))) { long pingLength = SystemClock.elapsedRealtime() - pingTime; if ((pingHeartbeat > PING_MIN_HEARTBEAT) && (pingHeartbeat > mPingHighWaterMark)) { pingHeartbeat -= PING_HEARTBEAT_INCREMENT; mPingHeartbeatDropped = true; if (pingHeartbeat < PING_MIN_HEARTBEAT) { pingHeartbeat = PING_MIN_HEARTBEAT; } userLog("Decreased ping heartbeat to ", pingHeartbeat, "s"); } else if (mPostAborted || (pingLength < 2000)) { userLog("Abort or NAT type return < 2 seconds; throwing IOException"); throw e; } else { userLog("NAT type IOException > 2 seconds?"); } } else { throw e; } } } else if (forcePing) { // In this case, there aren't any boxes that are pingable, but there are boxes // waiting (for IOExceptions) userLog("pingLoop waiting 60s for any pingable boxes"); sleep(60*SECONDS, true); } else if (pushCount > 0) { // If we want to Ping, but can't just yet, wait a little bit // TODO Change sleep to wait and use notify from SyncManager when a sync ends sleep(2*SECONDS, false); pingWaitCount++; //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)"); } else if (uninitCount > 0) { // In this case, we're doing an initial sync of at least one mailbox. Since this // is typically a one-time case, I'm ok with trying again every 10 seconds until // we're in one of the other possible states. userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)"); sleep(10*SECONDS, true); } else { // We've got nothing to do, so we'll check again in 30 minutes at which time // we'll update the folder list. Let the device sleep in the meantime... userLog("pingLoop sleeping for 30m"); sleep(30*MINUTES, true); } } } void sleep(long ms, boolean runAsleep) { if (runAsleep) { SyncManager.runAsleep(mMailboxId, ms+(5*SECONDS)); } try { Thread.sleep(ms); } catch (InterruptedException e) { // Doesn't matter whether we stop early; it's the thought that counts } finally { if (runAsleep) { SyncManager.runAwake(mMailboxId); } } } private int parsePingResult(InputStream is, ContentResolver cr, HashMap<String, Integer> errorMap) throws IOException, StaleFolderListException { PingParser pp = new PingParser(is, this); if (pp.parse()) { // True indicates some mailboxes need syncing... // syncList has the serverId's of the mailboxes... mBindArguments[0] = Long.toString(mAccount.mId); mPingChangeList = pp.getSyncList(); for (String serverId: mPingChangeList) { mBindArguments[1] = serverId; Cursor c = cr.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, WHERE_ACCOUNT_KEY_AND_SERVER_ID, mBindArguments, null); try { if (c.moveToFirst()) { /** * Check the boxes reporting changes to see if there really were any... * We do this because bugs in various Exchange servers can put us into a * looping behavior by continually reporting changes in a mailbox, even when * there aren't any. * * This behavior is seemingly random, and therefore we must code defensively * by backing off of push behavior when it is detected. * * One known cause, on certain Exchange 2003 servers, is acknowledged by * Microsoft, and the server hotfix for this case can be found at * http://support.microsoft.com/kb/923282 */ // Check the status of the last sync String status = c.getString(Mailbox.CONTENT_SYNC_STATUS_COLUMN); int type = SyncManager.getStatusType(status); // This check should always be true... if (type == SyncManager.SYNC_PING) { int changeCount = SyncManager.getStatusChangeCount(status); if (changeCount > 0) { errorMap.remove(serverId); } else if (changeCount == 0) { // This means that a ping reported changes in error; we keep a count // of consecutive errors of this kind String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN); Integer failures = errorMap.get(serverId); if (failures == null) { userLog("Last ping reported changes in error for: ", name); errorMap.put(serverId, 1); } else if (failures > MAX_PING_FAILURES) { // We'll back off of push for this box pushFallback(c.getLong(Mailbox.CONTENT_ID_COLUMN)); continue; } else { userLog("Last ping reported changes in error for: ", name); errorMap.put(serverId, failures + 1); } } } // If there were no problems with previous sync, we'll start another one SyncManager.startManualSync(c.getLong(Mailbox.CONTENT_ID_COLUMN), SyncManager.SYNC_PING, null); } } finally { c.close(); } } } return pp.getSyncStatus(); } private String getEmailFilter() { String filter = Eas.FILTER_1_WEEK; switch (mAccount.mSyncLookback) { case com.android.email.Account.SYNC_WINDOW_1_DAY: { filter = Eas.FILTER_1_DAY; break; } case com.android.email.Account.SYNC_WINDOW_3_DAYS: { filter = Eas.FILTER_3_DAYS; break; } case com.android.email.Account.SYNC_WINDOW_1_WEEK: { filter = Eas.FILTER_1_WEEK; break; } case com.android.email.Account.SYNC_WINDOW_2_WEEKS: { filter = Eas.FILTER_2_WEEKS; break; } case com.android.email.Account.SYNC_WINDOW_1_MONTH: { filter = Eas.FILTER_1_MONTH; break; } case com.android.email.Account.SYNC_WINDOW_ALL: { filter = Eas.FILTER_ALL; break; } } return filter; } /** * Common code to sync E+PIM data * * @param target, an EasMailbox, EasContacts, or EasCalendar object */ public void sync(AbstractSyncAdapter target) throws IOException { Mailbox mailbox = target.mMailbox; boolean moreAvailable = true; while (!mStop && moreAvailable) { // If we have no connectivity, just exit cleanly. SyncManager will start us up again // when connectivity has returned if (!hasConnectivity()) { userLog("No connectivity in sync; finishing sync"); mExitStatus = EXIT_DONE; return; } // Now, handle various requests while (true) { Request req = null; synchronized (mRequests) { if (mRequests.isEmpty()) { break; } else { req = mRequests.get(0); } } // Our two request types are PartRequest (loading attachment) and // MeetingResponseRequest (respond to a meeting request) if (req instanceof PartRequest) { getAttachment((PartRequest)req); } else if (req instanceof MeetingResponseRequest) { sendMeetingResponse((MeetingResponseRequest)req); } // If there's an exception handling the request, we'll throw it // Otherwise, we remove the request synchronized(mRequests) { mRequests.remove(req); } } Serializer s = new Serializer(); String className = target.getCollectionName(); String syncKey = target.getSyncKey(); userLog("sync, sending ", className, " syncKey: ", syncKey); s.start(Tags.SYNC_SYNC) .start(Tags.SYNC_COLLECTIONS) .start(Tags.SYNC_COLLECTION) .data(Tags.SYNC_CLASS, className) .data(Tags.SYNC_SYNC_KEY, syncKey) .data(Tags.SYNC_COLLECTION_ID, mailbox.mServerId) .tag(Tags.SYNC_DELETES_AS_MOVES); // EAS doesn't like GetChanges if the syncKey is "0"; not documented if (!syncKey.equals("0")) { s.tag(Tags.SYNC_GET_CHANGES); } s.data(Tags.SYNC_WINDOW_SIZE, className.equals("Email") ? EMAIL_WINDOW_SIZE : PIM_WINDOW_SIZE); // Handle options s.start(Tags.SYNC_OPTIONS); // Set the lookback appropriately (EAS calls this a "filter") for all but Contacts if (className.equals("Email")) { s.data(Tags.SYNC_FILTER_TYPE, getEmailFilter()); } else if (className.equals("Calendar")) { // TODO Force one month for calendar until we can set this! s.data(Tags.SYNC_FILTER_TYPE, Eas.FILTER_1_MONTH); } // Set the truncation amount for all classes if (mProtocolVersionDouble >= 12.0) { s.start(Tags.BASE_BODY_PREFERENCE) // HTML for email; plain text for everything else .data(Tags.BASE_TYPE, (className.equals("Email") ? Eas.BODY_PREFERENCE_HTML : Eas.BODY_PREFERENCE_TEXT)) .data(Tags.BASE_TRUNCATION_SIZE, Eas.EAS12_TRUNCATION_SIZE) .end(); } else { s.data(Tags.SYNC_TRUNCATION, Eas.EAS2_5_TRUNCATION_SIZE); } s.end(); // Send our changes up to the server target.sendLocalChanges(s); s.end().end().end().done(); HttpResponse resp = sendHttpClientPost("Sync", s.toByteArray()); int code = resp.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { InputStream is = resp.getEntity().getContent(); if (is != null) { moreAvailable = target.parse(is); target.cleanup(); } else { userLog("Empty input stream in sync command response"); } } else { userLog("Sync response error: ", code); if (isProvisionError(code)) { if (!tryProvision()) { mExitStatus = EXIT_SECURITY_FAILURE; return; } } else if (isAuthError(code)) { mExitStatus = EXIT_LOGIN_FAILURE; } else { mExitStatus = EXIT_IO_ERROR; } return; } } mExitStatus = EXIT_DONE; } protected boolean setupService() { // Make sure account and mailbox are always the latest from the database mAccount = Account.restoreAccountWithId(mContext, mAccount.mId); if (mAccount == null) return false; mMailbox = Mailbox.restoreMailboxWithId(mContext, mMailbox.mId); if (mMailbox == null) return false; mThread = Thread.currentThread(); android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); TAG = mThread.getName(); HostAuth ha = HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv); if (ha == null) return false; mHostAddress = ha.mAddress; mUserName = ha.mLogin; mPassword = ha.mPassword; // Set up our protocol version from the Account mProtocolVersion = mAccount.mProtocolVersion; // If it hasn't been set up, start with default version if (mProtocolVersion == null) { mProtocolVersion = DEFAULT_PROTOCOL_VERSION; } mProtocolVersionDouble = Double.parseDouble(mProtocolVersion); return true; } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { if (!setupService()) return; try { SyncManager.callback().syncMailboxStatus(mMailboxId, EmailServiceStatus.IN_PROGRESS, 0); } catch (RemoteException e1) { // Don't care if this fails } // Whether or not we're the account mailbox try { mDeviceId = SyncManager.getDeviceId(); if ((mMailbox == null) || (mAccount == null)) { return; } else if (mMailbox.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) { runAccountMailbox(); } else { AbstractSyncAdapter target; if (mMailbox.mType == Mailbox.TYPE_CONTACTS) { target = new ContactsSyncAdapter(mMailbox, this); } else if (mMailbox.mType == Mailbox.TYPE_CALENDAR) { target = new CalendarSyncAdapter(mMailbox, this); } else { target = new EmailSyncAdapter(mMailbox, this); } // We loop here because someone might have put a request in while we were syncing // and we've missed that opportunity... do { if (mRequestTime != 0) { userLog("Looping for user request..."); mRequestTime = 0; } sync(target); } while (mRequestTime != 0); } } catch (EasAuthenticationException e) { userLog("Caught authentication error"); mExitStatus = EXIT_LOGIN_FAILURE; } catch (IOException e) { String message = e.getMessage(); userLog("Caught IOException: ", (message == null) ? "No message" : message); mExitStatus = EXIT_IO_ERROR; } catch (Exception e) { userLog("Uncaught exception in EasSyncService", e); } finally { int status; if (!mStop) { userLog("Sync finished"); SyncManager.done(this); switch (mExitStatus) { case EXIT_IO_ERROR: status = EmailServiceStatus.CONNECTION_ERROR; break; case EXIT_DONE: status = EmailServiceStatus.SUCCESS; ContentValues cv = new ContentValues(); cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis()); String s = "S" + mSyncReason + ':' + status + ':' + mChangeCount; cv.put(Mailbox.SYNC_STATUS, s); mContentResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailboxId), cv, null, null); break; case EXIT_LOGIN_FAILURE: status = EmailServiceStatus.LOGIN_FAILED; break; case EXIT_SECURITY_FAILURE: status = EmailServiceStatus.SECURITY_FAILURE; break; default: status = EmailServiceStatus.REMOTE_EXCEPTION; errorLog("Sync ended due to an exception."); break; } } else { userLog("Stopped sync finished."); status = EmailServiceStatus.SUCCESS; } try { SyncManager.callback().syncMailboxStatus(mMailboxId, status, 0); } catch (RemoteException e1) { // Don't care if this fails } // Make sure SyncManager knows about this SyncManager.kick("sync finished"); } } }
true
false
null
null
diff --git a/Service/app/api/requests/ReadPollRequest.java b/Service/app/api/requests/ReadPollRequest.java index 269318a..c28e07f 100644 --- a/Service/app/api/requests/ReadPollRequest.java +++ b/Service/app/api/requests/ReadPollRequest.java @@ -1,28 +1,28 @@ package api.requests; import api.entities.PollJSON; import api.responses.ReadPollResponse; import api.responses.Response; public class ReadPollRequest extends Request { public static final Class EXPECTED_RESPONSE = ReadPollResponse.class; - public Long poll_id; - public ReadPollRequest (Long l) { - this.poll_id = l; + public String poll_token; + public ReadPollRequest (String s) { + this.poll_token = s; } @Override public String getURL() { - return "/poll/" + poll_id; + return "/poll/" + poll_token; } @Override public Class<? extends Response> getExpectedResponseClass() { return ReadPollResponse.class; } @Override public Method getHttpMethod() { return Method.GET; } }
false
false
null
null
diff --git a/apvs-ptu/src/main/java/ch/cern/atlas/apvs/ptu/server/PtuClientHandler.java b/apvs-ptu/src/main/java/ch/cern/atlas/apvs/ptu/server/PtuClientHandler.java index 460283fa..8f793a9a 100644 --- a/apvs-ptu/src/main/java/ch/cern/atlas/apvs/ptu/server/PtuClientHandler.java +++ b/apvs-ptu/src/main/java/ch/cern/atlas/apvs/ptu/server/PtuClientHandler.java @@ -1,306 +1,306 @@ package ch.cern.atlas.apvs.ptu.server; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Logger; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; import ch.cern.atlas.apvs.domain.Error; import ch.cern.atlas.apvs.domain.Event; import ch.cern.atlas.apvs.domain.History; import ch.cern.atlas.apvs.domain.Measurement; import ch.cern.atlas.apvs.domain.Message; import ch.cern.atlas.apvs.domain.Ptu; import ch.cern.atlas.apvs.domain.Report; import ch.cern.atlas.apvs.eventbus.shared.RemoteEventBus; import ch.cern.atlas.apvs.eventbus.shared.RequestRemoteEvent; import ch.cern.atlas.apvs.ptu.shared.MeasurementChangedEvent; import ch.cern.atlas.apvs.ptu.shared.PtuIdsChangedEvent; public class PtuClientHandler extends PtuReconnectHandler { private static final Logger logger = Logger .getLogger(PtuClientHandler.class.getName()); private final RemoteEventBus eventBus; private SortedMap<String, Ptu> ptus; private boolean ptuIdsChanged = false; private Map<String, Set<String>> measurementChanged = new HashMap<String, Set<String>>(); PreparedStatement historyQueryCount; PreparedStatement historyQuery; public PtuClientHandler(ClientBootstrap bootstrap, final RemoteEventBus eventBus) { super(bootstrap); this.eventBus = eventBus; init(); RequestRemoteEvent.register(eventBus, new RequestRemoteEvent.Handler() { @Override public void onRequestEvent(RequestRemoteEvent event) { String type = event.getRequestedClassName(); if (type.equals(PtuIdsChangedEvent.class.getName())) { eventBus.fireEvent(new PtuIdsChangedEvent(getPtuIds())); } else if (type.equals(MeasurementChangedEvent.class.getName())) { List<Measurement> m = getMeasurements(); System.err.println("Getting all meas " + m.size()); for (Iterator<Measurement> i = m.iterator(); i.hasNext();) { eventBus.fireEvent(new MeasurementChangedEvent(i.next())); } } } }); } @Override public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { logger.info(e.toString()); } super.handleUpstream(ctx, e); } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // handle closed connection init(); eventBus.fireEvent(new PtuIdsChangedEvent(new ArrayList<String>())); super.channelClosed(ctx, e); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Print out the line received from the server. String line = (String) e.getMessage(); // System.err.println(line); List<Message> list; try { list = PtuJsonReader.jsonToJava(line); for (Iterator<Message> i = list.iterator(); i.hasNext();) { Message message = i.next(); if (message instanceof Measurement) { handleMessage((Measurement) message); } else if (message instanceof Report) { handleMessage((Report) message); } else if (message instanceof Event) { handleMessage((Event) message); } else if (message instanceof Error) { handleMessage((Error) message); } else { System.err.println("Error: unknown Message Type: " + message.getType()); } } } catch (IOException ioe) { // TODO Auto-generated catch block ioe.printStackTrace(); } } private void handleMessage(Measurement measurement) { String ptuId = measurement.getPtuId(); Ptu ptu = ptus.get(ptuId); if (ptu == null) { ptu = new Ptu(ptuId); ptus.put(ptuId, ptu); ptuIdsChanged = true; } String sensor = measurement.getName(); History history = ptu.getHistory(sensor); if (history == null) { // check on history and load from DB if ((historyQuery != null) && (historyQueryCount != null)) { long PERIOD = 36; // hours Date then = new Date(new Date().getTime() - (PERIOD * 3600000)); String timestamp = PtuConstants.timestampFormat.format(then); try { historyQueryCount.setString(1, sensor); historyQueryCount.setString(2, ptuId); historyQueryCount.setString(3, timestamp); historyQuery.setString(1, sensor); historyQuery.setString(2, ptuId); historyQuery.setString(3, timestamp); ResultSet result = historyQueryCount.executeQuery(); result.next(); int n = result.getInt(1); result.close(); int MAX_ENTRIES = 1000; long MIN_INTERVAL = 5000; // ms if (n > 0) { // limit entries if (n > MAX_ENTRIES) n = 1000; Deque<Number[]> data = new ArrayDeque<Number[]>(n); long lastTime = new Date().getTime(); result = historyQuery.executeQuery(); while (result.next() && (data.size() <= n)) { long time = result.getTimestamp(1).getTime(); // limit entry separation (reverse order // !!!) if (lastTime - time > MIN_INTERVAL) { lastTime = time; Number[] entry = new Number[2]; entry[0] = time; entry[1] = Double.parseDouble(result .getString(2)); data.addFirst(entry); } } result.close(); System.err .println("Creating history for " + ptuId + " " + sensor + " " + data.size() + " entries"); history = new History(data.toArray(new Number[data .size()][]), measurement.getUnit()); ptu.setHistory(sensor, history); } } catch (SQLException ex) { System.err.println(ex); } } } ptu.addMeasurement(measurement); Set<String> changed = measurementChanged.get(ptuId); if (changed == null) { changed = new HashSet<String>(); measurementChanged.put(ptuId, changed); } changed.add(measurement.getName()); // duplicate entries will not be added if (history != null) { history.addEntry(measurement.getDate().getTime(), measurement.getValue()); } sendEvents(); } private void handleMessage(Report report) { System.err.println(report.getType() + " NOT YET IMPLEMENTED"); } private void handleMessage(Event event) { System.err.println(event.getType() + " NOT YET IMPLEMENTED"); } private void handleMessage(Error error) { System.err.println(error.getType() + " NOT YET IMPLEMENTED"); } private void init() { ptus = new TreeMap<String, Ptu>(); } private synchronized void sendEvents() { // fire all at the end // FIXME we can still add MeasurementNamesChanged if (ptuIdsChanged) { eventBus.fireEvent(new PtuIdsChangedEvent(new ArrayList<String>( ptus.keySet()))); ptuIdsChanged = false; } for (Iterator<String> i = measurementChanged.keySet().iterator(); i .hasNext();) { String id = i.next(); for (Iterator<String> j = measurementChanged.get(id).iterator(); j .hasNext();) { Measurement m = ptus.get(id).getMeasurement(j.next()); eventBus.fireEvent(new MeasurementChangedEvent(m)); } } measurementChanged.clear(); } public Ptu getPtu(String ptuId) { return ptus.get(ptuId); } public List<String> getPtuIds() { List<String> list = new ArrayList<String>(ptus.keySet()); Collections.sort(list); return list; } public List<Measurement> getMeasurements() { List<Measurement> m = new ArrayList<Measurement>(); for (Iterator<Ptu> i = ptus.values().iterator(); i.hasNext();) { m.addAll(i.next().getMeasurements()); } return m; } public void connect(String dbUrl) { System.err.println("Connecting to DB " + dbUrl); try { - DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); +// DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); + DriverManager.registerDriver(new net.sf.log4jdbc.DriverSpy()); Connection connection = DriverManager.getConnection(dbUrl); historyQueryCount = connection .prepareStatement("select count(*) from tbl_measurements " + "join tbl_devices on tbl_measurements.device_id = tbl_devices.id " + "where sensor = ? " + "and name = ? " + "and datetime > timestamp ?"); historyQuery = connection .prepareStatement("select DATETIME, VALUE from tbl_measurements " + "join tbl_devices on tbl_measurements.device_id = tbl_devices.id " + "where SENSOR = ? " + "and NAME = ? " + "and DATETIME > timestamp ? " + "order by DATETIME desc"); } catch (SQLException e) { - e.printStackTrace(); System.err.println(e); } } } diff --git a/apvs/src/main/java/ch/cern/atlas/apvs/server/PtuServiceImpl.java b/apvs/src/main/java/ch/cern/atlas/apvs/server/PtuServiceImpl.java index 5ed214d0..ebcdf51c 100644 --- a/apvs/src/main/java/ch/cern/atlas/apvs/server/PtuServiceImpl.java +++ b/apvs/src/main/java/ch/cern/atlas/apvs/server/PtuServiceImpl.java @@ -1,130 +1,130 @@ package ch.cern.atlas.apvs.server; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.Executors; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import ch.cern.atlas.apvs.client.event.ServerSettingsChangedEvent; import ch.cern.atlas.apvs.client.service.PtuService; import ch.cern.atlas.apvs.client.settings.ServerSettings; import ch.cern.atlas.apvs.domain.History; import ch.cern.atlas.apvs.domain.Measurement; import ch.cern.atlas.apvs.domain.Ptu; import ch.cern.atlas.apvs.eventbus.shared.RemoteEventBus; import ch.cern.atlas.apvs.ptu.server.PtuClientHandler; import ch.cern.atlas.apvs.ptu.server.PtuPipelineFactory; /** * @author Mark Donszelmann */ @SuppressWarnings("serial") public class PtuServiceImpl extends ResponsePollService implements PtuService { private static final int DEFAULT_PTU_PORT = 4005; // private static final int DEFAULT_DB_PORT = 1521; private String ptuUrl; private String dbUrl; private RemoteEventBus eventBus; private PtuClientHandler ptuClientHandler; public PtuServiceImpl() { System.out.println("Creating PtuService..."); eventBus = APVSServerFactory.getInstance().getEventBus(); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); System.out.println("Starting PtuService..."); ServerSettingsChangedEvent.subscribe(eventBus, new ServerSettingsChangedEvent.Handler() { @Override public void onServerSettingsChanged( ServerSettingsChangedEvent event) { ServerSettings settings = event.getServerSettings(); if (settings != null) { String url = settings .get(ServerSettings.settingNames[0]); if ((url != null) && !url.equals(ptuUrl)) { ptuUrl = url; String[] s = ptuUrl.split(":", 2); String host = s[0]; int port = s.length > 1 ? Integer .parseInt(s[1]) : DEFAULT_PTU_PORT; System.err.println("Setting PTU to " + host + ":" + port); ptuClientHandler.connect(new InetSocketAddress( host, port)); } url = settings.get(ServerSettings.settingNames[3]); if ((url != null) && !url.equals(dbUrl)) { dbUrl = url; - ptuClientHandler.connect("jdbc:oracle:thin:"+dbUrl); + ptuClientHandler.connect("jdbc:log4jdbc:oracle:thin:"+dbUrl); } } } }); // Configure the client. ClientBootstrap bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); ptuClientHandler = new PtuClientHandler(bootstrap, eventBus); // Configure the pipeline factory. bootstrap.setPipelineFactory(new PtuPipelineFactory(ptuClientHandler)); } @Override public Ptu getPtu(String ptuId) { return ptuClientHandler != null ? ptuClientHandler.getPtu(ptuId) : null; } @Override public Measurement getMeasurement(String ptuId, String name) { Ptu ptu = getPtu(ptuId); return ptu != null ? ptu.getMeasurement(name) : null; } public History getHistory(String ptuId, String name) { Ptu ptu = getPtu(ptuId); return ptu != null ? ptu.getHistory(name) : null; } public Map<String, History> getHistories(String name) { Map<String, History> result = new HashMap<String, History>(); if (ptuClientHandler == null) { return result; } for (Iterator<String> i = ptuClientHandler.getPtuIds().iterator(); i .hasNext();) { String ptuId = i.next(); Ptu ptu = ptuClientHandler.getPtu(ptuId); if (ptu != null) { result.put(ptuId, ptu.getHistory(name)); } } return result; } }
false
false
null
null
diff --git a/src/main/java/org/aksw/dependency/graph/matching/NaiveSubgraphMatcher.java b/src/main/java/org/aksw/dependency/graph/matching/NaiveSubgraphMatcher.java index b470b81..cb9c783 100644 --- a/src/main/java/org/aksw/dependency/graph/matching/NaiveSubgraphMatcher.java +++ b/src/main/java/org/aksw/dependency/graph/matching/NaiveSubgraphMatcher.java @@ -1,105 +1,107 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.aksw.dependency.graph.matching; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; import org.aksw.dependency.graph.ColoredDirectedGraph; import org.aksw.dependency.graph.ColoredEdge; import org.aksw.dependency.graph.Node; import org.aksw.dependency.util.SubsetGenerator; /** * * @author ngonga */ public class NaiveSubgraphMatcher implements SubGraphMatcher { @Override - public List<List<Node>> getMatchingSubgraphs(ColoredDirectedGraph largerGraph, ColoredDirectedGraph smallerGraph) { + public Set<Set<Node>> getMatchingSubgraphs(ColoredDirectedGraph largerGraph, ColoredDirectedGraph smallerGraph) { List<Node> largerGraphNodes = new ArrayList<>(largerGraph.vertexSet()); List<Node> smallerGraphNodes = new ArrayList<>(smallerGraph.vertexSet()); - List<List<Node>> result = new ArrayList<List<Node>>(); + Set<Set<Node>> result = new HashSet<>(); if (largerGraph.vertexSet().size() < smallerGraph.vertexSet().size()) { return result; } List<List<Node>> largeGraphSubsets = SubsetGenerator.getSubsets(largerGraphNodes, smallerGraphNodes.size()); List<List<Node>> smallGraphSubsets = SubsetGenerator.getSubsets(smallerGraphNodes, smallerGraphNodes.size()); for (List<Node> large : largeGraphSubsets) { for (List<Node> small : smallGraphSubsets) { if (matches(largerGraph, smallerGraph, large, small)) { - result.add(large); + result.add(new HashSet<>(large)); } } } return result; } /* * Checks whether the graph spawned by the nodes described by * smallerGraphNodes is a subgraph of the graph spawned by largerGraphNodes * in largerGraph */ public boolean matches(ColoredDirectedGraph largerGraph, ColoredDirectedGraph smallerGraph, List<Node> largerGraphNodes, List<Node> smallerGraphNodes) { //test 1: node labels for (int i = 0; i < smallerGraphNodes.size(); i++) { - if (!smallerGraphNodes.get(i).equals(largerGraphNodes.get(i))) { + if (!smallerGraphNodes.get(i).getLabel().equals(largerGraphNodes.get(i).getLabel())) { return false; } } //test 2: edges for (int i = 0; i < smallerGraphNodes.size(); i++) { for (int j = 0; j < smallerGraphNodes.size(); j++) { //check for edge in small graph if (smallerGraph.containsEdge(smallerGraphNodes.get(i), smallerGraphNodes.get(j))) { if (!largerGraph.containsEdge(largerGraphNodes.get(i), largerGraphNodes.get(j))) { return false; } } } } - return false; + return true; } public static void main(String args[]) { ColoredDirectedGraph large = new ColoredDirectedGraph(); ColoredDirectedGraph small = new ColoredDirectedGraph(); List<Node> lNodes = new ArrayList<>(); for (int i = 0; i <= 6; i++) { lNodes.add(new Node(i + "")); large.addVertex(lNodes.get(i)); } List<Node> sNodes = new ArrayList<>(); for (int i = 0; i <= 2; i++) { sNodes.add(new Node(i + "")); small.addVertex(sNodes.get(i)); } large.addEdge(lNodes.get(0), lNodes.get(1), new ColoredEdge("edge", "red")); large.addEdge(lNodes.get(1), lNodes.get(2), new ColoredEdge("edge", "red")); large.addEdge(lNodes.get(2), lNodes.get(0), new ColoredEdge("edge", "red")); large.addEdge(lNodes.get(3), lNodes.get(4), new ColoredEdge("edge", "red")); large.addEdge(lNodes.get(4), lNodes.get(5), new ColoredEdge("edge", "red")); large.addEdge(lNodes.get(5), lNodes.get(3), new ColoredEdge("edge", "red")); large.addEdge(lNodes.get(2), lNodes.get(3), new ColoredEdge("edge", "red")); small.addEdge(sNodes.get(0), sNodes.get(1), new ColoredEdge("edge", "red")); small.addEdge(sNodes.get(1), sNodes.get(2), new ColoredEdge("edge", "red")); small.addEdge(sNodes.get(2), sNodes.get(0), new ColoredEdge("edge", "red")); System.out.println(new NaiveSubgraphMatcher().getMatchingSubgraphs(large, small)); } } diff --git a/src/main/java/org/aksw/dependency/graph/matching/SubGraphMatcher.java b/src/main/java/org/aksw/dependency/graph/matching/SubGraphMatcher.java index 2cd8d81..581f0f9 100644 --- a/src/main/java/org/aksw/dependency/graph/matching/SubGraphMatcher.java +++ b/src/main/java/org/aksw/dependency/graph/matching/SubGraphMatcher.java @@ -1,17 +1,18 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.aksw.dependency.graph.matching; import java.util.List; +import java.util.Set; import org.aksw.dependency.graph.ColoredDirectedGraph; import org.aksw.dependency.graph.Node; /** * * @author ngonga */ public interface SubGraphMatcher { - List<List<Node>> getMatchingSubgraphs(ColoredDirectedGraph largerGraph, ColoredDirectedGraph smallerGraph); + Set<Set<Node>> getMatchingSubgraphs(ColoredDirectedGraph largerGraph, ColoredDirectedGraph smallerGraph); } diff --git a/src/main/java/org/aksw/dependency/util/SubsetGenerator.java b/src/main/java/org/aksw/dependency/util/SubsetGenerator.java index c95b804..49cdd64 100644 --- a/src/main/java/org/aksw/dependency/util/SubsetGenerator.java +++ b/src/main/java/org/aksw/dependency/util/SubsetGenerator.java @@ -1,58 +1,57 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.aksw.dependency.util; import java.util.ArrayList; import java.util.List; import org.aksw.dependency.graph.Node; /** * * @author ngonga */ public class SubsetGenerator { public static List<List<Node>> getSubsets(List<Node> set, int subsetSize) { List<List<Node>> oldQueue = new ArrayList<>(); List<List<Node>> newQueue = new ArrayList<>(); if (subsetSize > 0 && subsetSize <= set.size()) { for (Node node : set) { List l = new ArrayList(); l.add(node); oldQueue.add(l); } for (int i = 1; i < subsetSize; i++) { + newQueue = new ArrayList<>(); for (List<Node> node : oldQueue) { //get remaining objects for(Node n: set) { if(!node.contains(n)) { List copy = new ArrayList(node); copy.add(n); newQueue.add(copy); } } } oldQueue = newQueue; } } return newQueue; } public static void main(String args[]) { List<Node> set = new ArrayList<>(); for(int i=0; i<10; i++) { set.add(new Node(i+"")); } System.out.println(getSubsets(set, 2)); } - - }
false
false
null
null
diff --git a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/DefaultProjectClasspathEntry.java b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/DefaultProjectClasspathEntry.java index 80a3690ca..aca9e725e 100644 --- a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/DefaultProjectClasspathEntry.java +++ b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/DefaultProjectClasspathEntry.java @@ -1,347 +1,350 @@ /******************************************************************************* * Copyright (c) 2000, 2005 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.jdt.internal.launching; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.jdt.core.ClasspathContainerInitializer; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.launching.IRuntimeClasspathEntry; import org.eclipse.jdt.launching.IRuntimeContainerComparator; import org.eclipse.jdt.launching.JavaRuntime; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * Default user classpath entries for a Java project */ public class DefaultProjectClasspathEntry extends AbstractRuntimeClasspathEntry { public static final String TYPE_ID = "org.eclipse.jdt.launching.classpathentry.defaultClasspath"; //$NON-NLS-1$ /** * Whether only exported entries should be on the runtime classpath. * By default all entries are on the runtime classpath. */ private boolean fExportedEntriesOnly = false; /** * Default constructor need to instantiate extensions */ public DefaultProjectClasspathEntry() { } /** * Constructs a new classpath entry for the given project. * * @param project Java project */ public DefaultProjectClasspathEntry(IJavaProject project) { setJavaProject(project); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.launching.AbstractRuntimeClasspathEntry#buildMemento(org.w3c.dom.Document, org.w3c.dom.Element) */ protected void buildMemento(Document document, Element memento) throws CoreException { memento.setAttribute("project", getJavaProject().getElementName()); //$NON-NLS-1$ memento.setAttribute("exportedEntriesOnly", Boolean.toString(fExportedEntriesOnly)); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry2#initializeFrom(org.w3c.dom.Element) */ public void initializeFrom(Element memento) throws CoreException { String name = memento.getAttribute("project"); //$NON-NLS-1$ if (name == null) { abort(LaunchingMessages.DefaultProjectClasspathEntry_3, null); } IJavaProject project = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(name)); setJavaProject(project); name = memento.getAttribute("exportedEntriesOnly"); //$NON-NLS-1$ if (name == null) { fExportedEntriesOnly = false; } else { fExportedEntriesOnly = Boolean.valueOf(name).booleanValue(); } } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry2#getTypeId() */ public String getTypeId() { return TYPE_ID; } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry#getType() */ public int getType() { return OTHER; } protected IProject getProject() { return getJavaProject().getProject(); } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry#getLocation() */ public String getLocation() { return getProject().getLocation().toOSString(); } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry#getPath() */ public IPath getPath() { return getProject().getFullPath(); } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry#getResource() */ public IResource getResource() { return getProject(); } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry2#getRuntimeClasspathEntries(org.eclipse.debug.core.ILaunchConfiguration) */ public IRuntimeClasspathEntry[] getRuntimeClasspathEntries(ILaunchConfiguration configuration) throws CoreException { IClasspathEntry entry = JavaCore.newProjectEntry(getJavaProject().getProject().getFullPath()); List classpathEntries = new ArrayList(5); List expanding = new ArrayList(5); expandProject(entry, classpathEntries, expanding); IRuntimeClasspathEntry[] runtimeEntries = new IRuntimeClasspathEntry[classpathEntries.size()]; for (int i = 0; i < runtimeEntries.length; i++) { Object e = classpathEntries.get(i); if (e instanceof IClasspathEntry) { IClasspathEntry cpe = (IClasspathEntry)e; runtimeEntries[i] = new RuntimeClasspathEntry(cpe); } else { runtimeEntries[i] = (IRuntimeClasspathEntry)e; } } // remove bootpath entries - this is a default user classpath List ordered = new ArrayList(runtimeEntries.length); for (int i = 0; i < runtimeEntries.length; i++) { if (runtimeEntries[i].getClasspathProperty() == IRuntimeClasspathEntry.USER_CLASSES) { ordered.add(runtimeEntries[i]); } } return (IRuntimeClasspathEntry[]) ordered.toArray(new IRuntimeClasspathEntry[ordered.size()]); } /** * Returns the transitive closure of classpath entries for the * given project entry. * * @param projectEntry project classpath entry * @param expandedPath a list of entries already expanded, should be empty * to begin, and contains the result * @param expanding a list of projects that have been or are currently being * expanded (to detect cycles) * @exception CoreException if unable to expand the classpath */ private void expandProject(IClasspathEntry projectEntry, List expandedPath, List expanding) throws CoreException { expanding.add(projectEntry); // 1. Get the raw classpath // 2. Replace source folder entries with a project entry IPath projectPath = projectEntry.getPath(); IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(projectPath.lastSegment()); if (res == null) { // add project entry and return expandedPath.add(projectEntry); return; } IJavaProject project = (IJavaProject)JavaCore.create(res); if (project == null || !project.getProject().isOpen() || !project.exists()) { // add project entry and return expandedPath.add(projectEntry); return; } IClasspathEntry[] buildPath = project.getRawClasspath(); List unexpandedPath = new ArrayList(buildPath.length); boolean projectAdded = false; for (int i = 0; i < buildPath.length; i++) { IClasspathEntry classpathEntry = buildPath[i]; if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (!projectAdded) { projectAdded = true; unexpandedPath.add(projectEntry); } } else { // add exported entires, as configured if (classpathEntry.isExported()) { unexpandedPath.add(classpathEntry); } else if (!isExportedEntriesOnly() || project.equals(getJavaProject())) { // add non exported entries from root project or if we are including all entries unexpandedPath.add(classpathEntry); } } } // 3. expand each project entry (except for the root project) // 4. replace each container entry with a runtime entry associated with the project Iterator iter = unexpandedPath.iterator(); while (iter.hasNext()) { IClasspathEntry entry = (IClasspathEntry)iter.next(); if (entry == projectEntry) { expandedPath.add(entry); } else { switch (entry.getEntryKind()) { case IClasspathEntry.CPE_PROJECT: if (!expanding.contains(entry)) { expandProject(entry, expandedPath, expanding); } break; case IClasspathEntry.CPE_CONTAINER: IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), project); int property = -1; if (container != null) { switch (container.getKind()) { case IClasspathContainer.K_APPLICATION: property = IRuntimeClasspathEntry.USER_CLASSES; break; case IClasspathContainer.K_DEFAULT_SYSTEM: property = IRuntimeClasspathEntry.STANDARD_CLASSES; break; case IClasspathContainer.K_SYSTEM: property = IRuntimeClasspathEntry.BOOTSTRAP_CLASSES; break; } IRuntimeClasspathEntry r = JavaRuntime.newRuntimeContainerClasspathEntry(entry.getPath(), property, project); // check for duplicate/redundant entries boolean duplicate = false; ClasspathContainerInitializer initializer = JavaCore.getClasspathContainerInitializer(r.getPath().segment(0)); for (int i = 0; i < expandedPath.size(); i++) { Object o = expandedPath.get(i); if (o instanceof IRuntimeClasspathEntry) { IRuntimeClasspathEntry re = (IRuntimeClasspathEntry)o; if (re.getType() == IRuntimeClasspathEntry.CONTAINER) { if (container instanceof IRuntimeContainerComparator) { duplicate = ((IRuntimeContainerComparator)container).isDuplicate(re.getPath()); } else { ClasspathContainerInitializer initializer2 = JavaCore.getClasspathContainerInitializer(re.getPath().segment(0)); Object id1 = null; Object id2 = null; if (initializer == null) { id1 = r.getPath().segment(0); } else { id1 = initializer.getComparisonID(r.getPath(), project); } if (initializer2 == null) { id2 = re.getPath().segment(0); } else { id2 = initializer2.getComparisonID(re.getPath(), project); } if (id1 == null) { duplicate = id2 == null; } else { duplicate = id1.equals(id2); } } if (duplicate) { break; } } } } if (!duplicate) { expandedPath.add(r); } } break; case IClasspathEntry.CPE_VARIABLE: if (entry.getPath().segment(0).equals(JavaRuntime.JRELIB_VARIABLE)) { IRuntimeClasspathEntry r = JavaRuntime.newVariableRuntimeClasspathEntry(entry.getPath()); r.setSourceAttachmentPath(entry.getSourceAttachmentPath()); r.setSourceAttachmentRootPath(entry.getSourceAttachmentRootPath()); r.setClasspathProperty(IRuntimeClasspathEntry.STANDARD_CLASSES); if (!expandedPath.contains(r)) { expandedPath.add(r); } break; } // fall through if not the special JRELIB variable default: if (!expandedPath.contains(entry)) { expandedPath.add(entry); } break; } } } return; } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry2#isComposite() */ public boolean isComposite() { return true; } /* (non-Javadoc) * @see org.eclipse.jdt.launching.IRuntimeClasspathEntry2#getName() */ public String getName() { + if (isExportedEntriesOnly()) { + return MessageFormat.format(LaunchingMessages.DefaultProjectClasspathEntry_2, new String[] {getJavaProject().getElementName()}); + } return MessageFormat.format(LaunchingMessages.DefaultProjectClasspathEntry_4, new String[] {getJavaProject().getElementName()}); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { if (obj instanceof DefaultProjectClasspathEntry) { DefaultProjectClasspathEntry entry = (DefaultProjectClasspathEntry) obj; return entry.getJavaProject().equals(getJavaProject()) && entry.isExportedEntriesOnly() == isExportedEntriesOnly(); } return false; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return getJavaProject().hashCode(); } /** * Sets whether the runtime classpath computaion should only * include exported entries in referenced projects. * * @param exportedOnly * @since 3.2 */ public void setExportedEntriesOnly(boolean exportedOnly) { fExportedEntriesOnly = exportedOnly; } /** * Returns whether the classpath computation only includes exported * entries in referenced projects. * * @return * @since 3.2 */ public boolean isExportedEntriesOnly() { return fExportedEntriesOnly; } } diff --git a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/LaunchingMessages.java b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/LaunchingMessages.java index c8950250c..f08c8f988 100644 --- a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/LaunchingMessages.java +++ b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/LaunchingMessages.java @@ -1,200 +1,202 @@ /********************************************************************** * Copyright (c) 2000, 2005 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 - Initial API and implementation **********************************************************************/ package org.eclipse.jdt.internal.launching; import org.eclipse.osgi.util.NLS; public class LaunchingMessages extends NLS { private static final String BUNDLE_NAME = "org.eclipse.jdt.internal.launching.LaunchingMessages";//$NON-NLS-1$ public static String AbstractJavaLaunchConfigurationDelegate_Java_project_not_specified_9; public static String AbstractJavaLaunchConfigurationDelegate_JRE_home_directory_for__0__does_not_exist___1__6; public static String AbstractJavaLaunchConfigurationDelegate_JRE_home_directory_not_specified_for__0__5; public static String AbstractJavaLaunchConfigurationDelegate_Main_type_not_specified_11; public static String AbstractJavaLaunchConfigurationDelegate_Project_does_not_exist_or_is_not_a_Java_project_10; public static String AbstractJavaLaunchConfigurationDelegate_The_specified_JRE_installation_does_not_exist_4; public static String AbstractJavaLaunchConfigurationDelegate_Working_directory_does_not_exist___0__12; public static String ClasspathContainerSourceContainerTypeDelegate_5; public static String ClasspathContainerSourceContainerTypeDelegate_6; public static String ClasspathContainerSourceContainerTypeDelegate_7; public static String ClasspathVariableSourceContainerTypeDelegate_5; public static String ClasspathVariableSourceContainerTypeDelegate_6; public static String ClasspathVariableSourceContainerTypeDelegate_7; + public static String DefaultProjectClasspathEntry_2; + public static String DefaultProjectClasspathEntry_3; public static String DefaultProjectClasspathEntry_4; public static String JavaLocalApplicationLaunchConfigurationDelegate_Verifying_launch_attributes____1; public static String JavaLocalApplicationLaunchConfigurationDelegate_Creating_source_locator____2; public static String JavaLocalApplicationLaunchConfigurationDelegate_0; public static String JavaLocalApplicationLaunchConfigurationDelegate_1; public static String JavaProjectSourceContainerTypeDelegate_5; public static String JavaProjectSourceContainerTypeDelegate_6; public static String JavaProjectSourceContainerTypeDelegate_7; public static String JavaRemoteApplicationLaunchConfigurationDelegate_Connector_not_specified_2; public static String JavaRemoteApplicationLaunchConfigurationDelegate_Attaching_to__0_____1; public static String JavaRemoteApplicationLaunchConfigurationDelegate_Verifying_launch_attributes____1; public static String JavaRemoteApplicationLaunchConfigurationDelegate_Creating_source_locator____2; public static String JavaAppletLaunchConfigurationDelegate_Starting_Applet__0_____1; public static String JavaAppletLaunchConfigurationDelegate_Verifying_launch_attributes____1; public static String JavaAppletLaunchConfigurationDelegate_Creating_source_locator____2; public static String JavaRuntime_badFormat; public static String JavaRuntime_exceptionOccurred; public static String JavaRuntime_exceptionsOccurred; public static String JavaRuntime_Library_location_element_incorrectly_specified_3; public static String JavaRuntime_VM_element_specified_with_no_id_attribute_2; public static String JavaRuntime_VM_type_element_with_unknown_id_1; public static String JavaRuntime_Specified_VM_install_type_does_not_exist___0__2; public static String JavaRuntime_VM_not_fully_specified_in_launch_configuration__0____missing_VM_name__Reverting_to_default_VM__1; public static String JavaRuntime_Specified_VM_install_not_found__type__0___name__1__2; public static String JavaRuntime_Launch_configuration__0__references_non_existing_project__1___1; public static String JavaRuntime_Could_not_resolve_classpath_container___0__1; public static String JavaRuntime_Classpath_references_non_existant_project___0__3; public static String JavaRuntime_Classpath_references_non_existant_archive___0__4; public static String JavaRuntime_26; public static String JavaRuntime_27; public static String JavaRuntime_28; public static String JavaRuntime_31; public static String JavaRuntime_32; public static String JavaRuntime_0; public static String LaunchingPlugin_Exception_occurred_reading_vmConnectors_extensions_1; public static String LaunchingPlugin_32; public static String LaunchingPlugin_33; public static String LaunchingPlugin_34; public static String LaunchingPlugin_0; public static String LaunchingPlugin_1; public static String libraryLocation_assert_libraryNotNull; public static String SocketAttachConnector_Failed_to_connect_to_remote_VM_1; public static String SocketAttachConnector_Socket_attaching_connector_not_available_3; public static String SocketAttachConnector_Standard__Socket_Attach__4; public static String SocketAttachConnector_Failed_to_connect_to_remote_VM_because_of_unknown_host____0___1; public static String SocketAttachConnector_Failed_to_connect_to_remote_VM_as_connection_was_refused_2; public static String SocketAttachConnector_Connecting____1; public static String SocketAttachConnector_Configuring_connection____1; public static String SocketAttachConnector_Establishing_connection____2; public static String StandardVMDebugger_Could_not_find_a_free_socket_for_the_debugger_1; public static String StandardVMDebugger_Couldn__t_connect_to_VM_4; public static String StandardVMDebugger_Couldn__t_connect_to_VM_5; public static String StandardVMDebugger_Couldn__t_find_an_appropriate_debug_connector_2; public static String StandardVMDebugger_Launching_VM____1; public static String StandardVMDebugger_Finding_free_socket____2; public static String StandardVMDebugger_Constructing_command_line____3; public static String StandardVMDebugger_Starting_virtual_machine____4; public static String StandardVMDebugger_Establishing_debug_connection____5; public static String StandardVMRunner__0____1___2; public static String StandardVMRunner__0__at_localhost__1__1; public static String StandardVMRunner_Specified_working_directory_does_not_exist_or_is_not_a_directory___0__3; public static String StandardVMRunner_Launching_VM____1; public static String StandardVMRunner_Constructing_command_line____2; public static String StandardVMRunner_Starting_virtual_machine____3; public static String StandardVMRunner_Unable_to_locate_executable_for__0__1; public static String StandardVMRunner_Specified_executable__0__does_not_exist_for__1__4; public static String StandardVMType_Not_a_JDK_Root__Java_executable_was_not_found_1; public static String StandardVMType_ok_2; public static String StandardVMType_Standard_VM_3; public static String StandardVMType_Not_a_JDK_root__System_library_was_not_found__1; public static String StandardVMType_Standard_VM_not_supported_on_MacOS__1; public static String vmInstall_assert_idNotNull; public static String vmInstall_assert_typeNotNull; public static String vmInstallType_duplicateVM; public static String vmRunnerConfig_assert_classNotNull; public static String vmRunnerConfig_assert_classPathNotNull; public static String vmRunnerConfig_assert_programArgsNotNull; public static String vmRunnerConfig_assert_vmArgsNotNull; public static String RuntimeClasspathEntry_An_exception_occurred_generating_runtime_classpath_memento_8; public static String RuntimeClasspathEntry_Unable_to_recover_runtime_class_path_entry_type_2; public static String RuntimeClasspathEntry_Unable_to_recover_runtime_class_path_entry_location_3; public static String RuntimeClasspathEntry_Unable_to_recover_runtime_class_path_entry___missing_project_name_4; public static String RuntimeClasspathEntry_Unable_to_recover_runtime_class_path_entry___missing_archive_path_5; public static String RuntimeClasspathEntry_Unable_to_recover_runtime_class_path_entry___missing_variable_name_6; public static String RuntimeClasspathEntry_Illegal_classpath_entry__0__1; public static String JREContainer_JRE_System_Library_1; public static String SocketAttachConnector_Port_unspecified_for_remote_connection__2; public static String SocketAttachConnector_Hostname_unspecified_for_remote_connection__4; public static String JREContainerInitializer_JRE_referenced_by_classpath_container__0__does_not_exist__1; public static String JREContainerInitializer_Classpath_entry__0__does_not_refer_to_an_existing_library__2; public static String JREContainerInitializer_Classpath_entry__0__does_not_refer_to_a_library__3; public static String JREContainerInitializer_Default_System_Library_1; public static String ArchiveSourceLocation_Unable_to_create_memento_for_archive_source_location__0__1; public static String ArchiveSourceLocation_Unable_to_initialize_source_location___missing_archive_path__3; public static String ArchiveSourceLocation_Exception_occurred_initializing_source_location__5; public static String ArchiveSourceLocation_Unable_to_locate_source_element_in_archive__0__1; public static String ArchiveSourceLocation_Exception_occurred_while_detecting_root_source_directory_in_archive__0__1; public static String ArchiveSourceLocation_Exception_occurred_while_detecting_root_source_directory_in_archive__0__2; public static String DirectorySourceLocation_Unable_to_create_memento_for_directory_source_location__0__1; public static String DirectorySourceLocation_Unable_to_initialize_source_location___missing_directory_path_3; public static String DirectorySourceLocation_Unable_to_initialize_source_location___directory_does_not_exist___0__4; public static String DirectorySourceLocation_Exception_occurred_initializing_source_location__5; public static String JavaProjectSourceLocation_Unable_to_create_memento_for_Java_project_source_location__0__1; public static String JavaProjectSourceLocation_Unable_to_initialize_source_location___missing_project_name_3; public static String JavaProjectSourceLocation_Exception_occurred_initializing_source_location__4; public static String JavaSourceLocator_Illegal_to_have_a_container_resolved_to_a_container_1; public static String JavaSourceLocator_Unable_to_create_memento_for_Java_source_locator__4; public static String JavaSourceLocator_Unable_to_restore_Java_source_locator___invalid_format__6; public static String JavaSourceLocator_Unable_to_restore_Java_source_locator___invalid_format__10; public static String JavaSourceLocator_Unable_to_restore_source_location___class_not_found___0__11; public static String JavaSourceLocator_Unable_to_restore_source_location__12; public static String JavaSourceLocator_Unable_to_restore_Java_source_locator___invalid_format__14; public static String JavaSourceLocator_Exception_occurred_initializing_source_locator__15; public static String Standard11xVMType_Standard_1_1_x_VM_1; public static String PackageFragmentRootSourceLocation_Unable_to_create_memento_for_package_fragment_root_source_location__0__5; public static String PackageFragmentRootSourceLocation_Unable_to_initialize_source_location___missing_handle_identifier_for_package_fragment_root__6; public static String PackageFragmentRootSourceLocation_Unable_to_initialize_source_location___package_fragment_root_does_not_exist__7; public static String PackageFragmentRootSourceLocation_Exception_occurred_initializing_source_location__8; public static String JavaAppletLaunchConfigurationDelegate_No_launch_configuration_specified_1; public static String JavaAppletLaunchConfigurationDelegate_Could_not_build_HTML_file_for_applet_launch_1; public static String AbstractVMRunner_0; public static String AbstractJavaLaunchConfigurationDelegate_20; public static String PackageFragmentRootSourceContainerTypeDelegate_6; public static String PackageFragmentRootSourceContainerTypeDelegate_7; public static String PackageFragmentRootSourceContainerTypeDelegate_8; static { // load message values from bundle file NLS.initializeMessages(BUNDLE_NAME, LaunchingMessages.class); } public static String SocketAttachConnector_0; public static String AbstractVMInstall_0; public static String AbstractVMInstall_1; public static String AbstractVMInstall_3; public static String AbstractVMInstall_4; } \ No newline at end of file
false
false
null
null
diff --git a/src/gui/inputPanels/CoalescentView.java b/src/gui/inputPanels/CoalescentView.java index 82730b1..cc0c8e4 100644 --- a/src/gui/inputPanels/CoalescentView.java +++ b/src/gui/inputPanels/CoalescentView.java @@ -1,258 +1,267 @@ /******************************************************************** * * Copyright 2011 Brendan O'Fallon * * 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 gui.inputPanels; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.List; import gui.document.ACGDocument; import gui.inputPanels.Configurator.InputConfigException; import gui.inputPanels.DoubleModifierElement.ModType; import gui.inputPanels.PopSizeModelElement.PopSizeModel; import gui.widgets.Style; import gui.widgets.Stylist; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import org.w3c.dom.Element; /** * Represents a CoalescentModelElement graphically. Typically this is included in a DocMemberConfigPanel * @author brendano * */ public class CoalescentView extends JPanel { CoalescentModelElement coalModel; private JComboBox coalModelBox; private String[] coalModels = new String[]{"Constant size", "Exponential growth"}; private JComboBox recombModelBox; private String[] recombModels = new String[]{"None", "Constant rate"}; List<Element> params = new ArrayList<Element>(); List<Element> likelihoods = new ArrayList<Element>();; private JPanel popCenterPanel; private JPanel growthRatePanel; private DoubleParamView constPopView; private DoubleParamView baseSizeView; private DoubleParamView growthRateView; private DoubleParamView recView; private JPanel popPanel; private JPanel recPanel; private JPanel recCenterPanel; private Stylist stylist = new Stylist(); public CoalescentView(CoalescentModelElement coalModel) { this.coalModel = coalModel; stylist.addStyle(new Style() { public void apply(JComponent comp) { comp.setOpaque(false); comp.setAlignmentX(Component.LEFT_ALIGNMENT); } }); initComponents(); } public CoalescentView() { this( new CoalescentModelElement() ); } /** * Called when the coalescent model box has a new item selected */ protected void updateCoalModelBox() { if (coalModelBox.getSelectedIndex()==0) { coalModel.getPopSizeModel().setModelType( PopSizeModel.Constant ); popCenterPanel.remove(growthRatePanel); popCenterPanel.add(constPopView, BorderLayout.CENTER); popCenterPanel.revalidate(); } if (coalModelBox.getSelectedIndex()==1) { coalModel.getPopSizeModel().setModelType( PopSizeModel.ExpGrowth ); popCenterPanel.remove(constPopView); popCenterPanel.add(growthRatePanel, BorderLayout.CENTER); popCenterPanel.revalidate(); } popCenterPanel.repaint(); } /** * Obtain the CoalescentModelElement backing this view * @return */ public CoalescentModelElement getModel() { return coalModel; } /** * Replace the model backing this view with the given model. This also re-constructs all UI * components from scratch * @param coalescentModel */ public void setCoalModel(CoalescentModelElement coalescentModel) { this.coalModel = coalescentModel; this.removeAll(); initComponents(); updateView(); } /** * Called when recombination selection has changed */ protected void updateRecombModelBox() { if (recombModelBox.getSelectedIndex()==0) { coalModel.setUseRecombination(false); recCenterPanel.remove(recView); recCenterPanel.revalidate(); repaint(); } if (recombModelBox.getSelectedIndex()==1) { coalModel.setUseRecombination(true); recCenterPanel.add( recView, BorderLayout.CENTER); recCenterPanel.revalidate(); repaint(); } } /** * Update view components to reflect changes in model */ public void updateView() { if (coalModel.getPopSizeModel().getModelType() == PopSizeModel.Constant) coalModelBox.setSelectedIndex(0); if (coalModel.getPopSizeModel().getModelType() == PopSizeModel.ExpGrowth) coalModelBox.setSelectedIndex(1); - if (coalModel.getRecombModel()==null) - recombModelBox.setSelectedIndex(0); - else { + + if (coalModel.getUseRecombination()) { recombModelBox.setSelectedIndex(1); } + else { + recombModelBox.setSelectedIndex(0); + } constPopView.updateView(); baseSizeView.updateView(); growthRateView.updateView(); recView.updateView(); repaint(); } public void readNodesFromDocument(ACGDocument doc) throws InputConfigException { coalModel.readElements(doc); updateView(); } /** * Create GUI components */ private void initComponents() { setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); stylist.applyStyle(this); popPanel = new JPanel(); JPanel popTop = new JPanel(); stylist.applyStyle(popTop); stylist.applyStyle(popPanel); popPanel.setLayout(new BorderLayout()); popTop.add(new JLabel("Coalescent model:")); coalModelBox = new JComboBox(coalModels); coalModelBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { updateCoalModelBox(); } }); popTop.add(coalModelBox); popPanel.add(popTop, BorderLayout.NORTH); this.add(popPanel); popCenterPanel = new JPanel(); popCenterPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); stylist.applyStyle(popCenterPanel); popPanel.add(popCenterPanel, BorderLayout.CENTER); constPopView = new DoubleParamView("Population Size", coalModel.getPopSizeModel().getConstSizeModel()); constPopView.setPreferredSize(new Dimension(350, 36)); popCenterPanel.add( constPopView); baseSizeView = new DoubleParamView("Base Size", coalModel.getPopSizeModel().getBaseSizeModel()); baseSizeView.setPreferredSize(new Dimension(350, 36)); growthRateView = new DoubleParamView("Growth Rate", coalModel.getPopSizeModel().getGrowthRateModel()); growthRateView.setPreferredSize(new Dimension(350, 36)); growthRatePanel = new JPanel(); growthRatePanel.setOpaque(false); growthRatePanel.setLayout(new BoxLayout(growthRatePanel, BoxLayout.Y_AXIS)); growthRatePanel.add(baseSizeView); growthRatePanel.add(growthRateView); JSeparator sep = new JSeparator(JSeparator.VERTICAL); this.add(sep); recPanel = new JPanel(); stylist.applyStyle(recPanel); recPanel.setLayout(new BorderLayout()); JPanel recTop = new JPanel(); stylist.applyStyle(recTop); recCenterPanel = new JPanel(); stylist.applyStyle(recCenterPanel); recPanel.add(recTop, BorderLayout.NORTH); recView = new DoubleParamView("Recombination rate", coalModel.getRecombModel().getModel()); stylist.applyStyle(recView); recPanel.add(recCenterPanel, BorderLayout.CENTER); recTop.add(new JLabel("Recombination :")); recombModelBox = new JComboBox(recombModels); recombModelBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { updateRecombModelBox(); } }); - recombModelBox.setSelectedIndex(1); + + if (coalModel.getUseRecombination()) { + recombModelBox.setSelectedIndex(1); + } + else { + recombModelBox.setSelectedIndex(0); + } + recTop.add(recombModelBox); this.add(recPanel); } }
false
false
null
null
diff --git a/phresco-framework-impl/src/main/java/com/photon/phresco/framework/impl/ProjectManagerImpl.java b/phresco-framework-impl/src/main/java/com/photon/phresco/framework/impl/ProjectManagerImpl.java index 9fcfdce30..7c7737658 100644 --- a/phresco-framework-impl/src/main/java/com/photon/phresco/framework/impl/ProjectManagerImpl.java +++ b/phresco-framework-impl/src/main/java/com/photon/phresco/framework/impl/ProjectManagerImpl.java @@ -1,510 +1,527 @@ package com.photon.phresco.framework.impl; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.photon.phresco.api.ApplicationProcessor; import com.photon.phresco.commons.FrameworkConstants; import com.photon.phresco.commons.model.ApplicationInfo; import com.photon.phresco.commons.model.ArtifactGroup; import com.photon.phresco.commons.model.ArtifactGroupInfo; import com.photon.phresco.commons.model.ArtifactInfo; import com.photon.phresco.commons.model.Customer; import com.photon.phresco.commons.model.DownloadInfo; import com.photon.phresco.commons.model.ProjectInfo; import com.photon.phresco.commons.model.RepoInfo; import com.photon.phresco.configuration.Environment; import com.photon.phresco.exception.PhrescoException; import com.photon.phresco.framework.api.ProjectManager; import com.photon.phresco.plugins.model.Mojos.ApplicationHandler; import com.photon.phresco.plugins.util.MojoProcessor; import com.photon.phresco.service.client.api.ServiceClientConstant; import com.photon.phresco.service.client.api.ServiceManager; import com.photon.phresco.util.ArchiveUtil; import com.photon.phresco.util.ArchiveUtil.ArchiveType; import com.photon.phresco.util.Constants; import com.photon.phresco.util.FileUtil; import com.photon.phresco.util.PhrescoDynamicLoader; import com.photon.phresco.util.ProjectUtils; import com.photon.phresco.util.Utility; import com.phresco.pom.exception.PhrescoPomException; import com.phresco.pom.util.PomProcessor; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientResponse; public class ProjectManagerImpl implements ProjectManager, FrameworkConstants, Constants, ServiceClientConstant { private static final Logger S_LOGGER= Logger.getLogger(ProjectManagerImpl.class); private static boolean isDebugEnabled = S_LOGGER.isDebugEnabled(); private Map<String, ProjectInfo> projectInfosMap = null; public List<ProjectInfo> discover(String customerId) throws PhrescoException { if (isDebugEnabled) { S_LOGGER.debug("Entering Method ProjectManagerImpl.discover(String CustomerId)"); } File projectsHome = new File(Utility.getProjectHome()); if (isDebugEnabled) { S_LOGGER.debug("discover( ) projectHome = "+projectsHome); } if (!projectsHome.exists()) { return null; } projectInfosMap = new HashMap<String, ProjectInfo>(); List<ProjectInfo> projectInfos = new ArrayList<ProjectInfo>(); File[] appDirs = projectsHome.listFiles(); for (File appDir : appDirs) { if (appDir.isDirectory()) { // Only check the folders not files File[] dotPhrescoFolders = appDir.listFiles(new PhrescoFileNameFilter(FOLDER_DOT_PHRESCO)); if (ArrayUtils.isEmpty(dotPhrescoFolders)) { continue; // throw new PhrescoException(".phresco folder not found in project " + appDir.getName()); } File[] dotProjectFiles = dotPhrescoFolders[0].listFiles(new PhrescoFileNameFilter(PROJECT_INFO_FILE)); if (ArrayUtils.isEmpty(dotProjectFiles)) { throw new PhrescoException("project.info file not found in .phresco of project " + dotPhrescoFolders[0].getParent()); } fillProjects(dotProjectFiles[0], projectInfos, customerId); } } Iterator<Entry<String, ProjectInfo>> iterator = projectInfosMap.entrySet().iterator(); while (iterator.hasNext()) { projectInfos.add(iterator.next().getValue()); } return projectInfos; } public ProjectInfo getProject(String projectId, String customerId) throws PhrescoException { List<ProjectInfo> discover = discover(customerId); for (ProjectInfo projectInfo : discover) { if (projectInfo.getId().equals(projectId)) { return projectInfo; } } return null; } @Override public ProjectInfo getProject(String projectId, String customerId, String appId) throws PhrescoException { File[] appDirs = new File(Utility.getProjectHome()).listFiles(); for (File appDir : appDirs) { if (appDir.isDirectory()) { // Only check the folders not files File[] dotPhrescoFolders = appDir.listFiles(new PhrescoFileNameFilter(FOLDER_DOT_PHRESCO)); if (ArrayUtils.isEmpty(dotPhrescoFolders)) { throw new PhrescoException(".phresco folder not found in project " + appDir.getName()); } File[] dotProjectFiles = dotPhrescoFolders[0].listFiles(new PhrescoFileNameFilter(PROJECT_INFO_FILE)); ProjectInfo projectInfo = getProjectInfo(dotProjectFiles[0], projectId, customerId, appId); if (projectInfo != null) { return projectInfo; } } } return null; } public ProjectInfo create(ProjectInfo projectInfo, ServiceManager serviceManager) throws PhrescoException { if (isDebugEnabled) { S_LOGGER.debug("Entering Method ProjectManagerImpl.create(ProjectInfo projectInfo)"); } ClientResponse response = serviceManager.createProject(projectInfo); if (isDebugEnabled) { S_LOGGER.debug("createProject response code " + response.getStatus()); } if (response.getStatus() == 200) { try { extractArchive(response, projectInfo); ProjectUtils projectUtils = new ProjectUtils(); String customerId = projectInfo.getCustomerIds().get(0); Customer customer = serviceManager.getCustomer(customerId); RepoInfo repoInfo = customer.getRepoInfo(); List<ApplicationInfo> appInfos = projectInfo.getAppInfos(); for (ApplicationInfo appInfo : appInfos) { String pluginInfoFile = Utility.getProjectHome() + appInfo.getAppDirName() + File.separator + DOT_PHRESCO_FOLDER +File.separator + APPLICATION_HANDLER_INFO_FILE; File path = new File(Utility.getProjectHome() + appInfo.getAppDirName()); projectUtils.updateTestPom(path); MojoProcessor mojoProcessor = new MojoProcessor(new File(pluginInfoFile)); ApplicationHandler applicationHandler = mojoProcessor.getApplicationHandler(); if (applicationHandler != null) { List<ArtifactGroup> plugins = setArtifactGroup(applicationHandler); //Dynamic Class Loading PhrescoDynamicLoader dynamicLoader = new PhrescoDynamicLoader(repoInfo, plugins); ApplicationProcessor applicationProcessor = dynamicLoader.getApplicationProcessor(applicationHandler.getClazz()); applicationProcessor.postCreate(appInfo); } } } catch (FileNotFoundException e) { throw new PhrescoException(e); } catch (IOException e) { throw new PhrescoException(e); } } else if(response.getStatus() == 401){ throw new PhrescoException("Session expired"); } else { throw new PhrescoException("Project creation failed"); } //TODO This needs to be moved to service try { List<ApplicationInfo> appInfos = projectInfo.getAppInfos(); Environment defaultEnv = getEnvFromService(serviceManager); for (ApplicationInfo applicationInfo : appInfos) { createConfigurationXml(applicationInfo.getAppDirName(), serviceManager, defaultEnv); } } catch (PhrescoException e) { S_LOGGER.error("Entered into the catch block of Configuration creation failed Exception" + e.getLocalizedMessage()); throw new PhrescoException("Configuration creation failed"+e); } return projectInfo; } public ProjectInfo update(ProjectInfo projectInfo, ServiceManager serviceManager, String oldAppDirName) throws PhrescoException { if (projectInfo.getNoOfApps() == 0 && CollectionUtils.isEmpty(projectInfo.getAppInfos())) { ProjectInfo availableProjectInfo = getProject(projectInfo.getId(), projectInfo.getCustomerIds().get(0)); List<ApplicationInfo> appInfos = availableProjectInfo.getAppInfos(); for (ApplicationInfo applicationInfo : appInfos) { projectInfo.setAppInfos(Collections.singletonList(applicationInfo)); StringBuilder sb = new StringBuilder(Utility.getProjectHome()) .append(applicationInfo.getAppDirName()) .append(File.separator) .append(DOT_PHRESCO_FOLDER) .append(File.separator) .append(PROJECT_INFO_FILE); ProjectUtils.updateProjectInfo(projectInfo, new File(sb.toString()));// To update the project.info file } } else { + ClientResponse response = serviceManager.updateProject(projectInfo); if (response.getStatus() == 200) { BufferedReader breader = null; + File backUpProjectInfoFile = null; try { //application path with old app dir StringBuilder oldAppDirSb = new StringBuilder(Utility.getProjectHome()); oldAppDirSb.append(oldAppDirName); File oldDir = new File(oldAppDirSb.toString()); - + backUpProjectInfoFile = backUpProjectInfoFile(oldDir.getPath()); //application path with new app dir StringBuilder newAppDirSb = new StringBuilder(Utility.getProjectHome()); newAppDirSb.append(projectInfo.getAppInfos().get(0).getAppDirName()); File projectInfoFile = new File(newAppDirSb.toString()); //rename to application app dir oldDir.renameTo(projectInfoFile); extractArchive(response, projectInfo); updateProjectPom(projectInfo, newAppDirSb.toString()); StringBuilder dotPhrescoPathSb = new StringBuilder(projectInfoFile.getPath()); dotPhrescoPathSb.append(File.separator); dotPhrescoPathSb.append(DOT_PHRESCO_FOLDER); dotPhrescoPathSb.append(File.separator); String customerId = projectInfo.getCustomerIds().get(0); Customer customer = serviceManager.getCustomer(customerId); RepoInfo repoInfo = customer.getRepoInfo(); ApplicationInfo appInfo = projectInfo.getAppInfos().get(0); String pluginInfoFile = dotPhrescoPathSb.toString() + APPLICATION_HANDLER_INFO_FILE; MojoProcessor mojoProcessor = new MojoProcessor(new File(pluginInfoFile)); ApplicationHandler applicationHandler = mojoProcessor.getApplicationHandler(); createSqlFolder(appInfo, projectInfoFile, serviceManager); if (applicationHandler != null) { String selectedFeatures = applicationHandler.getSelectedFeatures(); String deletedFeatures = applicationHandler.getDeletedFeatures(); Gson gson = new Gson(); Type jsonType = new TypeToken<Collection<ArtifactGroup>>(){}.getType(); List<ArtifactGroup> artifactGroups = gson.fromJson(selectedFeatures, jsonType); List<ArtifactGroup> deletedArtifacts = gson.fromJson(deletedFeatures, jsonType); List<ArtifactGroup> plugins = setArtifactGroup(applicationHandler); // Dynamic Class Loading PhrescoDynamicLoader dynamicLoader = new PhrescoDynamicLoader(repoInfo, plugins); ApplicationProcessor applicationProcessor = dynamicLoader .getApplicationProcessor(applicationHandler.getClazz()); - applicationProcessor.postUpdate(appInfo, artifactGroups, deletedArtifacts); File projectInfoPath = new File(dotPhrescoPathSb.toString() + PROJECT_INFO_FILE); ProjectUtils.updateProjectInfo(projectInfo, projectInfoPath);// To update the project.info file } } catch (FileNotFoundException e) { e.printStackTrace(); throw new PhrescoException(e); } catch (IOException e) { e.printStackTrace(); throw new PhrescoException(e); - } + } finally { + FileUtil.delete(backUpProjectInfoFile); + } } else if (response.getStatus() == 401) { throw new PhrescoException("Session expired"); } else { throw new PhrescoException("Project updation failed"); } } return null; } + private File backUpProjectInfoFile(String oldDirPath) throws PhrescoException { + StringBuilder oldDotPhrescoPathSb = new StringBuilder(oldDirPath); + oldDotPhrescoPathSb.append(File.separator); + oldDotPhrescoPathSb.append(DOT_PHRESCO_FOLDER); + oldDotPhrescoPathSb.append(File.separator); + File projectInfoFile = new File(oldDotPhrescoPathSb.toString() + PROJECT_INFO_FILE); + File backUpInfoFile = new File(oldDotPhrescoPathSb.toString() + PROJECT_INFO_BACKUP_FILE); + try { + FileUtils.copyFile(projectInfoFile, backUpInfoFile); + return backUpInfoFile; + } catch (IOException e) { + throw new PhrescoException(e); + } + } private void updateProjectPom(ProjectInfo projectInfo, String newAppDirSb) throws PhrescoException { File pomFile = new File(newAppDirSb, "pom.xml"); PomProcessor pomProcessor; try { pomProcessor = new PomProcessor(pomFile); ApplicationInfo applicationInfo = projectInfo.getAppInfos().get(0); pomProcessor.setArtifactId(applicationInfo.getCode()); pomProcessor.setName(applicationInfo.getName()); pomProcessor.setVersion(projectInfo.getVersion()); pomProcessor.save(); } catch (PhrescoPomException e) { throw new PhrescoException(e); } } private List<ArtifactGroup> setArtifactGroup(ApplicationHandler applicationHandler) { List<ArtifactGroup> plugins = new ArrayList<ArtifactGroup>(); ArtifactGroup artifactGroup = new ArtifactGroup(); artifactGroup.setGroupId(applicationHandler.getGroupId()); artifactGroup.setArtifactId(applicationHandler.getArtifactId()); //artifactGroup.setType(Type.FEATURE); to set version List<ArtifactInfo> artifactInfos = new ArrayList<ArtifactInfo>(); ArtifactInfo artifactInfo = new ArtifactInfo(); artifactInfo.setVersion(applicationHandler.getVersion()); artifactInfos.add(artifactInfo); artifactGroup.setVersions(artifactInfos); plugins.add(artifactGroup); return plugins; } public boolean delete(List<ApplicationInfo> appInfos) throws PhrescoException { boolean deletionSuccess = false; String projectsPath = Utility.getProjectHome(); for (ApplicationInfo applicationInfo : appInfos) { String appDirName = applicationInfo.getAppDirName(); File application = new File(projectsPath + appDirName); deletionSuccess = FileUtil.delete(application); } return deletionSuccess; } private void fillProjects(File dotProjectFile, List<ProjectInfo> projectInfos, String customerId) throws PhrescoException { S_LOGGER.debug("Entering Method ProjectManagerImpl.fillProjects(File[] dotProjectFiles, List<Project> projects)"); Gson gson = new Gson(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(dotProjectFile)); ProjectInfo projectInfo = gson.fromJson(reader, ProjectInfo.class); if (projectInfo.getCustomerIds().get(0).equalsIgnoreCase(customerId)) { ProjectInfo projectInfoInMap = projectInfosMap.get(projectInfo.getId()); if (projectInfoInMap != null) { projectInfoInMap.getAppInfos().add(projectInfo.getAppInfos().get(0)); projectInfosMap.put(projectInfo.getId(), projectInfoInMap); } else { projectInfosMap.put(projectInfo.getId(), projectInfo); } } } catch (FileNotFoundException e) { throw new PhrescoException(e); } finally { Utility.closeStream(reader); } } private ProjectInfo getProjectInfo(File dotProjectFile, String projectId, String customerId, String appId) throws PhrescoException { S_LOGGER.debug("Entering Method ProjectManagerImpl.fillProjects(File[] dotProjectFiles, List<Project> projects)"); Gson gson = new Gson(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(dotProjectFile)); ProjectInfo projectInfo = gson.fromJson(reader, ProjectInfo.class); if (projectInfo.getCustomerIds().get(0).equalsIgnoreCase(customerId) && projectInfo.getId().equals(projectId)) { List<ApplicationInfo> appInfos = projectInfo.getAppInfos(); for (ApplicationInfo applicationInfo : appInfos) { if (applicationInfo.getId().equals(appId)) { return projectInfo; } } } } catch (FileNotFoundException e) { throw new PhrescoException(e); } finally { Utility.closeStream(reader); } return null; } private void extractArchive(ClientResponse response, ProjectInfo info) throws IOException, PhrescoException { InputStream inputStream = response.getEntityInputStream(); FileOutputStream fileOutputStream = null; String archiveHome = Utility.getArchiveHome(); File archiveFile = new File(archiveHome + info.getProjectCode() + ARCHIVE_FORMAT); fileOutputStream = new FileOutputStream(archiveFile); try { byte[] data = new byte[1024]; int i = 0; while ((i = inputStream.read(data)) != -1) { fileOutputStream.write(data, 0, i); } fileOutputStream.flush(); ArchiveUtil.extractArchive(archiveFile.getPath(), Utility.getProjectHome(), ArchiveType.ZIP); } finally { Utility.closeStream(inputStream); Utility.closeStream(fileOutputStream); } } private void createSqlFolder(ApplicationInfo appInfo, File path, ServiceManager serviceManager) throws PhrescoException { String dbName = ""; try { File pomPath = new File(Utility.getProjectHome() + appInfo.getAppDirName() + File.separator + POM_FILE); PomProcessor pompro = new PomProcessor(pomPath); String sqlFolderPath = pompro.getProperty(POM_PROP_KEY_SQL_FILE_DIR); File mysqlFolder = new File(path, sqlFolderPath + Constants.DB_MYSQL); File mysqlVersionFolder = getMysqlVersionFolder(mysqlFolder); File pluginInfoFile = new File(Utility.getProjectHome() + appInfo.getAppDirName() + File.separator + DOT_PHRESCO_FOLDER + File.separator + APPLICATION_HANDLER_INFO_FILE); MojoProcessor mojoProcessor = new MojoProcessor(pluginInfoFile); ApplicationHandler applicationHandler = mojoProcessor.getApplicationHandler(); String selectedDatabases = applicationHandler.getSelectedDatabase(); if (StringUtils.isNotEmpty(selectedDatabases) && StringUtils.isNotEmpty(sqlFolderPath)) { Gson gson = new Gson(); java.lang.reflect.Type jsonType = new TypeToken<Collection<DownloadInfo>>() { }.getType(); List<DownloadInfo> dbInfos = gson.fromJson(selectedDatabases, jsonType); List<ArtifactGroupInfo> newSelectedDatabases = appInfo.getSelectedDatabases(); for (ArtifactGroupInfo artifactGroupInfo : newSelectedDatabases) { List<String> artifactInfoIds = artifactGroupInfo.getArtifactInfoIds(); for (String artifactId : artifactInfoIds) { ArtifactInfo artifactInfo = serviceManager.getArtifactInfo(artifactId); String selectedVersion = artifactInfo.getVersion(); for (DownloadInfo dbInfo : dbInfos) { dbName = dbInfo.getName().toLowerCase(); ArtifactGroup artifactGroup = dbInfo.getArtifactGroup(); mySqlFolderCreation(path, dbName, sqlFolderPath, mysqlVersionFolder,selectedVersion, artifactGroup); } } } } } catch (PhrescoPomException e) { throw new PhrescoException(e); } } private void mySqlFolderCreation(File path, String dbName, String sqlFolderPath, File mysqlVersionFolder, String selectedVersion, ArtifactGroup artifactGroup) throws PhrescoException { try { List<ArtifactInfo> versions = artifactGroup.getVersions(); for (ArtifactInfo version : versions) { if (selectedVersion.equals(version.getVersion())) { String dbversion = version.getVersion(); String sqlPath = dbName + File.separator + dbversion.trim(); File sqlFolder = new File(path, sqlFolderPath + sqlPath); sqlFolder.mkdirs(); if (dbName.equals(Constants.DB_MYSQL) && mysqlVersionFolder != null && !(mysqlVersionFolder.getPath().equals(sqlFolder.getPath()))) { FileUtils.copyDirectory(mysqlVersionFolder, sqlFolder); } else { File sqlFile = new File(sqlFolder, Constants.SITE_SQL); if (!sqlFile.exists()) { sqlFile.createNewFile(); } } } } } catch (IOException e) { throw new PhrescoException(e); } } private File getMysqlVersionFolder(File mysqlFolder) { File[] mysqlFolderFiles = mysqlFolder.listFiles(); if (mysqlFolderFiles != null && mysqlFolderFiles.length > 0) { return mysqlFolderFiles[0]; } return null; } private File createConfigurationXml(String appDirName, ServiceManager serviceManager, Environment defaultEnv) throws PhrescoException { File configFile = new File(getConfigurationPath(appDirName).toString()); if (!configFile.exists()) { createEnvironments(configFile, defaultEnv, true); } return configFile; } private StringBuilder getConfigurationPath(String projectCode) { S_LOGGER.debug("Entering Method ProjectManager.getConfigurationPath(Project project)"); S_LOGGER.debug("removeSettingsInfos() ProjectCode = " + projectCode); StringBuilder builder = new StringBuilder(Utility.getProjectHome()); builder.append(projectCode); builder.append(File.separator); builder.append(FOLDER_DOT_PHRESCO); builder.append(File.separator); builder.append(CONFIGURATION_INFO_FILE_NAME); return builder; } private Environment getEnvFromService(ServiceManager serviceManager) throws PhrescoException { try { return serviceManager.getDefaultEnvFromServer(); } catch (ClientHandlerException ex) { S_LOGGER.error(ex.getLocalizedMessage()); throw new PhrescoException(ex); } } private void createEnvironments(File configPath, Environment defaultEnv, boolean isNewFile) throws PhrescoException { try { ConfigurationReader reader = new ConfigurationReader(configPath); ConfigurationWriter writer = new ConfigurationWriter(reader, isNewFile); writer.createEnvironment(Collections.singletonList(defaultEnv)); writer.saveXml(configPath); } catch (Exception e) { throw new PhrescoException(e); } } private class PhrescoFileNameFilter implements FilenameFilter { private String filter_; public PhrescoFileNameFilter(String filter) { filter_ = filter; } public boolean accept(File dir, String name) { return name.endsWith(filter_); } } } \ No newline at end of file
false
false
null
null
diff --git a/src/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl.java b/src/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl.java index aad894f9..d767da67 100644 --- a/src/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl.java +++ b/src/org/apache/xerces/impl/dv/xs/XSSimpleTypeDecl.java @@ -1,3708 +1,3711 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.impl.dv.xs; import java.util.AbstractList; import java.util.Locale; import java.util.StringTokenizer; import java.util.Vector; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.dv.DatatypeException; import org.apache.xerces.impl.dv.InvalidDatatypeFacetException; import org.apache.xerces.impl.dv.InvalidDatatypeValueException; import org.apache.xerces.impl.dv.ValidatedInfo; import org.apache.xerces.impl.dv.ValidationContext; import org.apache.xerces.impl.dv.XSFacets; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.impl.xpath.regex.RegularExpression; import org.apache.xerces.impl.xs.SchemaSymbols; import org.apache.xerces.impl.xs.util.ShortListImpl; import org.apache.xerces.impl.xs.util.StringListImpl; import org.apache.xerces.impl.xs.util.XSObjectListImpl; import org.apache.xerces.util.XMLChar; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xs.ShortList; import org.apache.xerces.xs.StringList; import org.apache.xerces.xs.XSAnnotation; import org.apache.xerces.xs.XSConstants; import org.apache.xerces.xs.XSFacet; import org.apache.xerces.xs.XSMultiValueFacet; import org.apache.xerces.xs.XSNamespaceItem; import org.apache.xerces.xs.XSObject; import org.apache.xerces.xs.XSObjectList; import org.apache.xerces.xs.XSSimpleTypeDefinition; import org.apache.xerces.xs.XSTypeDefinition; import org.apache.xerces.xs.datatypes.ObjectList; import org.w3c.dom.TypeInfo; /** * @xerces.internal * * @author Sandy Gao, IBM * @author Neeraj Bajaj, Sun Microsystems, inc. * * @version $Id$ */ public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo { protected static final short DV_STRING = PRIMITIVE_STRING; protected static final short DV_BOOLEAN = PRIMITIVE_BOOLEAN; protected static final short DV_DECIMAL = PRIMITIVE_DECIMAL; protected static final short DV_FLOAT = PRIMITIVE_FLOAT; protected static final short DV_DOUBLE = PRIMITIVE_DOUBLE; protected static final short DV_DURATION = PRIMITIVE_DURATION; protected static final short DV_DATETIME = PRIMITIVE_DATETIME; protected static final short DV_TIME = PRIMITIVE_TIME; protected static final short DV_DATE = PRIMITIVE_DATE; protected static final short DV_GYEARMONTH = PRIMITIVE_GYEARMONTH; protected static final short DV_GYEAR = PRIMITIVE_GYEAR; protected static final short DV_GMONTHDAY = PRIMITIVE_GMONTHDAY; protected static final short DV_GDAY = PRIMITIVE_GDAY; protected static final short DV_GMONTH = PRIMITIVE_GMONTH; protected static final short DV_HEXBINARY = PRIMITIVE_HEXBINARY; protected static final short DV_BASE64BINARY = PRIMITIVE_BASE64BINARY; protected static final short DV_ANYURI = PRIMITIVE_ANYURI; protected static final short DV_QNAME = PRIMITIVE_QNAME; protected static final short DV_PRECISIONDECIMAL = PRIMITIVE_PRECISIONDECIMAL; protected static final short DV_NOTATION = PRIMITIVE_NOTATION; protected static final short DV_ANYSIMPLETYPE = 0; protected static final short DV_ID = DV_NOTATION + 1; protected static final short DV_IDREF = DV_NOTATION + 2; protected static final short DV_ENTITY = DV_NOTATION + 3; protected static final short DV_INTEGER = DV_NOTATION + 4; protected static final short DV_LIST = DV_NOTATION + 5; protected static final short DV_UNION = DV_NOTATION + 6; protected static final short DV_YEARMONTHDURATION = DV_NOTATION + 7; protected static final short DV_DAYTIMEDURATION = DV_NOTATION + 8; protected static final short DV_ANYATOMICTYPE = DV_NOTATION + 9; protected static final short DV_ERROR = DV_NOTATION + 10; protected static final short DV_DATETIMESTAMP = DV_NOTATION + 11; private static final TypeValidator[] gDVs = { new AnySimpleDV(), new StringDV(), new BooleanDV(), new DecimalDV(), new FloatDV(), new DoubleDV(), new DurationDV(), new DateTimeDV(), new TimeDV(), new DateDV(), new YearMonthDV(), new YearDV(), new MonthDayDV(), new DayDV(), new MonthDV(), new HexBinaryDV(), new Base64BinaryDV(), new AnyURIDV(), new QNameDV(), new PrecisionDecimalDV(), // XML Schema 1.1 type new QNameDV(), // notation use the same one as qname new IDDV(), new IDREFDV(), new EntityDV(), new IntegerDV(), new ListDV(), new UnionDV(), new YearMonthDurationDV(), // XML Schema 1.1 type new DayTimeDurationDV(), // XML Schema 1.1 type new AnyAtomicDV(), // XML Schema 1.1 type new ErrorDV(), // XML Schema 1.1 type new DateTimeStampDV() //XML Schema 1.1 type }; static final short NORMALIZE_NONE = 0; static final short NORMALIZE_TRIM = 1; static final short NORMALIZE_FULL = 2; static final short[] fDVNormalizeType = { NORMALIZE_NONE, //AnySimpleDV(), NORMALIZE_FULL, //StringDV(), NORMALIZE_TRIM, //BooleanDV(), NORMALIZE_TRIM, //DecimalDV(), NORMALIZE_TRIM, //FloatDV(), NORMALIZE_TRIM, //DoubleDV(), NORMALIZE_TRIM, //DurationDV(), NORMALIZE_TRIM, //DateTimeDV(), NORMALIZE_TRIM, //TimeDV(), NORMALIZE_TRIM, //DateDV(), NORMALIZE_TRIM, //YearMonthDV(), NORMALIZE_TRIM, //YearDV(), NORMALIZE_TRIM, //MonthDayDV(), NORMALIZE_TRIM, //DayDV(), NORMALIZE_TRIM, //MonthDV(), NORMALIZE_TRIM, //HexBinaryDV(), NORMALIZE_NONE, //Base64BinaryDV(), // Base64 know how to deal with spaces NORMALIZE_TRIM, //AnyURIDV(), NORMALIZE_TRIM, //QNameDV(), NORMALIZE_TRIM, //PrecisionDecimalDV() (Schema 1.1) NORMALIZE_TRIM, //QNameDV(), // notation NORMALIZE_TRIM, //IDDV(), NORMALIZE_TRIM, //IDREFDV(), NORMALIZE_TRIM, //EntityDV(), NORMALIZE_TRIM, //IntegerDV(), NORMALIZE_FULL, //ListDV(), NORMALIZE_NONE, //UnionDV(), NORMALIZE_TRIM, //YearMonthDurationDV() (Schema 1.1) NORMALIZE_TRIM, //DayTimeDurationDV() (Schema 1.1) NORMALIZE_NONE, //AnyAtomicDV() (Schema 1.1) NORMALIZE_NONE, //ErrorDV() (Schema 1.1) NORMALIZE_TRIM, //DateTimeStampDV(), (Schema 1.1) }; static final short SPECIAL_PATTERN_NONE = 0; static final short SPECIAL_PATTERN_NMTOKEN = 1; static final short SPECIAL_PATTERN_NAME = 2; static final short SPECIAL_PATTERN_NCNAME = 3; static final String[] SPECIAL_PATTERN_STRING = { "NONE", "NMTOKEN", "Name", "NCName" }; static final String[] WS_FACET_STRING = { "preserve", "replace", "collapse" }; static final String[] ET_FACET_STRING = { "optional", "required", "prohibited" }; static final String URI_SCHEMAFORSCHEMA = "http://www.w3.org/2001/XMLSchema"; static final String ANY_TYPE = "anyType"; // XML Schema 1.1 type constants public static final short YEARMONTHDURATION_DT = 46; public static final short DAYTIMEDURATION_DT = 47; public static final short PRECISIONDECIMAL_DT = 48; public static final short ANYATOMICTYPE_DT = 49; public static final short ERROR_DT = 50; public static final short DATETIMESTAMP_DT = 51; // DOM Level 3 TypeInfo Derivation Method constants static final int DERIVATION_ANY = 0; static final int DERIVATION_RESTRICTION = 1; static final int DERIVATION_EXTENSION = 2; static final int DERIVATION_UNION = 4; static final int DERIVATION_LIST = 8; static final ValidationContext fEmptyContext = new ValidationContext() { public boolean needFacetChecking() { return true; } public boolean needExtraChecking() { return false; } public boolean needToNormalize() { return true; } public boolean useNamespaces () { return true; } public boolean isEntityDeclared (String name) { return false; } public boolean isEntityUnparsed (String name) { return false; } public boolean isIdDeclared (String name) { return false; } public void addId(String name) { } public void addIdRef(String name) { } public String getSymbol (String symbol) { return symbol.intern(); } public String getURI(String prefix) { return null; } public Locale getLocale() { return Locale.getDefault(); } public TypeValidatorHelper getTypeValidatorHelper() { return TypeValidatorHelper.getInstance(Constants.SCHEMA_VERSION_1_0); } }; protected static TypeValidator[] getGDVs() { return (TypeValidator[])gDVs.clone(); } private TypeValidator[] fDVs = gDVs; protected void setDVs(TypeValidator[] dvs) { fDVs = dvs; } // Default TypeValidatorHelper private static TypeValidatorHelper fDefaultTypeValidatorHelper = TypeValidatorHelper.getInstance(Constants.SCHEMA_VERSION_1_0); // this will be true if this is a static XSSimpleTypeDecl // and hence must remain immutable (i.e., applyFacets // may not be permitted to have any effect). private boolean fIsImmutable = false; private XSSimpleTypeDecl fItemType; private XSSimpleTypeDecl[] fMemberTypes; // The most specific built-in type kind. private short fBuiltInKind; private String fTypeName; private String fTargetNamespace; private short fFinalSet = 0; private XSSimpleTypeDecl fBase; private short fVariety = -1; private short fValidationDV = -1; private short fFacetsDefined = 0; private short fFixedFacet = 0; //for constraining facets private short fWhiteSpace = 0; private short fExplicitTimezone = ET_OPTIONAL; //for XML Schema 1.1 private int fLength = -1; private int fMinLength = -1; private int fMaxLength = -1; private int fTotalDigits = -1; private int fFractionDigits = -1; private int fMaxScale; //for XML Schema 1.1 private int fMinScale; //for XML Schema 1.1 private Vector fPattern; private Vector fPatternStr; private Vector fEnumeration; private short[] fEnumerationType; private ShortList[] fEnumerationItemType; // used in case fenumerationType value is LIST or LISTOFUNION private ShortList fEnumerationTypeList; private ObjectList fEnumerationItemTypeList; private StringList fLexicalPattern; private StringList fLexicalEnumeration; private ObjectList fActualEnumeration; private Object fMaxInclusive; private Object fMaxExclusive; private Object fMinExclusive; private Object fMinInclusive; private Vector fAssertion; // added for XML Schema 1.1, assertions // annotations for constraining facets public XSAnnotation lengthAnnotation; public XSAnnotation minLengthAnnotation; public XSAnnotation maxLengthAnnotation; public XSAnnotation whiteSpaceAnnotation; public XSAnnotation totalDigitsAnnotation; public XSAnnotation fractionDigitsAnnotation; public XSObjectListImpl patternAnnotations; public XSObjectList enumerationAnnotations; public XSAnnotation maxInclusiveAnnotation; public XSAnnotation maxExclusiveAnnotation; public XSAnnotation minInclusiveAnnotation; public XSAnnotation minExclusiveAnnotation; public XSAnnotation maxScaleAnnotation; public XSAnnotation minScaleAnnotation; public XSAnnotation explicitTimezoneAnnotation; // facets as objects private XSObjectListImpl fFacets; // enumeration and pattern facets private XSObjectListImpl fMultiValueFacets; // simpleType annotations private XSObjectList fAnnotations = null; private short fPatternType = SPECIAL_PATTERN_NONE; // for fundamental facets private short fOrdered; private boolean fFinite; private boolean fBounded; private boolean fNumeric; // The namespace schema information item corresponding to the target namespace // of the simple type definition, if it is globally declared; or null otherwise. private XSNamespaceItem fNamespaceItem = null; // context XSObject fContext = null; // default constructor public XSSimpleTypeDecl(){} //Create a new built-in primitive types (and id/idref/entity/integer/yearMonthDuration) protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, short validateDV, short ordered, boolean bounded, boolean finite, boolean numeric, boolean isImmutable, short builtInKind) { fIsImmutable = isImmutable; fBase = base; fTypeName = name; fTargetNamespace = URI_SCHEMAFORSCHEMA; // To simplify the code for anySimpleType, we treat it as an atomic type fVariety = VARIETY_ATOMIC; fValidationDV = validateDV; fFacetsDefined = FACET_WHITESPACE; - if (validateDV == DV_STRING) { + if (validateDV == DV_ANYSIMPLETYPE || + validateDV == DV_ANYATOMICTYPE || + validateDV == DV_STRING) { fWhiteSpace = WS_PRESERVE; - } else { + } + else { fWhiteSpace = WS_COLLAPSE; fFixedFacet = FACET_WHITESPACE; } this.fOrdered = ordered; this.fBounded = bounded; this.fFinite = finite; this.fNumeric = numeric; fAnnotations = null; // Specify the build in kind for this primitive type fBuiltInKind = builtInKind; } //Create a new simple type for restriction for built-in types protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, String uri, short finalSet, boolean isImmutable, XSObjectList annotations, short builtInKind) { this(base, name, uri, finalSet, isImmutable, annotations); // Specify the build in kind for this built-in type fBuiltInKind = builtInKind; } //Create a new simple type for restriction. protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, String uri, short finalSet, boolean isImmutable, XSObjectList annotations) { fBase = base; fTypeName = name; fTargetNamespace = uri; fFinalSet = finalSet; fAnnotations = annotations; fVariety = fBase.fVariety; fValidationDV = fBase.fValidationDV; switch (fVariety) { case VARIETY_ATOMIC: break; case VARIETY_LIST: fItemType = fBase.fItemType; break; case VARIETY_UNION: fMemberTypes = fBase.fMemberTypes; break; } // always inherit facets from the base. // in case a type is created, but applyFacets is not called fLength = fBase.fLength; fMinLength = fBase.fMinLength; fMaxLength = fBase.fMaxLength; fPattern = fBase.fPattern; fPatternStr = fBase.fPatternStr; fEnumeration = fBase.fEnumeration; fEnumerationType = fBase.fEnumerationType; fEnumerationItemType = fBase.fEnumerationItemType; fAssertion = fBase.fAssertion; // added for XML Schema 1.1 fWhiteSpace = fBase.fWhiteSpace; fMaxExclusive = fBase.fMaxExclusive; fMaxInclusive = fBase.fMaxInclusive; fMinExclusive = fBase.fMinExclusive; fMinInclusive = fBase.fMinInclusive; fTotalDigits = fBase.fTotalDigits; fFractionDigits = fBase.fFractionDigits; fPatternType = fBase.fPatternType; fFixedFacet = fBase.fFixedFacet; fFacetsDefined = fBase.fFacetsDefined; fMaxScale = fBase.fMaxScale; fMinScale = fBase.fMinScale; fExplicitTimezone = fBase.fExplicitTimezone; // always inherit facet annotations in case applyFacets is not called. lengthAnnotation = fBase.lengthAnnotation; minLengthAnnotation = fBase.minLengthAnnotation; maxLengthAnnotation = fBase.maxLengthAnnotation; patternAnnotations = fBase.patternAnnotations; enumerationAnnotations = fBase.enumerationAnnotations; whiteSpaceAnnotation = fBase.whiteSpaceAnnotation; maxExclusiveAnnotation = fBase.maxExclusiveAnnotation; maxInclusiveAnnotation = fBase.maxInclusiveAnnotation; minExclusiveAnnotation = fBase.minExclusiveAnnotation; minInclusiveAnnotation = fBase.minInclusiveAnnotation; totalDigitsAnnotation = fBase.totalDigitsAnnotation; fractionDigitsAnnotation = fBase.fractionDigitsAnnotation; maxScaleAnnotation = fBase.maxScaleAnnotation; minScaleAnnotation = fBase.minScaleAnnotation; explicitTimezoneAnnotation = fBase.explicitTimezoneAnnotation; //we also set fundamental facets information in case applyFacets is not called. calcFundamentalFacets(); fIsImmutable = isImmutable; // Inherit from the base type fBuiltInKind = base.fBuiltInKind; } //Create a new simple type for list. protected XSSimpleTypeDecl(String name, String uri, short finalSet, XSSimpleTypeDecl itemType, boolean isImmutable, XSObjectList annotations) { fBase = fAnySimpleType; fTypeName = name; fTargetNamespace = uri; fFinalSet = finalSet; fAnnotations = annotations; fVariety = VARIETY_LIST; fItemType = (XSSimpleTypeDecl)itemType; fValidationDV = DV_LIST; fFacetsDefined = FACET_WHITESPACE; fFixedFacet = FACET_WHITESPACE; fWhiteSpace = WS_COLLAPSE; //setting fundamental facets calcFundamentalFacets(); fIsImmutable = isImmutable; // Values of this type are lists fBuiltInKind = XSConstants.LIST_DT; } //Create a new simple type for union. protected XSSimpleTypeDecl(String name, String uri, short finalSet, XSSimpleTypeDecl[] memberTypes, XSObjectList annotations) { fBase = fAnySimpleType; fTypeName = name; fTargetNamespace = uri; fFinalSet = finalSet; fAnnotations = annotations; fVariety = VARIETY_UNION; fMemberTypes = memberTypes; fValidationDV = DV_UNION; // even for union, we set whitespace to something // this will never be used, but we can use fFacetsDefined to check // whether applyFacets() is allwwed: it's not allowed // if fFacetsDefined != 0 fFacetsDefined = FACET_WHITESPACE; fWhiteSpace = WS_COLLAPSE; //setting fundamental facets calcFundamentalFacets(); // none of the schema-defined types are unions, so just set // fIsImmutable to false. fIsImmutable = false; // No value can be of this type, so it's unavailable. fBuiltInKind = XSConstants.UNAVAILABLE_DT; } //set values for restriction. protected XSSimpleTypeDecl setRestrictionValues(XSSimpleTypeDecl base, String name, String uri, short finalSet, XSObjectList annotations) { //decline to do anything if the object is immutable. if(fIsImmutable) return null; fBase = base; fAnonymous = false; fTypeName = name; fTargetNamespace = uri; fFinalSet = finalSet; fAnnotations = annotations; fVariety = fBase.fVariety; fValidationDV = fBase.fValidationDV; switch (fVariety) { case VARIETY_ATOMIC: break; case VARIETY_LIST: fItemType = fBase.fItemType; break; case VARIETY_UNION: fMemberTypes = fBase.fMemberTypes; break; } // always inherit facets from the base. // in case a type is created, but applyFacets is not called fLength = fBase.fLength; fMinLength = fBase.fMinLength; fMaxLength = fBase.fMaxLength; fPattern = fBase.fPattern; fPatternStr = fBase.fPatternStr; fEnumeration = fBase.fEnumeration; fEnumerationType = fBase.fEnumerationType; fEnumerationItemType = fBase.fEnumerationItemType; fWhiteSpace = fBase.fWhiteSpace; fMaxExclusive = fBase.fMaxExclusive; fMaxInclusive = fBase.fMaxInclusive; fMinExclusive = fBase.fMinExclusive; fMinInclusive = fBase.fMinInclusive; fTotalDigits = fBase.fTotalDigits; fFractionDigits = fBase.fFractionDigits; fPatternType = fBase.fPatternType; fFixedFacet = fBase.fFixedFacet; fFacetsDefined = fBase.fFacetsDefined; fMaxScale = fBase.fMaxScale; fMinScale = fBase.fMinScale; fExplicitTimezone = fBase.fExplicitTimezone; //we also set fundamental facets information in case applyFacets is not called. calcFundamentalFacets(); // Inherit from the base type fBuiltInKind = base.fBuiltInKind; return this; } //set values for list. protected XSSimpleTypeDecl setListValues(String name, String uri, short finalSet, XSSimpleTypeDecl itemType, XSObjectList annotations) { //decline to do anything if the object is immutable. if(fIsImmutable) return null; fBase = fAnySimpleType; fAnonymous = false; fTypeName = name; fTargetNamespace = uri; fFinalSet = finalSet; fAnnotations = annotations; fVariety = VARIETY_LIST; fItemType = (XSSimpleTypeDecl)itemType; fValidationDV = DV_LIST; fFacetsDefined = FACET_WHITESPACE; fFixedFacet = FACET_WHITESPACE; fWhiteSpace = WS_COLLAPSE; //setting fundamental facets calcFundamentalFacets(); // Values of this type are lists fBuiltInKind = XSConstants.LIST_DT; return this; } //set values for union. protected XSSimpleTypeDecl setUnionValues(String name, String uri, short finalSet, XSSimpleTypeDecl[] memberTypes, XSObjectList annotations) { //decline to do anything if the object is immutable. if(fIsImmutable) return null; fBase = fAnySimpleType; fAnonymous = false; fTypeName = name; fTargetNamespace = uri; fFinalSet = finalSet; fAnnotations = annotations; fVariety = VARIETY_UNION; fMemberTypes = memberTypes; fValidationDV = DV_UNION; // even for union, we set whitespace to something // this will never be used, but we can use fFacetsDefined to check // whether applyFacets() is allwwed: it's not allowed // if fFacetsDefined != 0 fFacetsDefined = FACET_WHITESPACE; fWhiteSpace = WS_COLLAPSE; //setting fundamental facets calcFundamentalFacets(); // No value can be of this type, so it's unavailable. fBuiltInKind = XSConstants.UNAVAILABLE_DT; return this; } public short getType () { return XSConstants.TYPE_DEFINITION; } public short getTypeCategory () { return SIMPLE_TYPE; } public String getName() { return getAnonymous()?null:fTypeName; } public String getTypeName() { return fTypeName; } public String getNamespace() { return fTargetNamespace; } public short getFinal(){ return fFinalSet; } public TypeValidator getTypeValidator() { return fDVs[fValidationDV]; } public boolean isFinal(short derivation) { return (fFinalSet & derivation) != 0; } public XSTypeDefinition getBaseType(){ return fBase; } public boolean getAnonymous() { return fAnonymous || (fTypeName == null); } public short getVariety(){ // for anySimpleType, return absent variaty return fValidationDV == DV_ANYSIMPLETYPE ? VARIETY_ABSENT : fVariety; } public boolean isIDType(){ switch (fVariety) { case VARIETY_ATOMIC: return fValidationDV == DV_ID; case VARIETY_LIST: return fItemType.isIDType(); case VARIETY_UNION: for (int i = 0; i < fMemberTypes.length; i++) { if (fMemberTypes[i].isIDType()) return true; } } return false; } public short getWhitespace() throws DatatypeException{ if (fVariety == VARIETY_UNION) { throw new DatatypeException("dt-whitespace", new Object[]{fTypeName}); } return fWhiteSpace; } public short getPrimitiveKind() { if (fVariety == VARIETY_ATOMIC && fValidationDV != DV_ANYSIMPLETYPE && fValidationDV != DV_ANYATOMICTYPE) { if (fValidationDV == DV_ID || fValidationDV == DV_IDREF || fValidationDV == DV_ENTITY) { return DV_STRING; } else if (fValidationDV == DV_INTEGER) { return DV_DECIMAL; } else if (Constants.SCHEMA_1_1_SUPPORT && (fValidationDV == DV_YEARMONTHDURATION || fValidationDV == DV_DAYTIMEDURATION)) { return DV_DURATION; } else { return fValidationDV; } } else { // REVISIT: error situation. runtime exception? return (short)0; } } /** * Returns the closest built-in type category this type represents or * derived from. For example, if this simple type is a built-in derived * type integer the <code>INTEGER_DV</code> is returned. */ public short getBuiltInKind() { return this.fBuiltInKind; } /** * If variety is <code>atomic</code> the primitive type definition (a * built-in primitive datatype definition or the simple ur-type * definition) if available, otherwise <code>null</code>. */ public XSSimpleTypeDefinition getPrimitiveType() { if (fVariety == VARIETY_ATOMIC && fValidationDV != DV_ANYSIMPLETYPE && fValidationDV != DV_ANYATOMICTYPE) { XSSimpleTypeDecl pri = this; // recursively get base, until we reach anySimpleType while (pri.fBase != fAnySimpleType && pri.fBase != fAnyAtomicType) { pri = pri.fBase; } return pri; } else { // REVISIT: error situation. runtime exception? return null; } } /** * If variety is <code>list</code> the item type definition (an atomic or * union simple type definition) if available, otherwise * <code>null</code>. */ public XSSimpleTypeDefinition getItemType() { if (fVariety == VARIETY_LIST) { return fItemType; } else { // REVISIT: error situation. runtime exception? return null; } } /** * If variety is <code>union</code> the list of member type definitions (a * non-empty sequence of simple type definitions) if available, * otherwise an empty <code>XSObjectList</code>. */ public XSObjectList getMemberTypes() { if (fVariety == VARIETY_UNION) { return new XSObjectListImpl(fMemberTypes, fMemberTypes.length); } else { return XSObjectListImpl.EMPTY_LIST; } } /** * If <restriction> is chosen */ public void applyFacets(XSFacets facets, int presentFacet, int fixedFacet, ValidationContext context) throws InvalidDatatypeFacetException { if (context == null) { context = fEmptyContext; } applyFacets(facets, presentFacet, fixedFacet, SPECIAL_PATTERN_NONE, context); } /** * built-in derived types by restriction */ void applyFacets1(XSFacets facets, int presentFacet, int fixedFacet) { try { applyFacets(facets, presentFacet, fixedFacet, SPECIAL_PATTERN_NONE, fDummyContext); } catch (InvalidDatatypeFacetException e) { // should never gets here, internel error throw new RuntimeException("internal error"); } // we've now applied facets; so lock this object: fIsImmutable = true; } /** * built-in derived types by restriction */ void applyFacets1(XSFacets facets, int presentFacet, int fixedFacet, short patternType) { try { applyFacets(facets, presentFacet, fixedFacet, patternType, fDummyContext); } catch (InvalidDatatypeFacetException e) { // should never gets here, internel error throw new RuntimeException("internal error"); } // we've now applied facets; so lock this object: fIsImmutable = true; } /** * If <restriction> is chosen, or built-in derived types by restriction */ void applyFacets(XSFacets facets, int presentFacet, int fixedFacet, short patternType, ValidationContext context) throws InvalidDatatypeFacetException { // if the object is immutable, should not apply facets... if(fIsImmutable) return; ValidatedInfo tempInfo = new ValidatedInfo(); // clear facets. because we always inherit facets in the constructor // REVISIT: in fact, we don't need to clear them. // we can convert 5 string values (4 bounds + 1 enum) to actual values, // store them somewhere, then do facet checking at once, instead of // going through the following steps. (lots of checking are redundant: // for example, ((presentFacet & FACET_XXX) != 0)) fFacetsDefined = 0; fFixedFacet = 0; int result = 0 ; // step 1: parse present facets TypeValidatorHelper typeValidatorHelper = context.getTypeValidatorHelper(); if (typeValidatorHelper == null) { // fall back to 1.0 simple types typeValidatorHelper = fDefaultTypeValidatorHelper; } int allowedFacet = typeValidatorHelper.getAllowedFacets(fValidationDV); // length if ((presentFacet & FACET_LENGTH) != 0) { if ((allowedFacet & FACET_LENGTH) == 0) { reportError("cos-applicable-facets", new Object[]{"length", fTypeName}); } else { fLength = facets.length; lengthAnnotation = facets.lengthAnnotation; fFacetsDefined |= FACET_LENGTH; if ((fixedFacet & FACET_LENGTH) != 0) fFixedFacet |= FACET_LENGTH; } } // minLength if ((presentFacet & FACET_MINLENGTH) != 0) { if ((allowedFacet & FACET_MINLENGTH) == 0) { reportError("cos-applicable-facets", new Object[]{"minLength", fTypeName}); } else { fMinLength = facets.minLength; minLengthAnnotation = facets.minLengthAnnotation; fFacetsDefined |= FACET_MINLENGTH; if ((fixedFacet & FACET_MINLENGTH) != 0) fFixedFacet |= FACET_MINLENGTH; } } // maxLength if ((presentFacet & FACET_MAXLENGTH) != 0) { if ((allowedFacet & FACET_MAXLENGTH) == 0) { reportError("cos-applicable-facets", new Object[]{"maxLength", fTypeName}); } else { fMaxLength = facets.maxLength; maxLengthAnnotation = facets.maxLengthAnnotation; fFacetsDefined |= FACET_MAXLENGTH; if ((fixedFacet & FACET_MAXLENGTH) != 0) fFixedFacet |= FACET_MAXLENGTH; } } // pattern if ((presentFacet & FACET_PATTERN) != 0) { if ((allowedFacet & FACET_PATTERN) == 0) { reportError("cos-applicable-facets", new Object[]{"pattern", fTypeName}); } else { patternAnnotations = facets.patternAnnotations; RegularExpression regex = null; try { regex = new RegularExpression(facets.pattern, "X", context.getLocale()); } catch (Exception e) { reportError("InvalidRegex", new Object[]{facets.pattern, e.getLocalizedMessage()}); } if (regex != null) { fPattern = new Vector(); fPattern.addElement(regex); fPatternStr = new Vector(); fPatternStr.addElement(facets.pattern); fFacetsDefined |= FACET_PATTERN; if ((fixedFacet & FACET_PATTERN) != 0) fFixedFacet |= FACET_PATTERN; } } } // whiteSpace if ((presentFacet & FACET_WHITESPACE) != 0) { if ((allowedFacet & FACET_WHITESPACE) == 0) { reportError("cos-applicable-facets", new Object[]{"whiteSpace", fTypeName}); } else { fWhiteSpace = facets.whiteSpace; whiteSpaceAnnotation = facets.whiteSpaceAnnotation; fFacetsDefined |= FACET_WHITESPACE; if ((fixedFacet & FACET_WHITESPACE) != 0) fFixedFacet |= FACET_WHITESPACE; } } // enumeration if ((presentFacet & FACET_ENUMERATION) != 0) { if ((allowedFacet & FACET_ENUMERATION) == 0) { reportError("cos-applicable-facets", new Object[]{"enumeration", fTypeName}); } else { fEnumeration = new Vector(); Vector enumVals = facets.enumeration; fEnumerationType = new short[enumVals.size()]; fEnumerationItemType = new ShortList[enumVals.size()]; Vector enumNSDecls = facets.enumNSDecls; ValidationContextImpl ctx = new ValidationContextImpl(context); enumerationAnnotations = facets.enumAnnotations; for (int i = 0; i < enumVals.size(); i++) { if (enumNSDecls != null) ctx.setNSContext((NamespaceContext)enumNSDecls.elementAt(i)); try { ValidatedInfo info = getActualEnumValue((String)enumVals.elementAt(i), ctx, tempInfo); // check 4.3.5.c0 must: enumeration values from the value space of base fEnumeration.addElement(info.actualValue); fEnumerationType[i] = info.actualValueType; fEnumerationItemType[i] = info.itemValueTypes; } catch (InvalidDatatypeValueException ide) { reportError("enumeration-valid-restriction", new Object[]{enumVals.elementAt(i), this.getBaseType().getName()}); } } fFacetsDefined |= FACET_ENUMERATION; if ((fixedFacet & FACET_ENUMERATION) != 0) fFixedFacet |= FACET_ENUMERATION; } } // assertion. added for XML Schema 1.1 if ((presentFacet & FACET_ASSERT) != 0) { fAssertion = new Vector(); Vector asserts = facets.assertFacets; for (int i = 0; i < asserts.size(); i++) { fAssertion.addElement(asserts.elementAt(i)); } fFacetsDefined |= FACET_ASSERT; if ((fixedFacet & FACET_ASSERT) != 0) fFixedFacet |= FACET_ASSERT; } //explicitTimezone if ((presentFacet & FACET_EXPLICITTIMEZONE) != 0) { if ((allowedFacet & FACET_EXPLICITTIMEZONE) == 0) { reportError("cos-applicable-facets", new Object[]{"explicitTimezone", fTypeName}); } else { fExplicitTimezone = facets.explicitTimezone; explicitTimezoneAnnotation = facets.explicitTimezoneAnnotation; fFacetsDefined |= FACET_EXPLICITTIMEZONE; if ((fixedFacet & FACET_EXPLICITTIMEZONE) != 0) fFixedFacet |= FACET_EXPLICITTIMEZONE; } } // maxInclusive if ((presentFacet & FACET_MAXINCLUSIVE) != 0) { if ((allowedFacet & FACET_MAXINCLUSIVE) == 0) { reportError("cos-applicable-facets", new Object[]{"maxInclusive", fTypeName}); } else { maxInclusiveAnnotation = facets.maxInclusiveAnnotation; try { fMaxInclusive = fBase.getActualValue(facets.maxInclusive, context, tempInfo, true); fFacetsDefined |= FACET_MAXINCLUSIVE; if ((fixedFacet & FACET_MAXINCLUSIVE) != 0) fFixedFacet |= FACET_MAXINCLUSIVE; } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxInclusive, "maxInclusive", fBase.getName()}); } // check against fixed value in base if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { if ((fBase.fFixedFacet & FACET_MAXINCLUSIVE) != 0) { if (fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxInclusive) != 0) reportError( "FixedFacetValue", new Object[]{"maxInclusive", fMaxInclusive, fBase.fMaxInclusive, fTypeName}); } } // maxInclusive from base try { fBase.validate(context, tempInfo); } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxInclusive, "maxInclusive", fBase.getName()}); } } } // maxExclusive boolean needCheckBase = true; if ((presentFacet & FACET_MAXEXCLUSIVE) != 0) { if ((allowedFacet & FACET_MAXEXCLUSIVE) == 0) { reportError("cos-applicable-facets", new Object[]{"maxExclusive", fTypeName}); } else { maxExclusiveAnnotation = facets.maxExclusiveAnnotation; try { fMaxExclusive = fBase.getActualValue(facets.maxExclusive, context, tempInfo, true); fFacetsDefined |= FACET_MAXEXCLUSIVE; if ((fixedFacet & FACET_MAXEXCLUSIVE) != 0) fFixedFacet |= FACET_MAXEXCLUSIVE; } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxExclusive, "maxExclusive", fBase.getName()}); } // check against fixed value in base if (((fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxExclusive); if ((fBase.fFixedFacet & FACET_MAXEXCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"maxExclusive", facets.maxExclusive, fBase.fMaxExclusive, fTypeName}); } if (result == 0) { needCheckBase = false; } } // maxExclusive from base if (needCheckBase) { try { fBase.validate(context, tempInfo); } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxExclusive, "maxExclusive", fBase.getName()}); } } // If maxExclusive == base.maxExclusive, then we only need to check // maxExclusive <= base.maxInclusive else if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { if (fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxInclusive) > 0) { reportError( "maxExclusive-valid-restriction.2", new Object[]{facets.maxExclusive, fBase.fMaxInclusive}); } } } } // minExclusive needCheckBase = true; if ((presentFacet & FACET_MINEXCLUSIVE) != 0) { if ((allowedFacet & FACET_MINEXCLUSIVE) == 0) { reportError("cos-applicable-facets", new Object[]{"minExclusive", fTypeName}); } else { minExclusiveAnnotation = facets.minExclusiveAnnotation; try { fMinExclusive = fBase.getActualValue(facets.minExclusive, context, tempInfo, true); fFacetsDefined |= FACET_MINEXCLUSIVE; if ((fixedFacet & FACET_MINEXCLUSIVE) != 0) fFixedFacet |= FACET_MINEXCLUSIVE; } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minExclusive, "minExclusive", fBase.getName()}); } // check against fixed value in base if (((fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinExclusive); if ((fBase.fFixedFacet & FACET_MINEXCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"minExclusive", facets.minExclusive, fBase.fMinExclusive, fTypeName}); } if (result == 0) { needCheckBase = false; } } // minExclusive from base if (needCheckBase) { try { fBase.validate(context, tempInfo); } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minExclusive, "minExclusive", fBase.getName()}); } } // If minExclusive == base.minExclusive, then we only need to check // minExclusive >= base.minInclusive else if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) { if (fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinInclusive) < 0) { reportError( "minExclusive-valid-restriction.3", new Object[]{facets.minExclusive, fBase.fMinInclusive}); } } } } // minInclusive if ((presentFacet & FACET_MININCLUSIVE) != 0) { if ((allowedFacet & FACET_MININCLUSIVE) == 0) { reportError("cos-applicable-facets", new Object[]{"minInclusive", fTypeName}); } else { minInclusiveAnnotation = facets.minInclusiveAnnotation; try { fMinInclusive = fBase.getActualValue(facets.minInclusive, context, tempInfo, true); fFacetsDefined |= FACET_MININCLUSIVE; if ((fixedFacet & FACET_MININCLUSIVE) != 0) fFixedFacet |= FACET_MININCLUSIVE; } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minInclusive, "minInclusive", fBase.getName()}); } // check against fixed value in base if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) { if ((fBase.fFixedFacet & FACET_MININCLUSIVE) != 0) { if (fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinInclusive) != 0) reportError( "FixedFacetValue", new Object[]{"minInclusive", facets.minInclusive, fBase.fMinInclusive, fTypeName}); } } // minInclusive from base try { fBase.validate(context, tempInfo); } catch (InvalidDatatypeValueException ide) { reportError(ide.getKey(), ide.getArgs()); reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minInclusive, "minInclusive", fBase.getName()}); } } } // totalDigits if ((presentFacet & FACET_TOTALDIGITS) != 0) { if ((allowedFacet & FACET_TOTALDIGITS) == 0) { reportError("cos-applicable-facets", new Object[]{"totalDigits", fTypeName}); } else { totalDigitsAnnotation = facets.totalDigitsAnnotation; fTotalDigits = facets.totalDigits; fFacetsDefined |= FACET_TOTALDIGITS; if ((fixedFacet & FACET_TOTALDIGITS) != 0) fFixedFacet |= FACET_TOTALDIGITS; } } // fractionDigits if ((presentFacet & FACET_FRACTIONDIGITS) != 0) { if ((allowedFacet & FACET_FRACTIONDIGITS) == 0) { reportError("cos-applicable-facets", new Object[]{"fractionDigits", fTypeName}); } else { fFractionDigits = facets.fractionDigits; fractionDigitsAnnotation = facets.fractionDigitsAnnotation; fFacetsDefined |= FACET_FRACTIONDIGITS; if ((fixedFacet & FACET_FRACTIONDIGITS) != 0) fFixedFacet |= FACET_FRACTIONDIGITS; } } //maxScale if ((presentFacet & FACET_MAXSCALE) !=0 ){ if ((allowedFacet & FACET_MAXSCALE) == 0) { reportError("cos-applicable-facets", new Object[]{"maxScale", fTypeName}); }else { maxScaleAnnotation = facets.maxScaleAnnotation; fMaxScale = facets.maxScale; fFacetsDefined |= FACET_MAXSCALE; if ((fixedFacet & FACET_MAXSCALE) != 0) fFixedFacet |= FACET_MAXSCALE; } } //minScale if ((presentFacet & FACET_MINSCALE) !=0 ){ if ((allowedFacet & FACET_MINSCALE) == 0) { reportError("cos-applicable-facets", new Object[]{"minScale", fTypeName}); }else { minScaleAnnotation = facets.minScaleAnnotation; fMinScale = facets.minScale; fFacetsDefined |= FACET_MINSCALE; if ((fixedFacet & FACET_MINSCALE) != 0) fFixedFacet |= FACET_MINSCALE; } } // token type: internal use, so do less checking if (patternType != SPECIAL_PATTERN_NONE) { fPatternType = patternType; } // step 2: check facets against each other: length, bounds if(fFacetsDefined != 0) { // check 4.3.2.c1 must: minLength <= maxLength if(((fFacetsDefined & FACET_MINLENGTH ) != 0 ) && ((fFacetsDefined & FACET_MAXLENGTH) != 0)) { if(fMinLength > fMaxLength) reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fMinLength), Integer.toString(fMaxLength), fTypeName}); } // check 4.3.8.c1 error: maxInclusive + maxExclusive if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { reportError( "maxInclusive-maxExclusive", new Object[]{fMaxInclusive, fMaxExclusive, fTypeName}); } // check 4.3.9.c1 error: minInclusive + minExclusive if (((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) { reportError("minInclusive-minExclusive", new Object[]{fMinInclusive, fMinExclusive, fTypeName}); } // check 4.3.7.c1 must: minInclusive <= maxInclusive if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMinInclusive, fMaxInclusive); if (result != -1 && result != 0) reportError("minInclusive-less-than-equal-to-maxInclusive", new Object[]{fMinInclusive, fMaxInclusive, fTypeName}); } // check 4.3.8.c2 must: minExclusive <= maxExclusive ??? minExclusive < maxExclusive if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMinExclusive, fMaxExclusive); if (result != -1 && result != 0) reportError( "minExclusive-less-than-equal-to-maxExclusive", new Object[]{fMinExclusive, fMaxExclusive, fTypeName}); } // check 4.3.9.c2 must: minExclusive < maxInclusive if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0) && ((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) { if (fDVs[fValidationDV].compare(fMinExclusive, fMaxInclusive) != -1) reportError( "minExclusive-less-than-maxInclusive", new Object[]{fMinExclusive, fMaxInclusive, fTypeName}); } // check 4.3.10.c1 must: minInclusive < maxExclusive if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) { if (fDVs[fValidationDV].compare(fMinInclusive, fMaxExclusive) != -1) reportError( "minInclusive-less-than-maxExclusive", new Object[]{fMinInclusive, fMaxExclusive, fTypeName}); } // check 4.3.12.c1 must: fractionDigits <= totalDigits if (((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) && ((fFacetsDefined & FACET_TOTALDIGITS) != 0)) { if (fFractionDigits > fTotalDigits) reportError( "fractionDigits-totalDigits", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fTotalDigits), fTypeName}); } // check 4.3.14.4 must: minScale <= maxScale if (((fFacetsDefined & FACET_MAXSCALE) != 0 ) && ((fFacetsDefined & FACET_MINSCALE) != 0)) { if (fMinScale > fMaxScale) reportError ("minScale-totalDigits", new Object[]{Integer.toString(fMinScale), Integer.toString(fMaxScale), fTypeName}); } // step 3: check facets against base // check 4.3.1.c1 error: length & (fBase.maxLength | fBase.minLength) if((fFacetsDefined & FACET_LENGTH) != 0 ){ if ((fBase.fFacetsDefined & FACET_MINLENGTH) != 0 && fLength < fBase.fMinLength) { // length, fBase.minLength and fBase.maxLength defined reportError("length-minLength-maxLength.1.1", new Object[]{fTypeName, Integer.toString(fLength), Integer.toString(fBase.fMinLength)}); } if ((fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 && fLength > fBase.fMaxLength) { // length and fBase.maxLength defined reportError("length-minLength-maxLength.2.1", new Object[]{fTypeName, Integer.toString(fLength), Integer.toString(fBase.fMaxLength)}); } if ( (fBase.fFacetsDefined & FACET_LENGTH) != 0 ) { // check 4.3.1.c2 error: length != fBase.length if ( fLength != fBase.fLength ) reportError( "length-valid-restriction", new Object[]{Integer.toString(fLength), Integer.toString(fBase.fLength), fTypeName}); } } // check 4.3.1.c1 error: fBase.length & (maxLength | minLength) if((fBase.fFacetsDefined & FACET_LENGTH) != 0 || (fFacetsDefined & FACET_LENGTH) != 0){ if ((fFacetsDefined & FACET_MINLENGTH) != 0){ if (fBase.fLength < fMinLength) { // fBase.length, minLength and maxLength defined reportError("length-minLength-maxLength.1.1", new Object[]{fTypeName, Integer.toString(fBase.fLength), Integer.toString(fMinLength)}); } if ((fBase.fFacetsDefined & FACET_MINLENGTH) == 0){ reportError("length-minLength-maxLength.1.2.a", new Object[]{fTypeName}); } if (fMinLength != fBase.fMinLength){ reportError("length-minLength-maxLength.1.2.b", new Object[]{fTypeName, Integer.toString(fMinLength), Integer.toString(fBase.fMinLength)}); } } if ((fFacetsDefined & FACET_MAXLENGTH) != 0){ if (fBase.fLength > fMaxLength) { // fBase.length, minLength and maxLength defined reportError("length-minLength-maxLength.2.1", new Object[]{fTypeName, Integer.toString(fBase.fLength), Integer.toString(fMaxLength)}); } if ((fBase.fFacetsDefined & FACET_MAXLENGTH) == 0){ reportError("length-minLength-maxLength.2.2.a", new Object[]{fTypeName}); } if (fMaxLength != fBase.fMaxLength){ reportError("length-minLength-maxLength.2.2.b", new Object[]{fTypeName, Integer.toString(fMaxLength), Integer.toString(fBase.fBase.fMaxLength)}); } } } // check 4.3.2.c1 must: minLength <= fBase.maxLength if ( ((fFacetsDefined & FACET_MINLENGTH ) != 0 ) ) { if ( (fBase.fFacetsDefined & FACET_MAXLENGTH ) != 0 ) { if ( fMinLength > fBase.fMaxLength ) { reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fMinLength), Integer.toString(fBase.fMaxLength), fTypeName}); } } else if ( (fBase.fFacetsDefined & FACET_MINLENGTH) != 0 ) { if ( (fBase.fFixedFacet & FACET_MINLENGTH) != 0 && fMinLength != fBase.fMinLength ) { reportError( "FixedFacetValue", new Object[]{"minLength", Integer.toString(fMinLength), Integer.toString(fBase.fMinLength), fTypeName}); } // check 4.3.2.c2 error: minLength < fBase.minLength if ( fMinLength < fBase.fMinLength ) { reportError( "minLength-valid-restriction", new Object[]{Integer.toString(fMinLength), Integer.toString(fBase.fMinLength), fTypeName}); } } } // check 4.3.2.c1 must: maxLength < fBase.minLength if ( ((fFacetsDefined & FACET_MAXLENGTH ) != 0 ) && ((fBase.fFacetsDefined & FACET_MINLENGTH ) != 0 )) { if ( fMaxLength < fBase.fMinLength) { reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fBase.fMinLength), Integer.toString(fMaxLength)}); } } // check 4.3.3.c1 error: maxLength > fBase.maxLength if ( (fFacetsDefined & FACET_MAXLENGTH) != 0 ) { if ( (fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 ){ if(( (fBase.fFixedFacet & FACET_MAXLENGTH) != 0 )&& fMaxLength != fBase.fMaxLength ) { reportError( "FixedFacetValue", new Object[]{"maxLength", Integer.toString(fMaxLength), Integer.toString(fBase.fMaxLength), fTypeName}); } if ( fMaxLength > fBase.fMaxLength ) { reportError( "maxLength-valid-restriction", new Object[]{Integer.toString(fMaxLength), Integer.toString(fBase.fMaxLength), fTypeName}); } } } /* // check 4.3.7.c2 error: // maxInclusive > fBase.maxInclusive // maxInclusive >= fBase.maxExclusive // maxInclusive < fBase.minInclusive // maxInclusive <= fBase.minExclusive if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxInclusive); if ((fBase.fFixedFacet & FACET_MAXINCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"maxInclusive", fMaxInclusive, fBase.fMaxInclusive, fTypeName}); } if (result != -1 && result != 0) { reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMaxInclusive, fTypeName}); } } if (((fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxExclusive) != -1){ reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMaxExclusive, fTypeName}); } if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMinInclusive); if (result != 1 && result != 0) { reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMinInclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMinExclusive ) != 1) reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMinExclusive, fTypeName}); } // check 4.3.8.c3 error: // maxExclusive > fBase.maxExclusive // maxExclusive > fBase.maxInclusive // maxExclusive <= fBase.minInclusive // maxExclusive <= fBase.minExclusive if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) { if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) { result= fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxExclusive); if ((fBase.fFixedFacet & FACET_MAXEXCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"maxExclusive", fMaxExclusive, fBase.fMaxExclusive, fTypeName}); } if (result != -1 && result != 0) { reportError( "maxExclusive-valid-restriction.1", new Object[]{fMaxExclusive, fBase.fMaxExclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { result= fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxInclusive); if (result != -1 && result != 0) { reportError( "maxExclusive-valid-restriction.2", new Object[]{fMaxExclusive, fBase.fMaxInclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMinExclusive ) != 1) reportError( "maxExclusive-valid-restriction.3", new Object[]{fMaxExclusive, fBase.fMinExclusive, fTypeName}); if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMinInclusive) != 1) reportError( "maxExclusive-valid-restriction.4", new Object[]{fMaxExclusive, fBase.fMinInclusive, fTypeName}); } // check 4.3.9.c3 error: // minExclusive < fBase.minExclusive // minExclusive > fBase.maxInclusive // minExclusive < fBase.minInclusive // minExclusive >= fBase.maxExclusive if (((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) { if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) { result= fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinExclusive); if ((fBase.fFixedFacet & FACET_MINEXCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"minExclusive", fMinExclusive, fBase.fMinExclusive, fTypeName}); } if (result != 1 && result != 0) { reportError( "minExclusive-valid-restriction.1", new Object[]{fMinExclusive, fBase.fMinExclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { result=fDVs[fValidationDV].compare(fMinExclusive, fBase.fMaxInclusive); if (result != -1 && result != 0) { reportError( "minExclusive-valid-restriction.2", new Object[]{fMinExclusive, fBase.fMaxInclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinInclusive); if (result != 1 && result != 0) { reportError( "minExclusive-valid-restriction.3", new Object[]{fMinExclusive, fBase.fMinInclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMinExclusive, fBase.fMaxExclusive) != -1) reportError( "minExclusive-valid-restriction.4", new Object[]{fMinExclusive, fBase.fMaxExclusive, fTypeName}); } // check 4.3.10.c2 error: // minInclusive < fBase.minInclusive // minInclusive > fBase.maxInclusive // minInclusive <= fBase.minExclusive // minInclusive >= fBase.maxExclusive if (((fFacetsDefined & FACET_MININCLUSIVE) != 0)) { if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) { result = fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinInclusive); if ((fBase.fFixedFacet & FACET_MININCLUSIVE) != 0 && result != 0) { reportError( "FixedFacetValue", new Object[]{"minInclusive", fMinInclusive, fBase.fMinInclusive, fTypeName}); } if (result != 1 && result != 0) { reportError( "minInclusive-valid-restriction.1", new Object[]{fMinInclusive, fBase.fMinInclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { result=fDVs[fValidationDV].compare(fMinInclusive, fBase.fMaxInclusive); if (result != -1 && result != 0) { reportError( "minInclusive-valid-restriction.2", new Object[]{fMinInclusive, fBase.fMaxInclusive, fTypeName}); } } if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinExclusive ) != 1) reportError( "minInclusive-valid-restriction.3", new Object[]{fMinInclusive, fBase.fMinExclusive, fTypeName}); if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && fDVs[fValidationDV].compare(fMinInclusive, fBase.fMaxExclusive) != -1) reportError( "minInclusive-valid-restriction.4", new Object[]{fMinInclusive, fBase.fMaxExclusive, fTypeName}); } */ // check 4.3.11.c1 error: totalDigits > fBase.totalDigits if (((fFacetsDefined & FACET_TOTALDIGITS) != 0)) { if ((( fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0)) { if ((fBase.fFixedFacet & FACET_TOTALDIGITS) != 0 && fTotalDigits != fBase.fTotalDigits) { reportError("FixedFacetValue", new Object[]{"totalDigits", Integer.toString(fTotalDigits), Integer.toString(fBase.fTotalDigits), fTypeName}); } if (fTotalDigits > fBase.fTotalDigits) { reportError( "totalDigits-valid-restriction", new Object[]{Integer.toString(fTotalDigits), Integer.toString(fBase.fTotalDigits), fTypeName}); } } } //check maxScale > fBase.maxScale if ( (fFacetsDefined & FACET_MAXSCALE) != 0 ) { if ( (fBase.fFacetsDefined & FACET_MAXSCALE) != 0 ){ if(( (fBase.fFixedFacet & FACET_MAXSCALE) != 0 )&& fMaxScale != fBase.fMaxScale ) { reportError( "FixedFacetValue", new Object[]{"maxScale", Integer.toString(fMaxScale), Integer.toString(fBase.fMaxScale), fTypeName}); } if ( fMaxScale > fBase.fMaxScale) { reportError( "maxScale-valid-restriction", new Object[]{Integer.toString(fMaxScale), Integer.toString(fBase.fMaxScale), fTypeName}); } } } //check minScale < fBase.minScale if ( (fFacetsDefined & FACET_MINSCALE) != 0 ) { if ( (fBase.fFacetsDefined & FACET_MINSCALE) != 0 ){ if(( (fBase.fFixedFacet & FACET_MINSCALE) != 0 )&& fMinScale != fBase.fMinScale ) { reportError( "FixedFacetValue", new Object[]{"minScale", Integer.toString(fMinScale), Integer.toString(fBase.fMinScale), fTypeName}); } if (fMinScale < fBase.fMinScale) { reportError( "minScale-valid-restriction", new Object[]{Integer.toString(fMinScale), Integer.toString(fBase.fMinScale), fTypeName}); } } } //check must maxScale >= fBase.minScale if ( ((fFacetsDefined & FACET_MAXSCALE ) != 0 ) && ((fBase.fFacetsDefined & FACET_MINSCALE ) != 0 )) { if ( fMaxScale < fBase.fMinScale) { reportError ("minScale-totalDigits", new Object[]{Integer.toString(fBase.fMinScale), Integer.toString(fMaxScale), fTypeName}); } } //check must minScale <= fBase.maxScale if ( ((fFacetsDefined & FACET_MINSCALE ) != 0 ) && ((fBase.fFacetsDefined & FACET_MAXSCALE ) != 0 )) { if ( fMinScale > fBase.fMaxScale) { reportError ("minScale-totalDigits", new Object[]{Integer.toString(fMinScale), Integer.toString(fBase.fMaxScale), fTypeName}); } } // check 4.3.12.c1 must: fractionDigits <= base.totalDigits if ((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) { if ((fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0) { if (fFractionDigits > fBase.fTotalDigits) reportError( "fractionDigits-totalDigits", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fTotalDigits), fTypeName}); } } // check 4.3.12.c2 error: fractionDigits > fBase.fractionDigits // check fixed value for fractionDigits if (((fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) { if ((( fBase.fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) { if (((fBase.fFixedFacet & FACET_FRACTIONDIGITS) != 0 && fFractionDigits != fBase.fFractionDigits) || (fValidationDV == DV_INTEGER && fFractionDigits != 0)) { reportError("FixedFacetValue", new Object[]{"fractionDigits", Integer.toString(fFractionDigits), Integer.toString(fBase.fFractionDigits), fTypeName}); } if (fFractionDigits > fBase.fFractionDigits) { reportError( "fractionDigits-valid-restriction", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fBase.fFractionDigits), fTypeName}); } } else if (fValidationDV == DV_INTEGER && fFractionDigits != 0) { reportError("FixedFacetValue", new Object[]{"fractionDigits", Integer.toString(fFractionDigits), "0", fTypeName}); } } // check 4.3.6.c1 error: // (whiteSpace = preserve || whiteSpace = replace) && fBase.whiteSpace = collapese or // whiteSpace = preserve && fBase.whiteSpace = replace if ( (fFacetsDefined & FACET_WHITESPACE) != 0 && (fBase.fFacetsDefined & FACET_WHITESPACE) != 0 ){ if ( (fBase.fFixedFacet & FACET_WHITESPACE) != 0 && fWhiteSpace != fBase.fWhiteSpace ) { reportError( "FixedFacetValue", new Object[]{"whiteSpace", whiteSpaceValue(fWhiteSpace), whiteSpaceValue(fBase.fWhiteSpace), fTypeName}); } if ( fWhiteSpace == WS_PRESERVE && fBase.fWhiteSpace == WS_COLLAPSE ){ reportError( "whiteSpace-valid-restriction.1", new Object[]{fTypeName, "preserve"}); } if ( fWhiteSpace == WS_REPLACE && fBase.fWhiteSpace == WS_COLLAPSE ){ reportError( "whiteSpace-valid-restriction.1", new Object[]{fTypeName, "replace"}); } if ( fWhiteSpace == WS_PRESERVE && fBase.fWhiteSpace == WS_REPLACE ){ reportError( "whiteSpace-valid-restriction.2", new Object[]{fTypeName}); } } if ((fFacetsDefined & FACET_EXPLICITTIMEZONE) != 0) { if ((fBase.fFacetsDefined & FACET_EXPLICITTIMEZONE ) != 0 && fExplicitTimezone != fBase.fExplicitTimezone){ final String explicitTZStr = explicitTimezoneValue(fExplicitTimezone); final String baseExplicitTZStr = explicitTimezoneValue(fBase.fExplicitTimezone); if ((fBase.fFixedFacet & FACET_EXPLICITTIMEZONE) != 0) { reportError( "FixedFacetValue", new Object[]{"explicitTimezone", explicitTZStr, baseExplicitTZStr, fTypeName}); } //check 4.3.16.4 error: //(explicitTimezone != prohibited && fBase.explicitTimezone = prohibited) //or (explicitTimezone != required && fBase.explicitTimezone = required) if (fBase.fExplicitTimezone != ET_OPTIONAL) { reportError("timezone-valid-restriction", new Object[]{fTypeName, explicitTZStr, baseExplicitTZStr}); } } if ( (fValidationDV == DV_DATETIMESTAMP) && fExplicitTimezone != XSSimpleType.ET_REQUIRED){ reportError( "FixedFacetValue", new Object[]{"explicitTimezone", explicitTimezoneValue(fExplicitTimezone), explicitTimezoneValue(ET_REQUIRED), fTypeName}); } } }//fFacetsDefined != null // step 4: inherit other facets from base (including fTokeyType) // inherit length if ( (fFacetsDefined & FACET_LENGTH) == 0 && (fBase.fFacetsDefined & FACET_LENGTH) != 0 ) { fFacetsDefined |= FACET_LENGTH; fLength = fBase.fLength; lengthAnnotation = fBase.lengthAnnotation; } // inherit minLength if ( (fFacetsDefined & FACET_MINLENGTH) == 0 && (fBase.fFacetsDefined & FACET_MINLENGTH) != 0 ) { fFacetsDefined |= FACET_MINLENGTH; fMinLength = fBase.fMinLength; minLengthAnnotation = fBase.minLengthAnnotation; } // inherit maxLength if ((fFacetsDefined & FACET_MAXLENGTH) == 0 && (fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 ) { fFacetsDefined |= FACET_MAXLENGTH; fMaxLength = fBase.fMaxLength; maxLengthAnnotation = fBase.maxLengthAnnotation; } // inherit pattern if ( (fBase.fFacetsDefined & FACET_PATTERN) != 0 ) { if ((fFacetsDefined & FACET_PATTERN) == 0) { fFacetsDefined |= FACET_PATTERN; fPattern = fBase.fPattern; fPatternStr = fBase.fPatternStr; patternAnnotations = fBase.patternAnnotations; } else { for (int i = fBase.fPattern.size()-1; i >= 0; --i) { fPattern.addElement(fBase.fPattern.elementAt(i)); fPatternStr.addElement(fBase.fPatternStr.elementAt(i)); } if (fBase.patternAnnotations != null) { if (patternAnnotations != null) { for (int i = fBase.patternAnnotations.getLength()-1; i >= 0; --i) { patternAnnotations.addXSObject(fBase.patternAnnotations.item(i)); } } else { patternAnnotations = fBase.patternAnnotations; } } } } // inherit whiteSpace if ( (fFacetsDefined & FACET_WHITESPACE) == 0 && (fBase.fFacetsDefined & FACET_WHITESPACE) != 0 ) { fFacetsDefined |= FACET_WHITESPACE; fWhiteSpace = fBase.fWhiteSpace; whiteSpaceAnnotation = fBase.whiteSpaceAnnotation; } //inherit explicitTimezone if ( (fFacetsDefined & FACET_EXPLICITTIMEZONE) == 0 && (fBase.fFacetsDefined & FACET_EXPLICITTIMEZONE) != 0 ) { fFacetsDefined |= FACET_EXPLICITTIMEZONE; fExplicitTimezone = fBase.fExplicitTimezone; explicitTimezoneAnnotation = fBase.explicitTimezoneAnnotation; } // inherit enumeration if ((fFacetsDefined & FACET_ENUMERATION) == 0 && (fBase.fFacetsDefined & FACET_ENUMERATION) != 0) { fFacetsDefined |= FACET_ENUMERATION; fEnumeration = fBase.fEnumeration; enumerationAnnotations = fBase.enumerationAnnotations; } // inherit maxExclusive if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { fFacetsDefined |= FACET_MAXEXCLUSIVE; fMaxExclusive = fBase.fMaxExclusive; maxExclusiveAnnotation = fBase.maxExclusiveAnnotation; } // inherit maxInclusive if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) { fFacetsDefined |= FACET_MAXINCLUSIVE; fMaxInclusive = fBase.fMaxInclusive; maxInclusiveAnnotation = fBase.maxInclusiveAnnotation; } // inherit minExclusive if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MININCLUSIVE) != 0)) { fFacetsDefined |= FACET_MINEXCLUSIVE; fMinExclusive = fBase.fMinExclusive; minExclusiveAnnotation = fBase.minExclusiveAnnotation; } // inherit minExclusive if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0) && !((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MININCLUSIVE) != 0)) { fFacetsDefined |= FACET_MININCLUSIVE; fMinInclusive = fBase.fMinInclusive; minInclusiveAnnotation = fBase.minInclusiveAnnotation; } //inherit maxScale if ((( fBase.fFacetsDefined & FACET_MAXSCALE) != 0) && !((fFacetsDefined & FACET_MAXSCALE) != 0)) { fFacetsDefined |= FACET_MAXSCALE; fMaxScale = fBase.fMaxScale; maxScaleAnnotation = fBase.maxScaleAnnotation; } //inherit minScale if ((( fBase.fFacetsDefined & FACET_MINSCALE) != 0) && !((fFacetsDefined & FACET_MINSCALE) != 0)) { fFacetsDefined |= FACET_MINSCALE; fMinScale = fBase.fMinScale; minScaleAnnotation = fBase.minScaleAnnotation; } // inherit totalDigits if ((( fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0) && !((fFacetsDefined & FACET_TOTALDIGITS) != 0)) { fFacetsDefined |= FACET_TOTALDIGITS; fTotalDigits = fBase.fTotalDigits; totalDigitsAnnotation = fBase.totalDigitsAnnotation; } // inherit fractionDigits if ((( fBase.fFacetsDefined & FACET_FRACTIONDIGITS) != 0) && !((fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) { fFacetsDefined |= FACET_FRACTIONDIGITS; fFractionDigits = fBase.fFractionDigits; fractionDigitsAnnotation = fBase.fractionDigitsAnnotation; } // inherit assertion. added for XML Schema 1.1 if (((fBase.fFacetsDefined & FACET_ASSERT) != 0) && !((fFacetsDefined & FACET_ASSERT) != 0)) { fFacetsDefined |= FACET_ASSERT; fAssertion = fBase.fAssertion; } //inherit tokeytype if ((fPatternType == SPECIAL_PATTERN_NONE ) && (fBase.fPatternType != SPECIAL_PATTERN_NONE)) { fPatternType = fBase.fPatternType ; } // step 5: mark fixed values fFixedFacet |= fBase.fFixedFacet; //step 6: setting fundamental facets calcFundamentalFacets(); } //applyFacets() /** * validate a value, and return the compiled form */ public Object validate(String content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException { if (context == null) context = fEmptyContext; if (validatedInfo == null) validatedInfo = new ValidatedInfo(); else validatedInfo.memberType = null; // first normalize string value, and convert it to actual value boolean needNormalize = context==null||context.needToNormalize(); Object ob = getActualValue(content, context, validatedInfo, needNormalize); validate(context, validatedInfo); return ob; } protected ValidatedInfo getActualEnumValue(String lexical, ValidationContext ctx, ValidatedInfo info) throws InvalidDatatypeValueException { return fBase.validateWithInfo(lexical, ctx, info); } /** * validate a value, and return the compiled form */ public ValidatedInfo validateWithInfo(String content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException { if (context == null) context = fEmptyContext; if (validatedInfo == null) validatedInfo = new ValidatedInfo(); else validatedInfo.memberType = null; // first normalize string value, and convert it to actual value boolean needNormalize = context==null||context.needToNormalize(); getActualValue(content, context, validatedInfo, needNormalize); validate(context, validatedInfo); return validatedInfo; } /** * validate a value, and return the compiled form */ public Object validate(Object content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException { if (context == null) context = fEmptyContext; if (validatedInfo == null) validatedInfo = new ValidatedInfo(); else validatedInfo.memberType = null; // first normalize string value, and convert it to actual value boolean needNormalize = context==null||context.needToNormalize(); Object ob = getActualValue(content, context, validatedInfo, needNormalize); validate(context, validatedInfo); return ob; } /** * validate an actual value against this DV * * @param context the validation context * @param validatedInfo used to provide the actual value and member types */ public void validate(ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException { if (context == null) context = fEmptyContext; // then validate the actual value against the facets if (context.needFacetChecking() && (fFacetsDefined != 0 && fFacetsDefined != FACET_WHITESPACE)) { checkFacets(validatedInfo); } // now check extra rules: for ID/IDREF/ENTITY if (context.needExtraChecking()) { checkExtraRules(context, validatedInfo); } } private void checkFacets(ValidatedInfo validatedInfo) throws InvalidDatatypeValueException { Object ob = validatedInfo.actualValue; String content = validatedInfo.normalizedValue; short type = validatedInfo.actualValueType; ShortList itemType = validatedInfo.itemValueTypes; // For QName and NOTATION types, we don't check length facets if (fValidationDV != DV_QNAME && fValidationDV != DV_NOTATION) { int length = fDVs[fValidationDV].getDataLength(ob); // maxLength if ( (fFacetsDefined & FACET_MAXLENGTH) != 0 ) { if ( length > fMaxLength ) { throw new InvalidDatatypeValueException("cvc-maxLength-valid", new Object[]{content, Integer.toString(length), Integer.toString(fMaxLength), fTypeName}); } } //minLength if ( (fFacetsDefined & FACET_MINLENGTH) != 0 ) { if ( length < fMinLength ) { throw new InvalidDatatypeValueException("cvc-minLength-valid", new Object[]{content, Integer.toString(length), Integer.toString(fMinLength), fTypeName}); } } //length if ( (fFacetsDefined & FACET_LENGTH) != 0 ) { if ( length != fLength ) { throw new InvalidDatatypeValueException("cvc-length-valid", new Object[]{content, Integer.toString(length), Integer.toString(fLength), fTypeName}); } } } //enumeration if ( ((fFacetsDefined & FACET_ENUMERATION) != 0 ) ) { boolean present = false; final int enumSize = fEnumeration.size(); final short primitiveType1 = convertToPrimitiveKind(type); for (int i = 0; i < enumSize; i++) { final short primitiveType2 = convertToPrimitiveKind(fEnumerationType[i]); if ((primitiveType1 == primitiveType2 || primitiveType1 == XSConstants.ANYSIMPLETYPE_DT && primitiveType2 == XSConstants.STRING_DT || primitiveType1 == XSConstants.STRING_DT && primitiveType2 == XSConstants.ANYSIMPLETYPE_DT) && fEnumeration.elementAt(i).equals(ob)) { if (primitiveType1 == XSConstants.LIST_DT || primitiveType1 == XSConstants.LISTOFUNION_DT) { ShortList enumItemType = fEnumerationItemType[i]; final int typeList1Length = itemType != null ? itemType.getLength() : 0; final int typeList2Length = enumItemType != null ? enumItemType.getLength() : 0; if (typeList1Length == typeList2Length) { int j; for (j = 0; j < typeList1Length; ++j) { final short primitiveItem1 = convertToPrimitiveKind(itemType.item(j)); final short primitiveItem2 = convertToPrimitiveKind(enumItemType.item(j)); if (primitiveItem1 != primitiveItem2) { if (primitiveItem1 == XSConstants.ANYSIMPLETYPE_DT && primitiveItem2 == XSConstants.STRING_DT || primitiveItem1 == XSConstants.STRING_DT && primitiveItem2 == XSConstants.ANYSIMPLETYPE_DT) { continue; } break; } } if (j == typeList1Length) { present = true; break; } } } else { present = true; break; } } } if(!present){ throw new InvalidDatatypeValueException("cvc-enumeration-valid", new Object [] {content, fEnumeration.toString()}); } } //fractionDigits if ((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) { int scale = fDVs[fValidationDV].getFractionDigits(ob); if (scale > fFractionDigits) { throw new InvalidDatatypeValueException("cvc-fractionDigits-valid", new Object[] {content, Integer.toString(scale), Integer.toString(fFractionDigits)}); } } //totalDigits if ((fFacetsDefined & FACET_TOTALDIGITS)!=0) { int totalDigits = fDVs[fValidationDV].getTotalDigits(ob); if (totalDigits > fTotalDigits) { throw new InvalidDatatypeValueException("cvc-totalDigits-valid", new Object[] {content, Integer.toString(totalDigits), Integer.toString(fTotalDigits)}); } } //maxScale if ((fFacetsDefined & FACET_MAXSCALE) != 0) { int precision = fDVs[fValidationDV].getPrecision(ob); if (precision > fMaxScale){ throw new InvalidDatatypeValueException("cvc-maxScale-valid", new Object[] {content, Integer.toString(fMaxScale), fTypeName, Integer.toString(precision)}); } } //minScale if ((fFacetsDefined & FACET_MINSCALE) != 0) { int precision = fDVs[fValidationDV].getPrecision(ob); if (precision < fMinScale){ throw new InvalidDatatypeValueException("cvc-minScale-valid", new Object[] {content, Integer.toString(fMinScale), fTypeName, Integer.toString(precision)} ); } } //explicitTimezone if ( ( fFacetsDefined & FACET_EXPLICITTIMEZONE) !=0 ) { boolean hasTimezone = fDVs[fValidationDV].hasTimeZone(ob); if (hasTimezone) { if (fExplicitTimezone == ET_PROHIBITED ) { throw new InvalidDatatypeValueException("cvc-explicitTimezone-valid", new Object[] {content, "prohibited", fTypeName}); } } else if (fExplicitTimezone == ET_REQUIRED) { throw new InvalidDatatypeValueException("cvc-explicitTimezone-valid", new Object[] {content, "required", fTypeName}); } } int compare; //maxinclusive if ( (fFacetsDefined & FACET_MAXINCLUSIVE) != 0 ) { compare = fDVs[fValidationDV].compare(ob, fMaxInclusive); if (compare != -1 && compare != 0) { throw new InvalidDatatypeValueException("cvc-maxInclusive-valid", new Object[] {content, fMaxInclusive, fTypeName}); } } //maxExclusive if ( (fFacetsDefined & FACET_MAXEXCLUSIVE) != 0 ) { compare = fDVs[fValidationDV].compare(ob, fMaxExclusive ); if (compare != -1) { throw new InvalidDatatypeValueException("cvc-maxExclusive-valid", new Object[] {content, fMaxExclusive, fTypeName}); } } //minInclusive if ( (fFacetsDefined & FACET_MININCLUSIVE) != 0 ) { compare = fDVs[fValidationDV].compare(ob, fMinInclusive); if (compare != 1 && compare != 0) { throw new InvalidDatatypeValueException("cvc-minInclusive-valid", new Object[] {content, fMinInclusive, fTypeName}); } } //minExclusive if ( (fFacetsDefined & FACET_MINEXCLUSIVE) != 0 ) { compare = fDVs[fValidationDV].compare(ob, fMinExclusive); if (compare != 1) { throw new InvalidDatatypeValueException("cvc-minExclusive-valid", new Object[] {content, fMinExclusive, fTypeName}); } } } private void checkExtraRules(ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException { Object ob = validatedInfo.actualValue; if (fVariety == VARIETY_ATOMIC) { fDVs[fValidationDV].checkExtraRules(ob, context); } else if (fVariety == VARIETY_LIST) { ListDV.ListData values = (ListDV.ListData)ob; XSSimpleType memberType = validatedInfo.memberType; int len = values.getLength(); try { if (fItemType.fVariety == VARIETY_UNION) { XSSimpleTypeDecl[] memberTypes = (XSSimpleTypeDecl[])validatedInfo.memberTypes; for (int i = len-1; i >= 0; i--) { validatedInfo.actualValue = values.item(i); validatedInfo.memberType = memberTypes[i]; fItemType.checkExtraRules(context, validatedInfo); } } else { // (fVariety == VARIETY_ATOMIC) for (int i = len-1; i >= 0; i--) { validatedInfo.actualValue = values.item(i); fItemType.checkExtraRules(context, validatedInfo); } } } finally { validatedInfo.actualValue = values; validatedInfo.memberType = memberType; } } else { // (fVariety == VARIETY_UNION) ((XSSimpleTypeDecl)validatedInfo.memberType).checkExtraRules(context, validatedInfo); } }// checkExtraRules() //we can still return object for internal use. private Object getActualValue(Object content, ValidationContext context, ValidatedInfo validatedInfo, boolean needNormalize) throws InvalidDatatypeValueException{ String nvalue; if (needNormalize) { nvalue = normalize(content, fWhiteSpace); } else { nvalue = content.toString(); } if ( (fFacetsDefined & FACET_PATTERN ) != 0 ) { RegularExpression regex; for (int idx = fPattern.size()-1; idx >= 0; idx--) { regex = (RegularExpression)fPattern.elementAt(idx); if (!regex.matches(nvalue)){ throw new InvalidDatatypeValueException("cvc-pattern-valid", new Object[]{content, fPatternStr.elementAt(idx), fTypeName}); } } } if (fVariety == VARIETY_ATOMIC) { // validate special kinds of token, in place of old pattern matching if (fPatternType != SPECIAL_PATTERN_NONE) { boolean seenErr = false; if (fPatternType == SPECIAL_PATTERN_NMTOKEN) { // PATTERN "\\c+" seenErr = !XMLChar.isValidNmtoken(nvalue); } else if (fPatternType == SPECIAL_PATTERN_NAME) { // PATTERN "\\i\\c*" seenErr = !XMLChar.isValidName(nvalue); } else if (fPatternType == SPECIAL_PATTERN_NCNAME) { // PATTERN "[\\i-[:]][\\c-[:]]*" seenErr = !XMLChar.isValidNCName(nvalue); } if (seenErr) { throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{nvalue, SPECIAL_PATTERN_STRING[fPatternType]}); } } validatedInfo.normalizedValue = nvalue; Object avalue = fDVs[fValidationDV].getActualValue(nvalue, context); validatedInfo.actualValue = avalue; validatedInfo.actualValueType = fBuiltInKind; return avalue; } else if (fVariety == VARIETY_LIST) { StringTokenizer parsedList = new StringTokenizer(nvalue, " "); int countOfTokens = parsedList.countTokens() ; Object[] avalue = new Object[countOfTokens]; boolean isUnion = fItemType.getVariety() == VARIETY_UNION; short[] itemTypes = new short[isUnion ? countOfTokens : 1]; if (!isUnion) itemTypes[0] = fItemType.fBuiltInKind; XSSimpleTypeDecl[] memberTypes = new XSSimpleTypeDecl[countOfTokens]; for(int i = 0 ; i < countOfTokens ; i ++){ // we can't call fItemType.validate(), otherwise checkExtraRules() // will be called twice: once in fItemType.validate, once in // validate method of this type. // so we take two steps to get the actual value: // 1. fItemType.getActualValue() // 2. fItemType.chekcFacets() avalue[i] = fItemType.getActualValue(parsedList.nextToken(), context, validatedInfo, false); if (context.needFacetChecking() && (fItemType.fFacetsDefined != 0 && fItemType.fFacetsDefined != FACET_WHITESPACE)) { fItemType.checkFacets(validatedInfo); } memberTypes[i] = (XSSimpleTypeDecl)validatedInfo.memberType; if (isUnion) itemTypes[i] = memberTypes[i].fBuiltInKind; } ListDV.ListData v = new ListDV.ListData(avalue); validatedInfo.actualValue = v; validatedInfo.actualValueType = isUnion ? XSConstants.LISTOFUNION_DT : XSConstants.LIST_DT; validatedInfo.memberType = null; validatedInfo.memberTypes = memberTypes; validatedInfo.itemValueTypes = new ShortListImpl(itemTypes, itemTypes.length); validatedInfo.normalizedValue = nvalue; return v; } else { // (fVariety == VARIETY_UNION) final Object _content = (fMemberTypes.length > 1 && content != null) ? content.toString() : content; for (int i = 0; i < fMemberTypes.length; i++) { try { // we can't call fMemberType[i].validate(), otherwise checkExtraRules() // will be called twice: once in fMemberType[i].validate, once in // validate method of this type. // so we take two steps to get the actual value: // 1. fMemberType[i].getActualValue() // 2. fMemberType[i].chekcFacets() Object aValue = fMemberTypes[i].getActualValue(_content, context, validatedInfo, true); if (context.needFacetChecking() && (fMemberTypes[i].fFacetsDefined != 0 && fMemberTypes[i].fFacetsDefined != FACET_WHITESPACE)) { fMemberTypes[i].checkFacets(validatedInfo); } if (fMemberTypes[i].fVariety != VARIETY_UNION) { validatedInfo.memberType = fMemberTypes[i]; } return aValue; } catch(InvalidDatatypeValueException invalidValue) { } } StringBuffer typesBuffer = new StringBuffer(); XSSimpleTypeDecl decl; for(int i = 0;i < fMemberTypes.length; i++) { if(i != 0) typesBuffer.append(" | "); decl = fMemberTypes[i]; if(decl.fTargetNamespace != null) { typesBuffer.append('{'); typesBuffer.append(decl.fTargetNamespace); typesBuffer.append('}'); } typesBuffer.append(decl.fTypeName); if(decl.fEnumeration != null) { Vector v = decl.fEnumeration; typesBuffer.append(" : ["); for(int j = 0;j < v.size(); j++) { if(j != 0) typesBuffer.append(','); typesBuffer.append(v.elementAt(j)); } typesBuffer.append(']'); } } throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.3", new Object[]{content, fTypeName, typesBuffer.toString()}); } }//getActualValue() public boolean isEqual(Object value1, Object value2) { if (value1 == null) { return false; } return value1.equals(value2); }//isEqual() // determine whether the two values are identical public boolean isIdentical (Object value1, Object value2) { if (value1 == null) { return false; } return fDVs[fValidationDV].isIdentical(value1, value2); }//isIdentical() // normalize the string according to the whiteSpace facet public static String normalize(String content, short ws) { int len = content == null ? 0 : content.length(); if (len == 0 || ws == WS_PRESERVE) return content; StringBuffer sb = new StringBuffer(); if (ws == WS_REPLACE) { char ch; // when it's replace, just replace #x9, #xa, #xd by #x20 for (int i = 0; i < len; i++) { ch = content.charAt(i); if (ch != 0x9 && ch != 0xa && ch != 0xd) sb.append(ch); else sb.append((char)0x20); } } else { char ch; int i; boolean isLeading = true; // when it's collapse for (i = 0; i < len; i++) { ch = content.charAt(i); // append real characters, so we passed leading ws if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20) { sb.append(ch); isLeading = false; } else { // for whitespaces, we skip all following ws for (; i < len-1; i++) { ch = content.charAt(i+1); if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20) break; } // if it's not a leading or tailing ws, then append a space if (i < len - 1 && !isLeading) sb.append((char)0x20); } } } return sb.toString(); } // normalize the string according to the whiteSpace facet protected String normalize(Object content, short ws) { if (content == null) return null; // If pattern is not defined, we can skip some of the normalization. // Otherwise we have to normalize the data for correct result of // pattern validation. if ( (fFacetsDefined & FACET_PATTERN ) == 0 ) { short norm_type = fDVNormalizeType[fValidationDV]; if (norm_type == NORMALIZE_NONE) { return content.toString(); } else if (norm_type == NORMALIZE_TRIM) { return XMLChar.trim(content.toString()); } } if (!(content instanceof StringBuffer)) { String strContent = content.toString(); return normalize(strContent, ws); } StringBuffer sb = (StringBuffer)content; int len = sb.length(); if (len == 0) return ""; if (ws == WS_PRESERVE) return sb.toString(); if (ws == WS_REPLACE) { char ch; // when it's replace, just replace #x9, #xa, #xd by #x20 for (int i = 0; i < len; i++) { ch = sb.charAt(i); if (ch == 0x9 || ch == 0xa || ch == 0xd) sb.setCharAt(i, (char)0x20); } } else { char ch; int i, j = 0; boolean isLeading = true; // when it's collapse for (i = 0; i < len; i++) { ch = sb.charAt(i); // append real characters, so we passed leading ws if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20) { sb.setCharAt(j++, ch); isLeading = false; } else { // for whitespaces, we skip all following ws for (; i < len-1; i++) { ch = sb.charAt(i+1); if (ch != 0x9 && ch != 0xa && ch != 0xd && ch != 0x20) break; } // if it's not a leading or tailing ws, then append a space if (i < len - 1 && !isLeading) sb.setCharAt(j++, (char)0x20); } } sb.setLength(j); } return sb.toString(); } void reportError(String key, Object[] args) throws InvalidDatatypeFacetException { throw new InvalidDatatypeFacetException(key, args); } private String whiteSpaceValue(short ws){ return WS_FACET_STRING[ws]; } private String explicitTimezoneValue(short et){ return ET_FACET_STRING[et]; } /** * Fundamental Facet: ordered. */ public short getOrdered() { return fOrdered; } /** * Fundamental Facet: bounded. */ public boolean getBounded(){ return fBounded; } /** * Fundamental Facet: cardinality. */ public boolean getFinite(){ return fFinite; } /** * Fundamental Facet: numeric. */ public boolean getNumeric(){ return fNumeric; } /** * Convenience method. [Facets]: check whether a facet is defined on this * type. * @param facetName The name of the facet. * @return True if the facet is defined, false otherwise. */ public boolean isDefinedFacet(short facetName) { if ((fFacetsDefined & facetName) != 0) return true; if (fPatternType != SPECIAL_PATTERN_NONE) return facetName == FACET_PATTERN; if (fValidationDV == DV_INTEGER) return facetName == FACET_PATTERN || facetName == FACET_FRACTIONDIGITS; return false; } /** * [facets]: all facets defined on this type. The value is a bit * combination of FACET_XXX constants of all defined facets. */ public short getDefinedFacets() { if (fPatternType != SPECIAL_PATTERN_NONE) return (short)(fFacetsDefined | FACET_PATTERN); if (fValidationDV == DV_INTEGER) return (short)(fFacetsDefined | FACET_PATTERN | FACET_FRACTIONDIGITS); return fFacetsDefined; } /** * Convenience method. [Facets]: check whether a facet is defined and * fixed on this type. * @param facetName The name of the facet. * @return True if the facet is fixed, false otherwise. */ public boolean isFixedFacet(short facetName) { if ((fFixedFacet & facetName) != 0) return true; if (fValidationDV == DV_INTEGER) return facetName == FACET_FRACTIONDIGITS; return false; } /** * [facets]: all defined facets for this type which are fixed. */ public short getFixedFacets() { if (fValidationDV == DV_INTEGER) return (short)(fFixedFacet | FACET_FRACTIONDIGITS); return fFixedFacet; } /** * Convenience method. Returns a value of a single constraining facet for * this simple type definition. This method must not be used to retrieve * values for <code>enumeration</code> and <code>pattern</code> facets. * @param facetName The name of the facet, i.e. * <code>FACET_LENGTH, FACET_TOTALDIGITS </code> (see * <code>XSConstants</code>). To retrieve the value for a pattern or * an enumeration, see <code>enumeration</code> and * <code>pattern</code>. * @return A value of the facet specified in <code>facetName</code> for * this simple type definition or <code>null</code>. */ public String getLexicalFacetValue(short facetName) { switch (facetName) { case FACET_LENGTH: return (fLength == -1)?null:Integer.toString(fLength); case FACET_MINLENGTH: return (fMinLength == -1)?null:Integer.toString(fMinLength); case FACET_MAXLENGTH: return (fMaxLength == -1)?null:Integer.toString(fMaxLength); case FACET_WHITESPACE: return WS_FACET_STRING[fWhiteSpace]; case FACET_MAXINCLUSIVE: return (fMaxInclusive == null)?null:fMaxInclusive.toString(); case FACET_MAXEXCLUSIVE: return (fMaxExclusive == null)?null:fMaxExclusive.toString(); case FACET_MINEXCLUSIVE: return (fMinExclusive == null)?null:fMinExclusive.toString(); case FACET_MININCLUSIVE: return (fMinInclusive == null)?null:fMinInclusive.toString(); case FACET_TOTALDIGITS: return (fTotalDigits == -1)?null:Integer.toString(fTotalDigits); case FACET_MAXSCALE: return ((fFacetsDefined & FACET_MAXSCALE) == 0)?null:Integer.toString(fMaxScale); case FACET_MINSCALE: return ((fFacetsDefined & FACET_MINSCALE) == 0)?null:Integer.toString(fMinScale); case FACET_EXPLICITTIMEZONE: return ET_FACET_STRING[fExplicitTimezone]; case FACET_FRACTIONDIGITS: if (fValidationDV == DV_INTEGER) { return "0"; } return (fFractionDigits == -1)?null:Integer.toString(fFractionDigits); } return null; } /** * A list of enumeration values if it exists, otherwise an empty * <code>StringList</code>. */ public StringList getLexicalEnumeration() { if (fLexicalEnumeration == null){ if (fEnumeration == null) return StringListImpl.EMPTY_LIST; int size = fEnumeration.size(); String[] strs = new String[size]; for (int i = 0; i < size; i++) strs[i] = fEnumeration.elementAt(i).toString(); fLexicalEnumeration = new StringListImpl(strs, size); } return fLexicalEnumeration; } /** * A list of actual enumeration values if it exists, otherwise an empty * <code>ObjectList</code>. */ public ObjectList getActualEnumeration() { if (fActualEnumeration == null) { fActualEnumeration = new AbstractObjectList() { public int getLength() { return (fEnumeration != null) ? fEnumeration.size() : 0; } public boolean contains(Object item) { return (fEnumeration != null && fEnumeration.contains(item)); } public Object item(int index) { if (index < 0 || index >= getLength()) { return null; } return fEnumeration.elementAt(index); } }; } return fActualEnumeration; } /** * A list of enumeration type values (as a list of ShortList objects) if it exists, otherwise returns * null */ public ObjectList getEnumerationItemTypeList() { if (fEnumerationItemTypeList == null) { if(fEnumerationItemType == null) return null; fEnumerationItemTypeList = new AbstractObjectList() { public int getLength() { return (fEnumerationItemType != null) ? fEnumerationItemType.length : 0; } public boolean contains(Object item) { if(fEnumerationItemType == null || !(item instanceof ShortList)) return false; for(int i = 0;i < fEnumerationItemType.length; i++) if(fEnumerationItemType[i] == item) return true; return false; } public Object item(int index) { if (index < 0 || index >= getLength()) { return null; } return fEnumerationItemType[index]; } }; } return fEnumerationItemTypeList; } public ShortList getEnumerationTypeList() { if (fEnumerationTypeList == null) { if (fEnumerationType == null) { return ShortListImpl.EMPTY_LIST; } fEnumerationTypeList = new ShortListImpl (fEnumerationType, fEnumerationType.length); } return fEnumerationTypeList; } /** * A list of pattern values if it exists, otherwise an empty * <code>StringList</code>. */ public StringList getLexicalPattern() { if (fPatternType == SPECIAL_PATTERN_NONE && fValidationDV != DV_INTEGER && fPatternStr == null) return StringListImpl.EMPTY_LIST; if (fLexicalPattern == null){ int size = fPatternStr == null ? 0 : fPatternStr.size(); String[] strs; if (fPatternType == SPECIAL_PATTERN_NMTOKEN) { strs = new String[size+1]; strs[size] = "\\c+"; } else if (fPatternType == SPECIAL_PATTERN_NAME) { strs = new String[size+1]; strs[size] = "\\i\\c*"; } else if (fPatternType == SPECIAL_PATTERN_NCNAME) { strs = new String[size+2]; strs[size] = "\\i\\c*"; strs[size+1] = "[\\i-[:]][\\c-[:]]*"; } else if (fValidationDV == DV_INTEGER) { strs = new String[size+1]; strs[size] = "[\\-+]?[0-9]+"; } else { strs = new String[size]; } for (int i = 0; i < size; i++) strs[i] = (String)fPatternStr.elementAt(i); fLexicalPattern = new StringListImpl(strs, strs.length); } return fLexicalPattern; } /** * [annotations]: a set of annotations for this simple type component if * it exists, otherwise an empty <code>XSObjectList</code>. */ public XSObjectList getAnnotations() { return (fAnnotations != null) ? fAnnotations : XSObjectListImpl.EMPTY_LIST; } private void calcFundamentalFacets() { setOrdered(); setNumeric(); setBounded(); setCardinality(); } private void setOrdered(){ // When {variety} is atomic, {value} is inherited from {value} of {base type definition}. For all "primitive" types {value} is as specified in the table in Fundamental Facets (C.1). if(fVariety == VARIETY_ATOMIC){ this.fOrdered = fBase.fOrdered; } // When {variety} is list, {value} is false. else if(fVariety == VARIETY_LIST){ this.fOrdered = ORDERED_FALSE; } // When {variety} is union, the {value} is partial unless one of the following: // 1. If every member of {member type definitions} is derived from a common ancestor other than the simple ur-type, then {value} is the same as that ancestor's ordered facet. // 2. If every member of {member type definitions} has a {value} of false for the ordered facet, then {value} is false. else if(fVariety == VARIETY_UNION){ int length = fMemberTypes.length; // REVISIT: is the length possible to be 0? if (length == 0) { this.fOrdered = ORDERED_PARTIAL; return; } short firstMemberOrderVal = fMemberTypes[0].fOrdered; // if any one of the memberTypes have partial order, set the order of this union to partial if (firstMemberOrderVal==ORDERED_PARTIAL) { this.fOrdered = ORDERED_PARTIAL; return; } // if any of the memberTypes are of different order, set the order of this union to partial short ancestorId = getPrimitiveDV(getFirstExpandedSimpleTypeValidationDV(fMemberTypes[0])); boolean commonAnc = true; for (int i=1; i<fMemberTypes.length; i++) { if (fMemberTypes[i].fOrdered != firstMemberOrderVal) { this.fOrdered = ORDERED_PARTIAL; return; } if (commonAnc) { commonAnc = (getPrimitiveDV(getFirstExpandedSimpleTypeValidationDV(fMemberTypes[i])) == ancestorId); } } // if all the memberTypes are false order, set the order of this union to false if (firstMemberOrderVal == ORDERED_FALSE) { this.fOrdered = ORDERED_FALSE; return; } // all the memberTypes are total order // if they're from the same primitive type, set the order of this union to total, otherwise partial this.fOrdered = commonAnc ? ORDERED_TOTAL : ORDERED_PARTIAL; } }//setOrdered private void setNumeric(){ if(fVariety == VARIETY_ATOMIC){ this.fNumeric = fBase.fNumeric; } else if(fVariety == VARIETY_LIST){ this.fNumeric = false; } else if(fVariety == VARIETY_UNION){ XSSimpleType[] memberTypes = fMemberTypes; for(int i = 0 ; i < memberTypes.length ; i++){ if(!memberTypes[i].getNumeric() ){ this.fNumeric = false; return; } } this.fNumeric = true; } }//setNumeric private void setBounded(){ if(fVariety == VARIETY_ATOMIC){ if( (((this.fFacetsDefined & FACET_MININCLUSIVE) != 0) || ((this.fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) && (((this.fFacetsDefined & FACET_MAXINCLUSIVE) != 0) || ((this.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) ){ this.fBounded = true; } else{ this.fBounded = false; } } else if(fVariety == VARIETY_LIST){ if( ((this.fFacetsDefined & FACET_LENGTH) != 0 ) || ( ((this.fFacetsDefined & FACET_MINLENGTH) != 0 ) && ((this.fFacetsDefined & FACET_MAXLENGTH) != 0 )) ){ this.fBounded = true; } else{ this.fBounded = false; } } else if(fVariety == VARIETY_UNION){ XSSimpleTypeDecl [] memberTypes = this.fMemberTypes; short ancestorId = 0 ; if(memberTypes.length > 0){ ancestorId = getPrimitiveDV(getFirstExpandedSimpleTypeValidationDV(memberTypes[0])); } for(int i = 0 ; i < memberTypes.length ; i++){ if(!memberTypes[i].getBounded() || (ancestorId != getPrimitiveDV(getFirstExpandedSimpleTypeValidationDV(memberTypes[i]))) ){ this.fBounded = false; return; } } this.fBounded = true; } }//setBounded // returns the validation DV of the first simple type not a union private short getFirstExpandedSimpleTypeValidationDV(XSSimpleTypeDecl simpleType) { if (simpleType.fVariety == VARIETY_UNION) { for (int i=0; i<simpleType.fMemberTypes.length; i++) { short validationDV = getFirstExpandedSimpleTypeValidationDV(simpleType.fMemberTypes[i]); if (validationDV != -1) { return validationDV; } } return -1; } return simpleType.fValidationDV; } // getFirstPrimitiveValidationDV() private boolean specialCardinalityCheck(){ if( (fBase.fValidationDV == XSSimpleTypeDecl.DV_DATE) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GYEARMONTH) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GYEAR) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GMONTHDAY) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GDAY) || (fBase.fValidationDV == XSSimpleTypeDecl.DV_GMONTH) ){ return true; } return false; } //specialCardinalityCheck() private void setCardinality(){ if(fVariety == VARIETY_ATOMIC){ if(fBase.fFinite){ this.fFinite = true; } else {// (!fBase.fFinite) if ( ((this.fFacetsDefined & FACET_LENGTH) != 0 ) || ((this.fFacetsDefined & FACET_MAXLENGTH) != 0 ) || ((this.fFacetsDefined & FACET_TOTALDIGITS) != 0 ) ){ this.fFinite = true; } else if( (((this.fFacetsDefined & FACET_MININCLUSIVE) != 0 ) || ((this.fFacetsDefined & FACET_MINEXCLUSIVE) != 0 )) && (((this.fFacetsDefined & FACET_MAXINCLUSIVE) != 0 ) || ((this.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0 )) ){ if( ((this.fFacetsDefined & FACET_FRACTIONDIGITS) != 0 ) || specialCardinalityCheck()){ this.fFinite = true; } else{ this.fFinite = false; } } else{ this.fFinite = false; } } } else if(fVariety == VARIETY_LIST){ if( ((this.fFacetsDefined & FACET_LENGTH) != 0 ) || ( ((this.fFacetsDefined & FACET_MINLENGTH) != 0 ) && ((this.fFacetsDefined & FACET_MAXLENGTH) != 0 )) ){ this.fFinite = true; } else{ this.fFinite = false; } } else if(fVariety == VARIETY_UNION){ XSSimpleType [] memberTypes = fMemberTypes; for(int i = 0 ; i < memberTypes.length ; i++){ if(!(memberTypes[i].getFinite()) ){ this.fFinite = false; return; } } this.fFinite = true; } }//setCardinality private short getPrimitiveDV(short validationDV){ if (validationDV == DV_ID || validationDV == DV_IDREF || validationDV == DV_ENTITY){ return DV_STRING; } else if (validationDV == DV_INTEGER) { return DV_DECIMAL; } else if (Constants.SCHEMA_1_1_SUPPORT && (validationDV == DV_YEARMONTHDURATION || validationDV == DV_DAYTIMEDURATION)) { return DV_DURATION; } else { return validationDV; } }//getPrimitiveDV() public boolean derivedFromType(XSTypeDefinition ancestor, short derivation) { // REVISIT: implement according to derivation // ancestor is null, return false if (ancestor == null) { return false; } // extract the actual XSTypeDefinition if the given ancestor is a delegate. while (ancestor instanceof XSSimpleTypeDelegate) { ancestor = ((XSSimpleTypeDelegate) ancestor).type; } // ancestor is anyType, return true // anyType is the only type whose base type is itself if (ancestor.getBaseType() == ancestor) { return true; } // recursively get base, and compare it with ancestor XSTypeDefinition type = this; while (type != ancestor && // compare with ancestor type != fAnySimpleType) { // reached anySimpleType type = type.getBaseType(); } return type == ancestor; } public boolean derivedFrom(String ancestorNS, String ancestorName, short derivation) { // REVISIT: implement according to derivation // ancestor is null, retur false if (ancestorName == null) return false; // ancestor is anyType, return true if (URI_SCHEMAFORSCHEMA.equals(ancestorNS) && ANY_TYPE.equals(ancestorName)) { return true; } // recursively get base, and compare it with ancestor XSTypeDefinition type = this; while (!(ancestorName.equals(type.getName()) && ((ancestorNS == null && type.getNamespace() == null) || (ancestorNS != null && ancestorNS.equals(type.getNamespace())))) && // compare with ancestor type != fAnySimpleType) { // reached anySimpleType type = (XSTypeDefinition)type.getBaseType(); } return type != fAnySimpleType; } /** * Checks if a type is derived from another by restriction, given the name * and namespace. See: * http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#TypeInfo-isDerivedFrom * * @param ancestorNS * The namspace of the ancestor type declaration * @param ancestorName * The name of the ancestor type declaration * @param derivationMethod * The derivation method * * @return boolean True if the ancestor type is derived from the reference type by the specifiied derivation method. */ public boolean isDOMDerivedFrom(String ancestorNS, String ancestorName, int derivationMethod) { // ancestor is null, return false if (ancestorName == null) return false; // ancestor is anyType, return true if (SchemaSymbols.URI_SCHEMAFORSCHEMA.equals(ancestorNS) && SchemaSymbols.ATTVAL_ANYTYPE.equals(ancestorName) && (((derivationMethod & DERIVATION_RESTRICTION) != 0) || (derivationMethod == DERIVATION_ANY))) { return true; } // restriction if ((derivationMethod & DERIVATION_RESTRICTION) != 0) { if (isDerivedByRestriction(ancestorNS, ancestorName, this)) { return true; } } // list if ((derivationMethod & DERIVATION_LIST) != 0) { if (isDerivedByList(ancestorNS, ancestorName, this)) { return true; } } // union if ((derivationMethod & DERIVATION_UNION) != 0) { if (isDerivedByUnion(ancestorNS, ancestorName, this)) { return true; } } // extension if (((derivationMethod & DERIVATION_EXTENSION) != 0) && (((derivationMethod & DERIVATION_RESTRICTION) == 0) && ((derivationMethod & DERIVATION_LIST) == 0) && ((derivationMethod & DERIVATION_UNION) == 0))) { return false; } // If the value of the parameter is 0 i.e. no bit (corresponding to // restriction, list, extension or union) is set to 1 for the // derivationMethod parameter. if (((derivationMethod & DERIVATION_EXTENSION) == 0) && (((derivationMethod & DERIVATION_RESTRICTION) == 0) && ((derivationMethod & DERIVATION_LIST) == 0) && ((derivationMethod & DERIVATION_UNION) == 0))) { return isDerivedByAny(ancestorNS, ancestorName, this); } return false; } /** * Checks if a type is derived from another by any combination of restriction, list ir union. See: * http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#TypeInfo-isDerivedFrom * * @param ancestorNS * The namspace of the ancestor type declaration * @param ancestorName * The name of the ancestor type declaration * @param type * The reference type definition * * @return boolean True if the type is derived by restriciton for the reference type */ private boolean isDerivedByAny(String ancestorNS, String ancestorName, XSTypeDefinition type) { boolean derivedFrom = false; XSTypeDefinition oldType = null; // for each base, item or member type while (type != null && type != oldType) { // If the ancestor type is reached or is the same as this type. if ((ancestorName.equals(type.getName())) && ((ancestorNS == null && type.getNamespace() == null) || (ancestorNS != null && ancestorNS.equals(type.getNamespace())))) { derivedFrom = true; break; } // check if derived by restriction or list or union if (isDerivedByRestriction(ancestorNS, ancestorName, type)) { return true; } else if (isDerivedByList(ancestorNS, ancestorName, type)) { return true; } else if (isDerivedByUnion(ancestorNS, ancestorName, type)) { return true; } oldType = type; // get the base, item or member type depending on the variety if (((XSSimpleTypeDecl) type).getVariety() == VARIETY_ABSENT || ((XSSimpleTypeDecl) type).getVariety() == VARIETY_ATOMIC) { type = type.getBaseType(); } else if (((XSSimpleTypeDecl) type).getVariety() == VARIETY_UNION) { for (int i = 0; i < ((XSSimpleTypeDecl) type).getMemberTypes().getLength(); i++) { return isDerivedByAny(ancestorNS, ancestorName, (XSTypeDefinition) ((XSSimpleTypeDecl) type) .getMemberTypes().item(i)); } } else if (((XSSimpleTypeDecl) type).getVariety() == VARIETY_LIST) { type = ((XSSimpleTypeDecl) type).getItemType(); } } return derivedFrom; } /** * DOM Level 3 * Checks if a type is derived from another by restriction. See: * http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#TypeInfo-isDerivedFrom * * @param ancestorNS * The namspace of the ancestor type declaration * @param ancestorName * The name of the ancestor type declaration * @param type * The reference type definition * * @return boolean True if the type is derived by restriciton for the * reference type */ private boolean isDerivedByRestriction (String ancestorNS, String ancestorName, XSTypeDefinition type) { XSTypeDefinition oldType = null; while (type != null && type != oldType) { if ((ancestorName.equals(type.getName())) && ((ancestorNS != null && ancestorNS.equals(type.getNamespace())) || (type.getNamespace() == null && ancestorNS == null))) { return true; } oldType = type; type = type.getBaseType(); } return false; } /** * Checks if a type is derived from another by list. See: * http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#TypeInfo-isDerivedFrom * * @param ancestorNS * The namspace of the ancestor type declaration * @param ancestorName * The name of the ancestor type declaration * @param type * The reference type definition * * @return boolean True if the type is derived by list for the reference type */ private boolean isDerivedByList (String ancestorNS, String ancestorName, XSTypeDefinition type) { // If the variety is union if (type !=null && ((XSSimpleTypeDefinition)type).getVariety() == VARIETY_LIST) { // get the {item type} XSTypeDefinition itemType = ((XSSimpleTypeDefinition)type).getItemType(); // T2 is the {item type definition} if (itemType != null) { // T2 is derived from the other type definition by DERIVATION_RESTRICTION if (isDerivedByRestriction(ancestorNS, ancestorName, itemType)) { return true; } } } return false; } /** * Checks if a type is derived from another by union. See: * http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#TypeInfo-isDerivedFrom * * @param ancestorNS * The namspace of the ancestor type declaration * @param ancestorName * The name of the ancestor type declaration * @param type * The reference type definition * * @return boolean True if the type is derived by union for the reference type */ private boolean isDerivedByUnion (String ancestorNS, String ancestorName, XSTypeDefinition type) { // If the variety is union if (type !=null && ((XSSimpleTypeDefinition)type).getVariety() == VARIETY_UNION) { // get member types XSObjectList memberTypes = ((XSSimpleTypeDefinition)type).getMemberTypes(); for (int i = 0; i < memberTypes.getLength(); i++) { // One of the {member type definitions} is T2. if (memberTypes.item(i) != null) { // T2 is derived from the other type definition by DERIVATION_RESTRICTION if (isDerivedByRestriction(ancestorNS, ancestorName,(XSSimpleTypeDefinition)memberTypes.item(i))) { return true; } } } } return false; } static final XSSimpleTypeDecl fAnySimpleType = new XSSimpleTypeDecl(null, "anySimpleType", DV_ANYSIMPLETYPE, ORDERED_FALSE, false, true, false, true, XSConstants.ANYSIMPLETYPE_DT); static final XSSimpleTypeDecl fAnyAtomicType = new XSSimpleTypeDecl(fAnySimpleType, "anyAtomicType", DV_ANYATOMICTYPE, ORDERED_FALSE, false, true, false, true, XSSimpleTypeDecl.ANYATOMICTYPE_DT); static final XSSimpleTypeDecl fError = new XSSimpleTypeDecl(fAnySimpleType, "error", DV_ERROR, ORDERED_FALSE, false, true, false, true, XSSimpleTypeDecl.ERROR_DT); /** * Validation context used to validate facet values. */ static final ValidationContext fDummyContext = new ValidationContext() { public boolean needFacetChecking() { return true; } public boolean needExtraChecking() { return false; } public boolean needToNormalize() { return false; } public boolean useNamespaces() { return true; } public boolean isEntityDeclared(String name) { return false; } public boolean isEntityUnparsed(String name) { return false; } public boolean isIdDeclared(String name) { return false; } public void addId(String name) { } public void addIdRef(String name) { } public String getSymbol (String symbol) { return symbol.intern(); } public String getURI(String prefix) { return null; } public Locale getLocale() { return Locale.getDefault(); } public TypeValidatorHelper getTypeValidatorHelper() { return TypeValidatorHelper.getInstance(Constants.SCHEMA_VERSION_1_0); } }; private boolean fAnonymous = false; /** * A wrapper of ValidationContext, to provide a way of switching to a * different Namespace declaration context. */ static final class ValidationContextImpl implements ValidationContext { final ValidationContext fExternal; ValidationContextImpl(ValidationContext external) { fExternal = external; } NamespaceContext fNSContext; void setNSContext(NamespaceContext nsContext) { fNSContext = nsContext; } public boolean needFacetChecking() { return fExternal.needFacetChecking(); } public boolean needExtraChecking() { return fExternal.needExtraChecking(); } public boolean needToNormalize() { return fExternal.needToNormalize(); } // schema validation is predicated upon namespaces public boolean useNamespaces() { return true; } public boolean isEntityDeclared (String name) { return fExternal.isEntityDeclared(name); } public boolean isEntityUnparsed (String name) { return fExternal.isEntityUnparsed(name); } public boolean isIdDeclared (String name) { return fExternal.isIdDeclared(name); } public void addId(String name) { fExternal.addId(name); } public void addIdRef(String name) { fExternal.addIdRef(name); } public String getSymbol (String symbol) { return fExternal.getSymbol(symbol); } public String getURI(String prefix) { if (fNSContext == null) { return fExternal.getURI(prefix); } else { return fNSContext.getURI(prefix); } } public Locale getLocale() { return fExternal.getLocale(); } public TypeValidatorHelper getTypeValidatorHelper() { return fExternal.getTypeValidatorHelper(); } } public void reset(){ // if it's immutable, can't be reset: if (fIsImmutable) return; fItemType = null; fMemberTypes = null; fTypeName = null; fTargetNamespace = null; fFinalSet = 0; fBase = null; fVariety = -1; fValidationDV = -1; fFacetsDefined = 0; fFixedFacet = 0; //for constraining facets fWhiteSpace = 0; fExplicitTimezone = ET_OPTIONAL; fLength = -1; fMinLength = -1; fMaxLength = -1; fTotalDigits = -1; fFractionDigits = -1; fPattern = null; fPatternStr = null; fEnumeration = null; fEnumerationType = null; fEnumerationItemType = null; fLexicalPattern = null; fLexicalEnumeration = null; fMaxInclusive = null; fMaxExclusive = null; fMinExclusive = null; fMinInclusive = null; fMaxScale = 0; fMinScale = 0; lengthAnnotation = null; minLengthAnnotation = null; maxLengthAnnotation = null; whiteSpaceAnnotation = null; totalDigitsAnnotation = null; fractionDigitsAnnotation = null; patternAnnotations = null; enumerationAnnotations = null; maxInclusiveAnnotation = null; maxExclusiveAnnotation = null; minInclusiveAnnotation = null; minExclusiveAnnotation = null; maxScaleAnnotation = null; minScaleAnnotation = null; explicitTimezoneAnnotation = null; fPatternType = SPECIAL_PATTERN_NONE; fAnnotations = null; fFacets = null; fContext = null; // REVISIT: reset for fundamental facets } /** * @see org.apache.xerces.xs.XSObject#getNamespaceItem() */ public XSNamespaceItem getNamespaceItem() { return fNamespaceItem; } public void setNamespaceItem(XSNamespaceItem namespaceItem) { fNamespaceItem = namespaceItem; } /** * */ public void setContext(XSObject context) { fContext = context; } public XSObject getContext() { return fContext; } /** * @see java.lang.Object#toString() */ public String toString() { return this.fTargetNamespace+"," +this.fTypeName; } /** * A list of constraining facets if it exists, otherwise an empty * <code>XSObjectList</code>. Note: This method must not be used to * retrieve values for <code>enumeration</code> and <code>pattern</code> * facets. */ public XSObjectList getFacets() { if (fFacets == null && (fFacetsDefined != 0 || fValidationDV == DV_INTEGER)) { XSFacetImpl[] facets = new XSFacetImpl[13]; int count = 0; if ((fFacetsDefined & FACET_WHITESPACE) != 0) { facets[count] = new XSFacetImpl( FACET_WHITESPACE, WS_FACET_STRING[fWhiteSpace], (fFixedFacet & FACET_WHITESPACE) != 0, whiteSpaceAnnotation); count++; } if (fLength != -1) { facets[count] = new XSFacetImpl( FACET_LENGTH, Integer.toString(fLength), (fFixedFacet & FACET_LENGTH) != 0, lengthAnnotation); count++; } if (fMinLength != -1) { facets[count] = new XSFacetImpl( FACET_MINLENGTH, Integer.toString(fMinLength), (fFixedFacet & FACET_MINLENGTH) != 0, minLengthAnnotation); count++; } if (fMaxLength != -1) { facets[count] = new XSFacetImpl( FACET_MAXLENGTH, Integer.toString(fMaxLength), (fFixedFacet & FACET_MAXLENGTH) != 0, maxLengthAnnotation); count++; } if (fTotalDigits != -1) { facets[count] = new XSFacetImpl( FACET_TOTALDIGITS, Integer.toString(fTotalDigits), (fFixedFacet & FACET_TOTALDIGITS) != 0, totalDigitsAnnotation); count++; } if (fValidationDV == DV_INTEGER) { facets[count] = new XSFacetImpl( FACET_FRACTIONDIGITS, "0", true, fractionDigitsAnnotation); count++; } else if (fFractionDigits != -1) { facets[count] = new XSFacetImpl( FACET_FRACTIONDIGITS, Integer.toString(fFractionDigits), (fFixedFacet & FACET_FRACTIONDIGITS) != 0, fractionDigitsAnnotation); count++; } if (fMaxInclusive != null) { facets[count] = new XSFacetImpl( FACET_MAXINCLUSIVE, fMaxInclusive.toString(), (fFixedFacet & FACET_MAXINCLUSIVE) != 0, maxInclusiveAnnotation); count++; } if (fMaxExclusive != null) { facets[count] = new XSFacetImpl( FACET_MAXEXCLUSIVE, fMaxExclusive.toString(), (fFixedFacet & FACET_MAXEXCLUSIVE) != 0, maxExclusiveAnnotation); count++; } if (fMinExclusive != null) { facets[count] = new XSFacetImpl( FACET_MINEXCLUSIVE, fMinExclusive.toString(), (fFixedFacet & FACET_MINEXCLUSIVE) != 0, minExclusiveAnnotation); count++; } if (fMinInclusive != null) { facets[count] = new XSFacetImpl( FACET_MININCLUSIVE, fMinInclusive.toString(), (fFixedFacet & FACET_MININCLUSIVE) != 0, minInclusiveAnnotation); count++; } if ((fFacetsDefined & FACET_EXPLICITTIMEZONE) != 0) { facets[count] = new XSFacetImpl ( FACET_EXPLICITTIMEZONE, ET_FACET_STRING[fExplicitTimezone], (fFixedFacet & FACET_EXPLICITTIMEZONE) != 0, explicitTimezoneAnnotation); count++; } if ((fFacetsDefined & FACET_MAXSCALE) != 0) { facets[count] = new XSFacetImpl ( FACET_MAXSCALE, Integer.toString(fMaxScale), (fFixedFacet & FACET_MAXSCALE) != 0, maxScaleAnnotation); count++; } if ((fFacetsDefined & FACET_MINSCALE) != 0) { facets[count] = new XSFacetImpl ( FACET_MINSCALE, Integer.toString(fMinScale), (fFixedFacet & FACET_MINSCALE) != 0, minScaleAnnotation); count++; } fFacets = new XSObjectListImpl(facets, count); } return (fFacets != null) ? fFacets : XSObjectListImpl.EMPTY_LIST; } /** * A list of enumeration and pattern constraining facets if it exists, * otherwise an empty <code>XSObjectList</code>. */ public XSObjectList getMultiValueFacets() { if (fMultiValueFacets == null && ((fFacetsDefined & FACET_ENUMERATION) != 0 || (fFacetsDefined & FACET_ASSERT) != 0 || (fFacetsDefined & FACET_PATTERN) != 0 || fPatternType != SPECIAL_PATTERN_NONE || fValidationDV == DV_INTEGER)) { XSMVFacetImpl[] facets = new XSMVFacetImpl[3]; int count = 0; if ((fFacetsDefined & FACET_PATTERN) != 0 || fPatternType != SPECIAL_PATTERN_NONE || fValidationDV == DV_INTEGER) { facets[count] = new XSMVFacetImpl( FACET_PATTERN, this.getLexicalPattern(), patternAnnotations); count++; } if (fEnumeration != null) { facets[count] = new XSMVFacetImpl( FACET_ENUMERATION, this.getLexicalEnumeration(), enumerationAnnotations); count++; } if (fAssertion != null) { facets[count] = new XSMVFacetImpl(FACET_ASSERT, fAssertion); count++; } fMultiValueFacets = new XSObjectListImpl(facets, count); } return (fMultiValueFacets != null) ? fMultiValueFacets : XSObjectListImpl.EMPTY_LIST; } public Object getMinInclusiveValue() { return fMinInclusive; } public Object getMinExclusiveValue() { return fMinExclusive; } public Object getMaxInclusiveValue() { return fMaxInclusive; } public Object getMaxExclusiveValue() { return fMaxExclusive; } public void setAnonymous(boolean anon) { fAnonymous = anon; } private static final class XSFacetImpl implements XSFacet { final short kind; final String value; final boolean fixed; final XSObjectList annotations; public XSFacetImpl(short kind, String value, boolean fixed, XSAnnotation annotation) { this.kind = kind; this.value = value; this.fixed = fixed; if (annotation != null) { this.annotations = new XSObjectListImpl(); ((XSObjectListImpl)this.annotations).addXSObject(annotation); } else { this.annotations = XSObjectListImpl.EMPTY_LIST; } } /* * (non-Javadoc) * * @see org.apache.xerces.xs.XSFacet#getAnnotation() */ /** * Optional. Annotation. */ public XSAnnotation getAnnotation() { return (XSAnnotation) annotations.item(0); } /* * (non-Javadoc) * * @see org.apache.xerces.xs.XSFacet#getAnnotations() */ /** * Optional. Annotations. */ public XSObjectList getAnnotations() { return annotations; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSFacet#getFacetKind() */ public short getFacetKind() { return kind; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSFacet#getLexicalFacetValue() */ public String getLexicalFacetValue() { return value; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSFacet#isFixed() */ public boolean getFixed() { return fixed; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSObject#getName() */ public String getName() { return null; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSObject#getNamespace() */ public String getNamespace() { return null; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSObject#getNamespaceItem() */ public XSNamespaceItem getNamespaceItem() { // REVISIT: implement return null; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSObject#getType() */ public short getType() { return XSConstants.FACET; } } private static final class XSMVFacetImpl implements XSMultiValueFacet { final short kind; final XSObjectList annotations; final StringList values; final Vector asserts; public XSMVFacetImpl(short kind, StringList values, XSObjectList annotations) { this.kind = kind; this.values = values; this.annotations = (annotations != null) ? annotations : XSObjectListImpl.EMPTY_LIST; this.asserts = null; } /* * overloaded constructor. added to support assertions. */ public XSMVFacetImpl(short kind, Vector asserts) { this.kind = kind; this.asserts = asserts; this.values = null; this.annotations = null; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSFacet#getFacetKind() */ public short getFacetKind() { return kind; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSMultiValueFacet#getAnnotations() */ public XSObjectList getAnnotations() { return annotations; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSMultiValueFacet#getLexicalFacetValues() */ public StringList getLexicalFacetValues() { return values; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSObject#getName() */ public String getName() { return null; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSObject#getNamespace() */ public String getNamespace() { return null; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSObject#getNamespaceItem() */ public XSNamespaceItem getNamespaceItem() { // REVISIT: implement return null; } /* (non-Javadoc) * @see org.apache.xerces.xs.XSObject#getType() */ public short getType() { return XSConstants.MULTIVALUE_FACET; } public Vector getAsserts() { return asserts; } } private static abstract class AbstractObjectList extends AbstractList implements ObjectList { public Object get(int index) { if (index >= 0 && index < getLength()) { return item(index); } throw new IndexOutOfBoundsException("Index: " + index); } public int size() { return getLength(); } } public String getTypeNamespace() { return getNamespace(); } public boolean isDerivedFrom(String typeNamespaceArg, String typeNameArg, int derivationMethod) { return isDOMDerivedFrom(typeNamespaceArg, typeNameArg, derivationMethod); } private short convertToPrimitiveKind(short valueType) { /** Primitive datatypes. */ if (valueType <= XSConstants.NOTATION_DT) { return valueType; } /** Types derived from string. */ if (valueType <= XSConstants.ENTITY_DT) { return XSConstants.STRING_DT; } /** Types derived from decimal. */ if (valueType <= XSConstants.POSITIVEINTEGER_DT) { return XSConstants.DECIMAL_DT; } /** Other types. */ return valueType; } } // class XSSimpleTypeDecl
false
false
null
null
diff --git a/src/com/android/mms/ui/MessageItem.java b/src/com/android/mms/ui/MessageItem.java index de2da9ef..f0926aad 100644 --- a/src/com/android/mms/ui/MessageItem.java +++ b/src/com/android/mms/ui/MessageItem.java @@ -1,421 +1,423 @@ /* * Copyright (C) 2008 Esmertec AG. * 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.mms.ui; import java.util.regex.Pattern; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.Telephony.Mms; import android.provider.Telephony.MmsSms; import android.provider.Telephony.Sms; import android.text.TextUtils; import android.util.Log; import com.android.mms.LogTag; import com.android.mms.MmsApp; import com.android.mms.R; import com.android.mms.data.Contact; +import com.android.mms.data.WorkingMessage; import com.android.mms.model.SlideModel; import com.android.mms.model.SlideshowModel; import com.android.mms.model.TextModel; import com.android.mms.ui.MessageListAdapter.ColumnsMap; import com.android.mms.util.AddressUtils; import com.android.mms.util.DownloadManager; import com.android.mms.util.ItemLoadedCallback; import com.android.mms.util.ItemLoadedFuture; import com.android.mms.util.PduLoaderManager; import com.google.android.mms.MmsException; import com.google.android.mms.pdu.EncodedStringValue; import com.google.android.mms.pdu.MultimediaMessagePdu; import com.google.android.mms.pdu.NotificationInd; import com.google.android.mms.pdu.PduHeaders; import com.google.android.mms.pdu.PduPersister; import com.google.android.mms.pdu.RetrieveConf; import com.google.android.mms.pdu.SendReq; /** * Mostly immutable model for an SMS/MMS message. * * <p>The only mutable field is the cached formatted message member, * the formatting of which is done outside this model in MessageListItem. */ public class MessageItem { private static String TAG = "MessageItem"; public enum DeliveryStatus { NONE, INFO, FAILED, PENDING, RECEIVED } public static int ATTACHMENT_TYPE_NOT_LOADED = -1; final Context mContext; final String mType; final long mMsgId; final int mBoxId; DeliveryStatus mDeliveryStatus; boolean mReadReport; boolean mLocked; // locked to prevent auto-deletion String mTimestamp; String mAddress; String mContact; String mBody; // Body of SMS, first text of MMS. String mTextContentType; // ContentType of text of MMS. Pattern mHighlight; // portion of message to highlight (from search) // The only non-immutable field. Not synchronized, as access will // only be from the main GUI thread. Worst case if accessed from // another thread is it'll return null and be set again from that // thread. CharSequence mCachedFormattedMessage; // The last message is cached above in mCachedFormattedMessage. In the latest design, we // show "Sending..." in place of the timestamp when a message is being sent. mLastSendingState // is used to keep track of the last sending state so that if the current sending state is // different, we can clear the message cache so it will get rebuilt and recached. boolean mLastSendingState; // Fields for MMS only. Uri mMessageUri; int mMessageType; int mAttachmentType; String mSubject; SlideshowModel mSlideshow; int mMessageSize; int mErrorType; int mErrorCode; int mMmsStatus; Cursor mCursor; ColumnsMap mColumnsMap; private PduLoadedCallback mPduLoadedCallback; private ItemLoadedFuture mItemLoadedFuture; MessageItem(Context context, String type, final Cursor cursor, final ColumnsMap columnsMap, Pattern highlight) throws MmsException { mContext = context; mMsgId = cursor.getLong(columnsMap.mColumnMsgId); mHighlight = highlight; mType = type; mCursor = cursor; mColumnsMap = columnsMap; if ("sms".equals(type)) { mReadReport = false; // No read reports in sms long status = cursor.getLong(columnsMap.mColumnSmsStatus); if (status == Sms.STATUS_NONE) { // No delivery report requested mDeliveryStatus = DeliveryStatus.NONE; } else if (status >= Sms.STATUS_FAILED) { // Failure mDeliveryStatus = DeliveryStatus.FAILED; } else if (status >= Sms.STATUS_PENDING) { // Pending mDeliveryStatus = DeliveryStatus.PENDING; } else { // Success mDeliveryStatus = DeliveryStatus.RECEIVED; } mMessageUri = ContentUris.withAppendedId(Sms.CONTENT_URI, mMsgId); // Set contact and message body mBoxId = cursor.getInt(columnsMap.mColumnSmsType); mAddress = cursor.getString(columnsMap.mColumnSmsAddress); if (Sms.isOutgoingFolder(mBoxId)) { String meString = context.getString( R.string.messagelist_sender_self); mContact = meString; } else { // For incoming messages, the ADDRESS field contains the sender. mContact = Contact.get(mAddress, false).getName(); } mBody = cursor.getString(columnsMap.mColumnSmsBody); // Unless the message is currently in the progress of being sent, it gets a time stamp. if (!isOutgoingMessage()) { // Set "received" or "sent" time stamp long date = cursor.getLong(columnsMap.mColumnSmsDate); mTimestamp = MessageUtils.formatTimeStampString(context, date); } mLocked = cursor.getInt(columnsMap.mColumnSmsLocked) != 0; mErrorCode = cursor.getInt(columnsMap.mColumnSmsErrorCode); } else if ("mms".equals(type)) { mMessageUri = ContentUris.withAppendedId(Mms.CONTENT_URI, mMsgId); mBoxId = cursor.getInt(columnsMap.mColumnMmsMessageBox); mMessageType = cursor.getInt(columnsMap.mColumnMmsMessageType); mErrorType = cursor.getInt(columnsMap.mColumnMmsErrorType); String subject = cursor.getString(columnsMap.mColumnMmsSubject); if (!TextUtils.isEmpty(subject)) { EncodedStringValue v = new EncodedStringValue( cursor.getInt(columnsMap.mColumnMmsSubjectCharset), PduPersister.getBytes(subject)); mSubject = v.getString(); } mLocked = cursor.getInt(columnsMap.mColumnMmsLocked) != 0; mSlideshow = null; - mAttachmentType = ATTACHMENT_TYPE_NOT_LOADED; mDeliveryStatus = DeliveryStatus.NONE; mReadReport = false; mBody = null; mMessageSize = 0; mTextContentType = null; // Initialize the time stamp to "" instead of null mTimestamp = ""; mMmsStatus = cursor.getInt(columnsMap.mColumnMmsStatus); + mAttachmentType = cursor.getInt(columnsMap.mColumnMmsTextOnly) != 0 ? + WorkingMessage.TEXT : ATTACHMENT_TYPE_NOT_LOADED; // Start an async load of the pdu. If the pdu is already loaded, the callback // will get called immediately boolean loadSlideshow = mMessageType != PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND; mItemLoadedFuture = MmsApp.getApplication().getPduLoaderManager() .getPdu(mMessageUri, loadSlideshow, new PduLoadedMessageItemCallback()); } else { throw new MmsException("Unknown type of the message: " + type); } } private void interpretFrom(EncodedStringValue from, Uri messageUri) { if (from != null) { mAddress = from.getString(); } else { // In the rare case when getting the "from" address from the pdu fails, // (e.g. from == null) fall back to a slower, yet more reliable method of // getting the address from the "addr" table. This is what the Messaging // notification system uses. mAddress = AddressUtils.getFrom(mContext, messageUri); } mContact = TextUtils.isEmpty(mAddress) ? "" : Contact.get(mAddress, false).getName(); } public boolean isMms() { return mType.equals("mms"); } public boolean isSms() { return mType.equals("sms"); } public boolean isDownloaded() { return (mMessageType != PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND); } public boolean isMe() { // Logic matches MessageListAdapter.getItemViewType which is used to decide which // type of MessageListItem to create: a left or right justified item depending on whether // the message is incoming or outgoing. boolean isIncomingMms = isMms() && (mBoxId == Mms.MESSAGE_BOX_INBOX || mBoxId == Mms.MESSAGE_BOX_ALL); boolean isIncomingSms = isSms() && (mBoxId == Sms.MESSAGE_TYPE_INBOX || mBoxId == Sms.MESSAGE_TYPE_ALL); return !(isIncomingMms || isIncomingSms); } public boolean isOutgoingMessage() { boolean isOutgoingMms = isMms() && (mBoxId == Mms.MESSAGE_BOX_OUTBOX); boolean isOutgoingSms = isSms() && ((mBoxId == Sms.MESSAGE_TYPE_FAILED) || (mBoxId == Sms.MESSAGE_TYPE_OUTBOX) || (mBoxId == Sms.MESSAGE_TYPE_QUEUED)); return isOutgoingMms || isOutgoingSms; } public boolean isSending() { return !isFailedMessage() && isOutgoingMessage(); } public boolean isFailedMessage() { boolean isFailedMms = isMms() && (mErrorType >= MmsSms.ERR_TYPE_GENERIC_PERMANENT); boolean isFailedSms = isSms() && (mBoxId == Sms.MESSAGE_TYPE_FAILED); return isFailedMms || isFailedSms; } // Note: This is the only mutable field in this class. Think of // mCachedFormattedMessage as a C++ 'mutable' field on a const // object, with this being a lazy accessor whose logic to set it // is outside the class for model/view separation reasons. In any // case, please keep this class conceptually immutable. public void setCachedFormattedMessage(CharSequence formattedMessage) { mCachedFormattedMessage = formattedMessage; } public CharSequence getCachedFormattedMessage() { boolean isSending = isSending(); if (isSending != mLastSendingState) { mLastSendingState = isSending; mCachedFormattedMessage = null; // clear cache so we'll rebuild the message // to show "Sending..." or the sent date. } return mCachedFormattedMessage; } public int getBoxId() { return mBoxId; } public long getMessageId() { return mMsgId; } public int getMmsDownloadStatus() { return mMmsStatus & ~DownloadManager.DEFERRED_MASK; } @Override public String toString() { return "type: " + mType + " box: " + mBoxId + " uri: " + mMessageUri + " address: " + mAddress + " contact: " + mContact + " read: " + mReadReport + " delivery status: " + mDeliveryStatus; } public class PduLoadedMessageItemCallback implements ItemLoadedCallback { public void onItemLoaded(Object result, Throwable exception) { if (exception != null) { Log.e(TAG, "PduLoadedMessageItemCallback PDU couldn't be loaded: ", exception); return; } PduLoaderManager.PduLoaded pduLoaded = (PduLoaderManager.PduLoaded)result; long timestamp = 0L; if (PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND == mMessageType) { mDeliveryStatus = DeliveryStatus.NONE; NotificationInd notifInd = (NotificationInd)pduLoaded.mPdu; interpretFrom(notifInd.getFrom(), mMessageUri); // Borrow the mBody to hold the URL of the message. mBody = new String(notifInd.getContentLocation()); mMessageSize = (int) notifInd.getMessageSize(); timestamp = notifInd.getExpiry() * 1000L; } else { if (mCursor.isClosed()) { return; } MultimediaMessagePdu msg = (MultimediaMessagePdu)pduLoaded.mPdu; mSlideshow = pduLoaded.mSlideshow; mAttachmentType = MessageUtils.getAttachmentType(mSlideshow); if (mMessageType == PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF) { if (msg == null) { interpretFrom(null, mMessageUri); } else { RetrieveConf retrieveConf = (RetrieveConf) msg; interpretFrom(retrieveConf.getFrom(), mMessageUri); timestamp = retrieveConf.getDate() * 1000L; } } else { // Use constant string for outgoing messages mContact = mAddress = mContext.getString(R.string.messagelist_sender_self); timestamp = msg == null ? 0 : ((SendReq) msg).getDate() * 1000L; } SlideModel slide = mSlideshow == null ? null : mSlideshow.get(0); if ((slide != null) && slide.hasText()) { TextModel tm = slide.getText(); mBody = tm.getText(); mTextContentType = tm.getContentType(); } mMessageSize = mSlideshow == null ? 0 : mSlideshow.getTotalMessageSize(); String report = mCursor.getString(mColumnsMap.mColumnMmsDeliveryReport); if ((report == null) || !mAddress.equals(mContext.getString( R.string.messagelist_sender_self))) { mDeliveryStatus = DeliveryStatus.NONE; } else { int reportInt; try { reportInt = Integer.parseInt(report); if (reportInt == PduHeaders.VALUE_YES) { mDeliveryStatus = DeliveryStatus.RECEIVED; } else { mDeliveryStatus = DeliveryStatus.NONE; } } catch (NumberFormatException nfe) { Log.e(TAG, "Value for delivery report was invalid."); mDeliveryStatus = DeliveryStatus.NONE; } } report = mCursor.getString(mColumnsMap.mColumnMmsReadReport); if ((report == null) || !mAddress.equals(mContext.getString( R.string.messagelist_sender_self))) { mReadReport = false; } else { int reportInt; try { reportInt = Integer.parseInt(report); mReadReport = (reportInt == PduHeaders.VALUE_YES); } catch (NumberFormatException nfe) { Log.e(TAG, "Value for read report was invalid."); mReadReport = false; } } } if (!isOutgoingMessage()) { if (PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND == mMessageType) { mTimestamp = mContext.getString(R.string.expire_on, MessageUtils.formatTimeStampString(mContext, timestamp)); } else { mTimestamp = MessageUtils.formatTimeStampString(mContext, timestamp); } } if (mPduLoadedCallback != null) { mPduLoadedCallback.onPduLoaded(MessageItem.this); } } } public void setOnPduLoaded(PduLoadedCallback pduLoadedCallback) { mPduLoadedCallback = pduLoadedCallback; } public void cancelPduLoading() { if (mItemLoadedFuture != null) { if (Log.isLoggable(LogTag.APP, Log.DEBUG)) { Log.v(TAG, "cancelPduLoading for: " + this); } mItemLoadedFuture.cancel(); mItemLoadedFuture = null; } } public interface PduLoadedCallback { /** * Called when this item's pdu and slideshow are finished loading. * * @param messageItem the MessageItem that finished loading. */ void onPduLoaded(MessageItem messageItem); } public SlideshowModel getSlideshow() { return mSlideshow; } } diff --git a/src/com/android/mms/ui/MessageListAdapter.java b/src/com/android/mms/ui/MessageListAdapter.java index 8ac335fe..fa1d65a9 100644 --- a/src/com/android/mms/ui/MessageListAdapter.java +++ b/src/com/android/mms/ui/MessageListAdapter.java @@ -1,493 +1,503 @@ /* * Copyright (C) 2008 Esmertec AG. * 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.mms.ui; import java.util.regex.Pattern; import android.content.Context; import android.database.Cursor; import android.os.Handler; import android.provider.BaseColumns; import android.provider.Telephony.Mms; import android.provider.Telephony.MmsSms; import android.provider.Telephony.MmsSms.PendingMessages; import android.provider.Telephony.Sms; import android.provider.Telephony.Sms.Conversations; import android.provider.Telephony.TextBasedSmsColumns; import android.util.Log; import android.util.LruCache; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.CursorAdapter; import android.widget.ListView; import com.android.mms.R; import com.google.android.mms.MmsException; /** * The back-end data adapter of a message list. */ public class MessageListAdapter extends CursorAdapter { private static final String TAG = "MessageListAdapter"; private static final boolean LOCAL_LOGV = false; static final String[] PROJECTION = new String[] { // TODO: should move this symbol into com.android.mms.telephony.Telephony. MmsSms.TYPE_DISCRIMINATOR_COLUMN, BaseColumns._ID, Conversations.THREAD_ID, // For SMS Sms.ADDRESS, Sms.BODY, Sms.DATE, Sms.DATE_SENT, Sms.READ, Sms.TYPE, Sms.STATUS, Sms.LOCKED, Sms.ERROR_CODE, // For MMS Mms.SUBJECT, Mms.SUBJECT_CHARSET, Mms.DATE, Mms.DATE_SENT, Mms.READ, Mms.MESSAGE_TYPE, Mms.MESSAGE_BOX, Mms.DELIVERY_REPORT, Mms.READ_REPORT, PendingMessages.ERROR_TYPE, Mms.LOCKED, - Mms.STATUS + Mms.STATUS, + Mms.TEXT_ONLY }; // The indexes of the default columns which must be consistent // with above PROJECTION. static final int COLUMN_MSG_TYPE = 0; static final int COLUMN_ID = 1; static final int COLUMN_THREAD_ID = 2; static final int COLUMN_SMS_ADDRESS = 3; static final int COLUMN_SMS_BODY = 4; static final int COLUMN_SMS_DATE = 5; static final int COLUMN_SMS_DATE_SENT = 6; static final int COLUMN_SMS_READ = 7; static final int COLUMN_SMS_TYPE = 8; static final int COLUMN_SMS_STATUS = 9; static final int COLUMN_SMS_LOCKED = 10; static final int COLUMN_SMS_ERROR_CODE = 11; static final int COLUMN_MMS_SUBJECT = 12; static final int COLUMN_MMS_SUBJECT_CHARSET = 13; static final int COLUMN_MMS_DATE = 14; static final int COLUMN_MMS_DATE_SENT = 15; static final int COLUMN_MMS_READ = 16; static final int COLUMN_MMS_MESSAGE_TYPE = 17; static final int COLUMN_MMS_MESSAGE_BOX = 18; static final int COLUMN_MMS_DELIVERY_REPORT = 19; static final int COLUMN_MMS_READ_REPORT = 20; static final int COLUMN_MMS_ERROR_TYPE = 21; static final int COLUMN_MMS_LOCKED = 22; static final int COLUMN_MMS_STATUS = 23; + static final int COLUMN_MMS_TEXT_ONLY = 24; private static final int CACHE_SIZE = 50; public static final int INCOMING_ITEM_TYPE_SMS = 0; public static final int OUTGOING_ITEM_TYPE_SMS = 1; public static final int INCOMING_ITEM_TYPE_MMS = 2; public static final int OUTGOING_ITEM_TYPE_MMS = 3; protected LayoutInflater mInflater; private final MessageItemCache mMessageItemCache; private final ColumnsMap mColumnsMap; private OnDataSetChangedListener mOnDataSetChangedListener; private Handler mMsgListItemHandler; private Pattern mHighlight; private Context mContext; private boolean mIsGroupConversation; public MessageListAdapter( Context context, Cursor c, ListView listView, boolean useDefaultColumnsMap, Pattern highlight) { super(context, c, FLAG_REGISTER_CONTENT_OBSERVER); mContext = context; mHighlight = highlight; mInflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); mMessageItemCache = new MessageItemCache(CACHE_SIZE); if (useDefaultColumnsMap) { mColumnsMap = new ColumnsMap(); } else { mColumnsMap = new ColumnsMap(c); } listView.setRecyclerListener(new AbsListView.RecyclerListener() { @Override public void onMovedToScrapHeap(View view) { if (view instanceof MessageListItem) { MessageListItem mli = (MessageListItem) view; // Clear references to resources mli.unbind(); } } }); } @Override public void bindView(View view, Context context, Cursor cursor) { if (view instanceof MessageListItem) { String type = cursor.getString(mColumnsMap.mColumnMsgType); long msgId = cursor.getLong(mColumnsMap.mColumnMsgId); MessageItem msgItem = getCachedMessageItem(type, msgId, cursor); if (msgItem != null) { MessageListItem mli = (MessageListItem) view; int position = cursor.getPosition(); mli.bind(msgItem, mIsGroupConversation, position); mli.setMsgListItemHandler(mMsgListItemHandler); } } } public interface OnDataSetChangedListener { void onDataSetChanged(MessageListAdapter adapter); void onContentChanged(MessageListAdapter adapter); } public void setOnDataSetChangedListener(OnDataSetChangedListener l) { mOnDataSetChangedListener = l; } public void setMsgListItemHandler(Handler handler) { mMsgListItemHandler = handler; } public void setIsGroupConversation(boolean isGroup) { mIsGroupConversation = isGroup; } public void cancelBackgroundLoading() { mMessageItemCache.evictAll(); // causes entryRemoved to be called for each MessageItem // in the cache which causes us to cancel loading of // background pdu's and images. } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); if (LOCAL_LOGV) { Log.v(TAG, "MessageListAdapter.notifyDataSetChanged()."); } mMessageItemCache.evictAll(); if (mOnDataSetChangedListener != null) { mOnDataSetChangedListener.onDataSetChanged(this); } } @Override protected void onContentChanged() { if (getCursor() != null && !getCursor().isClosed()) { if (mOnDataSetChangedListener != null) { mOnDataSetChangedListener.onContentChanged(this); } } } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { int boxType = getItemViewType(cursor); View view = mInflater.inflate((boxType == INCOMING_ITEM_TYPE_SMS || boxType == INCOMING_ITEM_TYPE_MMS) ? R.layout.message_list_item_recv : R.layout.message_list_item_send, parent, false); if (boxType == INCOMING_ITEM_TYPE_MMS || boxType == OUTGOING_ITEM_TYPE_MMS) { // We've got an mms item, pre-inflate the mms portion of the view view.findViewById(R.id.mms_layout_view_stub).setVisibility(View.VISIBLE); } return view; } public MessageItem getCachedMessageItem(String type, long msgId, Cursor c) { MessageItem item = mMessageItemCache.get(getKey(type, msgId)); if (item == null && c != null && isCursorValid(c)) { try { item = new MessageItem(mContext, type, c, mColumnsMap, mHighlight); mMessageItemCache.put(getKey(item.mType, item.mMsgId), item); } catch (MmsException e) { Log.e(TAG, "getCachedMessageItem: ", e); } } return item; } private boolean isCursorValid(Cursor cursor) { // Check whether the cursor is valid or not. if (cursor.isClosed() || cursor.isBeforeFirst() || cursor.isAfterLast()) { return false; } return true; } private static long getKey(String type, long id) { if (type.equals("mms")) { return -id; } else { return id; } } @Override public boolean areAllItemsEnabled() { return true; } /* MessageListAdapter says that it contains four types of views. Really, it just contains * a single type, a MessageListItem. Depending upon whether the message is an incoming or * outgoing message, the avatar and text and other items are laid out either left or right * justified. That works fine for everything but the message text. When views are recycled, * there's a greater than zero chance that the right-justified text on outgoing messages * will remain left-justified. The best solution at this point is to tell the adapter we've * got two different types of views. That way we won't recycle views between the two types. * @see android.widget.BaseAdapter#getViewTypeCount() */ @Override public int getViewTypeCount() { return 4; // Incoming and outgoing messages, both sms and mms } @Override public int getItemViewType(int position) { Cursor cursor = (Cursor)getItem(position); return getItemViewType(cursor); } private int getItemViewType(Cursor cursor) { String type = cursor.getString(mColumnsMap.mColumnMsgType); int boxId; if ("sms".equals(type)) { boxId = cursor.getInt(mColumnsMap.mColumnSmsType); // Note that messages from the SIM card all have a boxId of zero. return (boxId == TextBasedSmsColumns.MESSAGE_TYPE_INBOX || boxId == TextBasedSmsColumns.MESSAGE_TYPE_ALL) ? INCOMING_ITEM_TYPE_SMS : OUTGOING_ITEM_TYPE_SMS; } else { boxId = cursor.getInt(mColumnsMap.mColumnMmsMessageBox); // Note that messages from the SIM card all have a boxId of zero: Mms.MESSAGE_BOX_ALL return (boxId == Mms.MESSAGE_BOX_INBOX || boxId == Mms.MESSAGE_BOX_ALL) ? INCOMING_ITEM_TYPE_MMS : OUTGOING_ITEM_TYPE_MMS; } } public Cursor getCursorForItem(MessageItem item) { Cursor cursor = getCursor(); if (isCursorValid(cursor)) { if (cursor.moveToFirst()) { do { long id = cursor.getLong(mRowIDColumn); if (id == item.mMsgId) { return cursor; } } while (cursor.moveToNext()); } } return null; } public static class ColumnsMap { public int mColumnMsgType; public int mColumnMsgId; public int mColumnSmsAddress; public int mColumnSmsBody; public int mColumnSmsDate; public int mColumnSmsDateSent; public int mColumnSmsRead; public int mColumnSmsType; public int mColumnSmsStatus; public int mColumnSmsLocked; public int mColumnSmsErrorCode; public int mColumnMmsSubject; public int mColumnMmsSubjectCharset; public int mColumnMmsDate; public int mColumnMmsDateSent; public int mColumnMmsRead; public int mColumnMmsMessageType; public int mColumnMmsMessageBox; public int mColumnMmsDeliveryReport; public int mColumnMmsReadReport; public int mColumnMmsErrorType; public int mColumnMmsLocked; public int mColumnMmsStatus; + public int mColumnMmsTextOnly; public ColumnsMap() { mColumnMsgType = COLUMN_MSG_TYPE; mColumnMsgId = COLUMN_ID; mColumnSmsAddress = COLUMN_SMS_ADDRESS; mColumnSmsBody = COLUMN_SMS_BODY; mColumnSmsDate = COLUMN_SMS_DATE; mColumnSmsDateSent = COLUMN_SMS_DATE_SENT; mColumnSmsType = COLUMN_SMS_TYPE; mColumnSmsStatus = COLUMN_SMS_STATUS; mColumnSmsLocked = COLUMN_SMS_LOCKED; mColumnSmsErrorCode = COLUMN_SMS_ERROR_CODE; mColumnMmsSubject = COLUMN_MMS_SUBJECT; mColumnMmsSubjectCharset = COLUMN_MMS_SUBJECT_CHARSET; mColumnMmsMessageType = COLUMN_MMS_MESSAGE_TYPE; mColumnMmsMessageBox = COLUMN_MMS_MESSAGE_BOX; mColumnMmsDeliveryReport = COLUMN_MMS_DELIVERY_REPORT; mColumnMmsReadReport = COLUMN_MMS_READ_REPORT; mColumnMmsErrorType = COLUMN_MMS_ERROR_TYPE; mColumnMmsLocked = COLUMN_MMS_LOCKED; mColumnMmsStatus = COLUMN_MMS_STATUS; + mColumnMmsTextOnly = COLUMN_MMS_TEXT_ONLY; } public ColumnsMap(Cursor cursor) { // Ignore all 'not found' exceptions since the custom columns // may be just a subset of the default columns. try { mColumnMsgType = cursor.getColumnIndexOrThrow( MmsSms.TYPE_DISCRIMINATOR_COLUMN); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnMsgId = cursor.getColumnIndexOrThrow(BaseColumns._ID); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnSmsAddress = cursor.getColumnIndexOrThrow(Sms.ADDRESS); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnSmsBody = cursor.getColumnIndexOrThrow(Sms.BODY); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnSmsDate = cursor.getColumnIndexOrThrow(Sms.DATE); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnSmsDateSent = cursor.getColumnIndexOrThrow(Sms.DATE_SENT); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnSmsType = cursor.getColumnIndexOrThrow(Sms.TYPE); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnSmsStatus = cursor.getColumnIndexOrThrow(Sms.STATUS); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnSmsLocked = cursor.getColumnIndexOrThrow(Sms.LOCKED); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnSmsErrorCode = cursor.getColumnIndexOrThrow(Sms.ERROR_CODE); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnMmsSubject = cursor.getColumnIndexOrThrow(Mms.SUBJECT); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnMmsSubjectCharset = cursor.getColumnIndexOrThrow(Mms.SUBJECT_CHARSET); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnMmsMessageType = cursor.getColumnIndexOrThrow(Mms.MESSAGE_TYPE); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnMmsMessageBox = cursor.getColumnIndexOrThrow(Mms.MESSAGE_BOX); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnMmsDeliveryReport = cursor.getColumnIndexOrThrow(Mms.DELIVERY_REPORT); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnMmsReadReport = cursor.getColumnIndexOrThrow(Mms.READ_REPORT); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnMmsErrorType = cursor.getColumnIndexOrThrow(PendingMessages.ERROR_TYPE); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnMmsLocked = cursor.getColumnIndexOrThrow(Mms.LOCKED); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } try { mColumnMmsStatus = cursor.getColumnIndexOrThrow(Mms.STATUS); } catch (IllegalArgumentException e) { Log.w("colsMap", e.getMessage()); } + + try { + mColumnMmsTextOnly = cursor.getColumnIndexOrThrow(Mms.TEXT_ONLY); + } catch (IllegalArgumentException e) { + Log.w("colsMap", e.getMessage()); + } } } private static class MessageItemCache extends LruCache<Long, MessageItem> { public MessageItemCache(int maxSize) { super(maxSize); } @Override protected void entryRemoved(boolean evicted, Long key, MessageItem oldValue, MessageItem newValue) { oldValue.cancelPduLoading(); } } }
false
false
null
null
diff --git a/contrib/alpha/GenericDict2.java b/contrib/alpha/GenericDict2.java index e3655e8..8d9c6fd 100644 --- a/contrib/alpha/GenericDict2.java +++ b/contrib/alpha/GenericDict2.java @@ -1,375 +1,375 @@ import uk.co.uwcs.choob.*; import uk.co.uwcs.choob.modules.*; import uk.co.uwcs.choob.support.*; import uk.co.uwcs.choob.support.events.*; import java.util.*; import java.util.regex.*; import java.text.*; import java.io.*; import java.net.*; public class GenericDict2 { private IRCInterface irc; private Modules mods; public GenericDict2(Modules mods, IRCInterface irc) { this.mods = mods; this.irc = irc; } - private final String c_style_quoted_string = "\"((?:\\\\.|[^\"\\\\])+)\""; + private final String c_style_quoted_string = "\"((?:\\\\.|[^\"\\\\])*)\""; private final String replace_all_statement = "\\.replaceAll\\(" + c_style_quoted_string + "\\s*,\\s*" + c_style_quoted_string + "\\)"; private final String[] genericDictLongHelp = { "parameters may be specified in any order ", "Options: --url <urlparams> --match <patterns> --output <outputstring> --options <options>", "<urlparams> is a list of strings to be concatenated into a URL which will be used for scraping. Enclose sections to preserve spaces in with ` backticks ", "<patterns> is a list of patterns to match sections of the website to scrape, with variable names to assign the contents to, eg <a>%VARNAME%</a> would assign the section in the a tag to %VARNAME%", "<outputstring> is what the command will output, insert the variable data scraped with <patterns> as appropriate", "in the outputstring you may use '%VARNAME%.replaceAll(pattern,string)' to alter the variable contents and 'if ( SOMESTR == ASTR ) { FOO } ' to make selections about what to output", "Example: genericdict --url http://example.com/ ` $1 $2 ` /somemoreurl/ ` $3 ` /endurl --match <a>%SOMEVAR%</a> lalala%BADGERS%lalala --output if ( $1 == example ) { Somevar is %SOMEVAR%. } Here be badgers %BADGERS%.replaceAll(\"Badgers\",\"Ponies\")" }; public void commandGetHelp(Message mes) { irc.sendContextMessage(mes,genericDictLongHelp); } public String[] helpCommandGenericDict = { "A Stupidly complex command to scrape text from a website, use genericdict2.gethelp for detailed usage." }; public void commandGenericDict(Message mes) { try { String message = " " + mods.util.getParamString(mes); URL url = getURL(getParams(message,"url",true)); HashMap<String,String> matchers = new HashMap<String,String>(); HashMap<String,String> values = new HashMap<String,String>(); final String patternsError = "Your patterns must contain a variable to assign result to"; try { for (String regex : getParams(message,"match",true)) { String[] split = regex.split("%.*?%"); matchers.put(getVarName(regex),"(?s)" + split[0] + "(.*?)" + split[1]); } } catch (ArrayIndexOutOfBoundsException e) { throw new GenericDictException(patternsError); } catch (StringIndexOutOfBoundsException e) { throw new GenericDictException(patternsError); } for (String key : matchers.keySet()) { Matcher ma; try { ma = mods.scrape.getMatcher(url, GetContentsCached.DEFAULT_TIMEOUT, matchers.get(key)); } catch (IOException e) { throw new GenericDictException("Error reading from specified site"); } if (ma.find()) { values.put(key,ma.group(1)); } } String toReturn = formatOutputString(getParams(message,"output",true),values); toReturn = mods.scrape.readyForIrc(toReturn) + " "; boolean appendURL = false; for (String opt : getParams(message,"options",false)) if (opt.equals("appendurl")) appendURL = true; int maxLength = -1; for (String opt : getParams(message,"limit",false)) { try { maxLength = Integer.parseInt(opt); } catch (NumberFormatException e) {} } if ((maxLength > 0) && (toReturn.length() > maxLength)) { toReturn = toReturn.substring(0,maxLength) + "..."; } if ((toReturn.length() == 0) || toReturn.matches("^(\\s|\\t|\\r)*$")) throw new GenericDictException("No results found"); if (!appendURL) irc.sendContextReply(mes,toReturn); else irc.sendContextReply(mes,toReturn + url.toString()); } catch (GenericDictException e) { irc.sendContextReply(mes,e.getMessage()); } } private URL getURL(ArrayList<String> urlParts) throws GenericDictException { String urlString = ""; boolean skipwhitespace = true; URL url = null; try { for (String urlPart : urlParts) if (urlPart.equals("`")) { skipwhitespace = !skipwhitespace; if (skipwhitespace) urlString = urlString.replaceFirst("\\+$",""); } else { if (skipwhitespace) urlString = urlString + urlPart; else urlString = urlString + URLEncoder.encode(urlPart + " ","UTF-8"); } url = new URL(urlString); } catch (MalformedURLException e) { throw new GenericDictException("Malformed URL"); } catch (UnsupportedEncodingException e) { throw new GenericDictException("Unsupported Encoding"); } return url; } private ArrayList<String> getParams(String message,String option, boolean required) throws GenericDictException { int index = message.indexOf(" --" + option + " "); if (index == -1) { if (required) throw new GenericDictException("No parameters found for required option: " + option); else return new ArrayList<String>(); } try { String optionStr = message.substring(index + option.length() + 4).replaceFirst("\\s--\\w.*",""); return new ArrayList<String>(Arrays.asList(optionStr.split("\\s"))); } catch (StringIndexOutOfBoundsException e) { throw new GenericDictException("Error reading parameters for " + option); } } private String getVarName(String str) throws GenericDictException { try { String toReturn = str.substring(str.indexOf("%") + 1); return toReturn.substring(0,toReturn.indexOf("%")); } catch (StringIndexOutOfBoundsException e) { throw new GenericDictException("Unable to find variable name, syntax for variables is %variablename%"); } } /** Delegate to formatOutputString without a list as the first param */ private String formatOutputString(List<String> unformatted, Map<String, String> varValues) throws GenericDictException { StringBuilder sb = new StringBuilder(); for (String s : unformatted) sb.append(s).append(" "); return formatOutputString(sb.toString(), varValues); } /** Format an --output string. * @param unformatted List of words (split(" ")) in the output string. * @param varVaules Values of the %THINGS%. * @return The block of text to be processed before sending to irc. */ private String formatOutputString(String unformatted, Map<String, String> varValues) throws GenericDictException { final String varPattern = "%\\w*?%"; final String varReplacePattern = varPattern + "(" + replace_all_statement + ")"; String toReturn = ""; String tmp = unformatted; Matcher p; final Pattern vrp = Pattern.compile(varReplacePattern); // While we can find a varReplacePattern in the string. while ((p = vrp.matcher(tmp)).find()) { // Run the sane matcher to get the arguments. Matcher moo = Pattern.compile(replace_all_statement).matcher(p.group(1)); if (!moo.find()) throw new GenericDictException("syntax of replaceAll is %variable%.replaceAll(\"regex\",\"replacement\")"); // Grab and check the args. final String toReplace = moo.group(1); final String theReplacement = moo.group(2); assert toReplace != null; assert theReplacement != null; System.out.println("toReplace" + toReplace); System.out.println("theReplacement" + theReplacement); // Do the replacement. try { tmp = tmp.replaceFirst(varReplacePattern, varValues.get(getVarName(tmp)).replaceAll(toReplace,theReplacement)); } // (eew) The item didn't exist, so remove it and the statement. catch (NullPointerException e) { tmp = tmp.replaceFirst(varReplacePattern, ""); } } // Remove anything that wasn't replaceAll'd to it's value. while (tmp.matches(".*?" + varPattern + ".*")) { try { tmp = tmp.replaceFirst(varPattern,varValues.get(getVarName(tmp))); } catch (NullPointerException e) { tmp = tmp.replaceFirst(varPattern,""); } } toReturn = toReturn + tmp + " "; toReturn = stripUndesirables(formatConditionals(toReturn)); if (toReturn.length() == 0) throw new GenericDictException("You must specify something to output"); return toReturn; } private String stripUnquotedWhiteSpace(String toStrip) { String toReturn = ""; boolean skip = true; for (int i = 0 ; i < toStrip.length(); i++) { char chr = toStrip.charAt(i); if (chr != ' ') { if (chr == '"') skip = !skip; else toReturn = toReturn + Character.toString(chr); } else if (!skip) { toReturn = toReturn + Character.toString(chr); } } return toReturn; } private String formatConditionals(String unformatted) throws GenericDictException { String toReturn = unformatted.replaceAll("\n",""); final String conditional = "(\\s|^)if\\s*?\\((.*?)\\)\\s*?\\{(.*?)\\}"; Matcher conditionalPattern = Pattern.compile(".*?" + conditional + ".*",Pattern.CASE_INSENSITIVE).matcher(toReturn); while (conditionalPattern.matches()) { if (doComparison(conditionalPattern.group(2))) toReturn = toReturn.replaceFirst(conditional," " + conditionalPattern.group(3)); else toReturn = toReturn.replaceFirst(conditional,""); conditionalPattern = Pattern.compile(".*?" + conditional + ".*",Pattern.CASE_INSENSITIVE).matcher(toReturn); } return toReturn; } private boolean doComparison(String comparison) throws GenericDictException { int orIndex = comparison.indexOf("||"); int andIndex = comparison.indexOf("&&"); if (orIndex != -1) { return (doComparison(comparison.substring(0,orIndex)) || doComparison(comparison.substring(orIndex + 2,comparison.length()))); } if (andIndex != -1) { return (doComparison(comparison.substring(0,andIndex)) || doComparison(comparison.substring(andIndex + 2,comparison.length() ))); } String stripped = stripUnquotedWhiteSpace(comparison); final String syntax = "Conditionals must be in the form : 'if ( string <operator> string )"; if (stripped.indexOf("==") != -1) { String[] split = ("'" + stripped + "'").split("=="); if (split.length != 2) throw new GenericDictException(syntax); return ((split[0] + "'").equals("'" + split[1])); } else if (stripped.indexOf("!=") != -1) { String[] split = ("'" + stripped + "'").split("!="); if (split.length != 2) throw new GenericDictException(syntax); return !((split[0] + "'").equals("'" + split[1])); } else if (stripped.indexOf(">") != -1) { String[] split = ("'" + stripped + "'").split(""); if (split.length != 2) throw new GenericDictException(syntax); return (((split[0] + "'").compareTo("'" + split[1])) > 0); } else if (stripped.indexOf("<") != -1) { String[] split = ("'" + stripped + "'").split("<"); if (split.length != 2) throw new GenericDictException(syntax); return (((split[0] + "'").compareTo("'" + split[1])) < 0); } throw new GenericDictException(syntax); } private String stripUndesirables(String original) { String toReturn = original; int x = 0; while (toReturn.matches(".*\\s\\s.*") && x < 100) { toReturn = toReturn.replaceAll("\\s\\s"," "); x++; } toReturn = toReturn.replaceAll("\t","").replaceAll("\r","").replaceAll("\n"," "); return toReturn; } } class GenericDictException extends Exception { public GenericDictException(String message) { super(message); } }
true
false
null
null
diff --git a/editor-common/editor-common-client/src/main/java/cz/mzk/editor/client/util/ClientUtils.java b/editor-common/editor-common-client/src/main/java/cz/mzk/editor/client/util/ClientUtils.java index 19341928..65284711 100644 --- a/editor-common/editor-common-client/src/main/java/cz/mzk/editor/client/util/ClientUtils.java +++ b/editor-common/editor-common-client/src/main/java/cz/mzk/editor/client/util/ClientUtils.java @@ -1,646 +1,646 @@ /* * Metadata Editor * @author Jiri Kremser * * * * Metadata Editor - Rich internet application for editing metadata. * Copyright (C) 2011 Jiri Kremser (kremser@mzk.cz) * Moravian Library in Brno * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * */ package cz.mzk.editor.client.util; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.regexp.shared.RegExp; import com.google.gwt.regexp.shared.SplitResult; import com.google.gwt.user.client.DOM; import com.smartgwt.client.data.Record; import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.tree.Tree; import com.smartgwt.client.widgets.tree.TreeNode; import cz.mzk.editor.client.CreateObjectException; import cz.mzk.editor.client.mods.StringPlusAuthorityClient; import cz.mzk.editor.client.mods.StringPlusAuthorityPlusTypeClient; import cz.mzk.editor.client.view.other.RecentlyModifiedRecord; import cz.mzk.editor.client.view.other.ScanRecord; import cz.mzk.editor.client.view.other.SubstructureTreeNode; import cz.mzk.editor.shared.domain.DigitalObjectModel; import cz.mzk.editor.shared.rpc.MetadataBundle; import cz.mzk.editor.shared.rpc.NewDigitalObject; import cz.mzk.editor.shared.rpc.RecentlyModifiedItem; import cz.mzk.editor.shared.rpc.TreeStructureBundle.TreeStructureNode; /** * @author Jiri Kremser */ public class ClientUtils { /** * <p> * Converts a String to a boolean (optimised for performance). * </p> * <p> * <code>'true'</code>, <code>'on'</code> or <code>'yes'</code> (case * insensitive) will return <code>true</code>. Otherwise, <code>false</code> * is returned. * </p> * <p> * This method performs 4 times faster (JDK1.4) than * <code>Boolean.valueOf(String)</code>. However, this method accepts 'on' * and 'yes' as true values. * * <pre> * BooleanUtils.toBoolean(null) = false * BooleanUtils.toBoolean("true") = true * BooleanUtils.toBoolean("TRUE") = true * BooleanUtils.toBoolean("tRUe") = true * BooleanUtils.toBoolean("on") = true * BooleanUtils.toBoolean("yes") = true * BooleanUtils.toBoolean("false") = false * BooleanUtils.toBoolean("x gti") = false * </pre> * * @param str * the String to check * @return the boolean value of the string, <code>false</code> if no match */ public static boolean toBoolean(String str) { // Previously used equalsIgnoreCase, which was fast for interned 'true'. // Non interned 'true' matched 15 times slower. // // Optimisation provides same performance as before for interned 'true'. // Similar performance for null, 'false', and other strings not length // 2/3/4. // 'true'/'TRUE' match 4 times slower, 'tRUE'/'True' 7 times slower. if (str == "true") { return true; } if (str == null) { return false; } switch (str.length()) { case 2: { char ch0 = str.charAt(0); char ch1 = str.charAt(1); return (ch0 == 'o' || ch0 == 'O') && (ch1 == 'n' || ch1 == 'N'); } case 3: { char ch = str.charAt(0); if (ch == 'y') { return (str.charAt(1) == 'e' || str.charAt(1) == 'E') && (str.charAt(2) == 's' || str.charAt(2) == 'S'); } if (ch == 'Y') { return (str.charAt(1) == 'E' || str.charAt(1) == 'e') && (str.charAt(2) == 'S' || str.charAt(2) == 's'); } return false; } case 4: { char ch = str.charAt(0); if (ch == 't') { return (str.charAt(1) == 'r' || str.charAt(1) == 'R') && (str.charAt(2) == 'u' || str.charAt(2) == 'U') && (str.charAt(3) == 'e' || str.charAt(3) == 'E'); } if (ch == 'T') { return (str.charAt(1) == 'R' || str.charAt(1) == 'r') && (str.charAt(2) == 'U' || str.charAt(2) == 'u') && (str.charAt(3) == 'E' || str.charAt(3) == 'e'); } } } return false; } /** * To record. * * @param item * the item * @return the recently modified record */ public static RecentlyModifiedRecord toRecord(RecentlyModifiedItem item) { return new RecentlyModifiedRecord(item.getUuid(), item.getName(), item.getDescription(), item.getModel()); } /** * Escape html. * * @param maybeHtml * the maybe html * @return the string */ public static String escapeHtml(String maybeHtml) { final com.google.gwt.user.client.Element div = DOM.createDiv(); DOM.setInnerText(div, maybeHtml); return DOM.getInnerHTML(div); } /** * To list of list of strings. * * @param frequency * the frequency * @return the list */ public static List<List<String>> toListOfListOfStrings(List<StringPlusAuthorityClient> frequency) { if (frequency == null) return null; List<List<String>> outerList = new ArrayList<List<String>>(frequency.size()); for (StringPlusAuthorityClient value : frequency) { if (value == null) continue; List<String> innerList = new ArrayList<String>(2); innerList.add(value.getValue()); innerList.add(value.getAuthority()); outerList.add(innerList); } return outerList; } /** * To list of list of strings. * * @param toConvert * the to convert * @param something * the something * @return the list */ public static List<List<String>> toListOfListOfStrings(List<StringPlusAuthorityPlusTypeClient> toConvert, boolean something) { if (toConvert == null) return null; List<List<String>> outerList = new ArrayList<List<String>>(toConvert.size()); for (StringPlusAuthorityPlusTypeClient value : toConvert) { if (value == null) continue; List<String> innerList = new ArrayList<String>(2); innerList.add(value.getValue()); innerList.add(value.getType()); innerList.add(value.getAuthority()); outerList.add(innerList); } return outerList; } /** * Subtract. * * @param whole * the whole * @param part * the part * @return the list grid record[] */ public static ListGridRecord[] subtract(ListGridRecord[] whole, ListGridRecord[] part) { if (whole == null || whole.length == 0) return null; if (part == null || part.length == 0) return whole; List<ListGridRecord> list = new ArrayList<ListGridRecord>(); for (ListGridRecord record : whole) { boolean add = true; for (ListGridRecord counterpart : part) { if (record == counterpart) { add = false; } } if (add) list.add(record); } return list.toArray(new ListGridRecord[] {}); } public static NewDigitalObject createTheStructure(MetadataBundle bundle, Tree tree, boolean visible) throws CreateObjectException { Map<String, NewDigitalObject> processedPages = new HashMap<String, NewDigitalObject>(); TreeNode root = tree.findById(SubstructureTreeNode.ROOT_OBJECT_ID); if (root == null || tree.getChildren(root).length == 0) { return null; } String name = root.getAttribute(Constants.ATTR_NAME); if (name == null || "".equals(name)) { throw new CreateObjectException("unknown name"); } TreeNode[] children = tree.getChildren(root); if (children.length == 0) { return new NewDigitalObject(name); } String modelString = root.getAttribute(Constants.ATTR_MODEL_ID); if (modelString == null || "".equals(modelString)) { throw new CreateObjectException("unknown type"); } DigitalObjectModel model = null; try { model = DigitalObjectModel.parseString(modelString); } catch (RuntimeException ex) { throw new CreateObjectException("unknown type"); } boolean exists = root.getAttributeAsBoolean(Constants.ATTR_EXIST); NewDigitalObject newObj = new NewDigitalObject(0, name, model, bundle, exists ? name : null, exists); newObj.setVisible(visible); createChildrenStructure(tree, root, bundle, visible, processedPages, newObj); return newObj; } private static void createChildrenStructure(Tree tree, TreeNode node, MetadataBundle bundle, boolean visible, Map<String, NewDigitalObject> processedPages, NewDigitalObject newObj) throws CreateObjectException { TreeNode[] children = tree.getChildren(node); int childrenLastPageIndex = -1; List<TreeNode> folders = new ArrayList<TreeNode>(); for (TreeNode child : children) { if (child.getAttribute(tree.getIsFolderProperty()) == null) { NewDigitalObject newChild = createTheStructure(bundle, tree, child, visible, childrenLastPageIndex, processedPages); newObj.getChildren().add(newChild); childrenLastPageIndex = newChild.getPageIndex(); } else { folders.add(child); } } for (TreeNode folder : folders) { NewDigitalObject newChild = createTheStructure(bundle, tree, folder, visible, childrenLastPageIndex, processedPages); newObj.getChildren().add(newChild); childrenLastPageIndex = newChild.getPageIndex(); } } private static NewDigitalObject createTheStructure(MetadataBundle bundle, Tree tree, TreeNode node, boolean visible, int lastPageIndex, Map<String, NewDigitalObject> processedPages) throws CreateObjectException { String modelString = node.getAttribute(Constants.ATTR_MODEL_ID); if (modelString == null || "".equals(modelString)) { throw new CreateObjectException("unknown type"); } DigitalObjectModel model = null; try { model = DigitalObjectModel.parseString(modelString); } catch (RuntimeException ex) { throw new CreateObjectException("unknown type"); } String imgUuid = node.getAttribute(Constants.ATTR_PICTURE_OR_UUID); if (!processedPages.containsKey(imgUuid)) { int pageIndex = -1; if (model == DigitalObjectModel.PAGE) { if (imgUuid == null || "".equals(imgUuid)) { throw new CreateObjectException("unknown uuid"); } if (lastPageIndex < 0) { lastPageIndex = 0; } pageIndex = ++lastPageIndex; } String name = node.getAttribute(Constants.ATTR_NAME); if (name == null || "".equals(name)) { if (model != DigitalObjectModel.PAGE) { name = node.getAttribute(Constants.ATTR_PART_NUMBER_OR_ALTO); } if (name == null || "".equals(name)) { throw new CreateObjectException("unknown name"); } } Boolean exists = node.getAttributeAsBoolean(Constants.ATTR_EXIST); NewDigitalObject newObj = new NewDigitalObject(pageIndex, name, model, bundle, null, exists); newObj.setVisible(visible); String dateOrIntPartName = node.getAttribute(Constants.ATTR_DATE_OR_INT_PART_NAME); if (dateOrIntPartName != null && !"".equals(dateOrIntPartName)) { newObj.setDateOrIntPartName(dateOrIntPartName); } String noteOrIntSubtitle = node.getAttribute(Constants.ATTR_NOTE_OR_INT_SUBTITLE); if (noteOrIntSubtitle != null && !"".equals(noteOrIntSubtitle)) { newObj.setNoteOrIntSubtitle(noteOrIntSubtitle); } String type = node.getAttribute(Constants.ATTR_TYPE); if (type != null && !"".equals(type)) { if (model == DigitalObjectModel.INTERNALPART) newObj.setType(Constants.PERIODICAL_ITEM_GENRE_TYPES.MAP.get(type)); newObj.setType(node.getAttribute(Constants.ATTR_TYPE)); } String partNumberOrAlto = node.getAttribute(Constants.ATTR_PART_NUMBER_OR_ALTO); if (partNumberOrAlto != null && !"".equals(partNumberOrAlto)) { newObj.setPartNumberOrAlto(partNumberOrAlto); } if (exists) { if (imgUuid != null && !"".equals(imgUuid)) { newObj.setUuid(imgUuid.startsWith("uuid:") ? imgUuid.substring("uuid:".length()) : imgUuid); } else { throw new CreateObjectException("unknown uuid of an existing object"); } } String aditionalInfoOrOcr = node.getAttribute(Constants.ATTR_ADITIONAL_INFO_OR_OCR); if (aditionalInfoOrOcr != null && !"".equals(aditionalInfoOrOcr)) { newObj.setAditionalInfoOrOcr(aditionalInfoOrOcr); } newObj.setPath(imgUuid); createChildrenStructure(tree, node, bundle, visible, processedPages, newObj); if (model == DigitalObjectModel.PAGE) { processedPages.put(imgUuid, newObj); } return newObj; } else { return new NewDigitalObject(processedPages.get(imgUuid)); } } public static String toStringTree(NewDigitalObject node) { final StringBuilder buffer = new StringBuilder(); return toStringTreeHelper(node, buffer, new LinkedList<Iterator<NewDigitalObject>>()).toString(); } private static String toStringTreeDrawLines(List<Iterator<NewDigitalObject>> parentIterators, boolean amLast) { StringBuilder result = new StringBuilder(); Iterator<Iterator<NewDigitalObject>> it = parentIterators.iterator(); while (it.hasNext()) { Iterator<NewDigitalObject> anIt = it.next(); if (anIt.hasNext() || (!it.hasNext() && amLast)) { result.append(" |"); } else { result.append(" "); } } return result.toString(); } private static StringBuilder toStringTreeHelper(NewDigitalObject node, StringBuilder buffer, List<Iterator<NewDigitalObject>> parentIterators) { if (!parentIterators.isEmpty()) { boolean amLast = !parentIterators.get(parentIterators.size() - 1).hasNext(); buffer.append("\n"); String lines = toStringTreeDrawLines(parentIterators, amLast); buffer.append(lines); buffer.append("\n"); buffer.append(lines); buffer.append("- "); } buffer.append(node.toString()); if (node.getChildren() != null && node.getChildren().size() > 0) { Iterator<NewDigitalObject> it = node.getChildren().iterator(); parentIterators.add(it); while (it.hasNext()) { NewDigitalObject child = it.next(); toStringTreeHelper(child, buffer, parentIterators); } parentIterators.remove(it); } return buffer; } private static final String[] RCODE_1 = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; private static final String[] RCODE_2 = {"M", "DCCCC", "D", "CCCC", "C", "LXXXX", "L", "XXXX", "X", "VIIII", "V", "IIII", "I"}; private static final int[] BVAL = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; public static String decimalToRoman(int binary, boolean oldFashion) { if (binary <= 0 || binary >= 4000) { throw new NumberFormatException("Value outside roman numeral range."); } String roman = ""; // Loop from biggest value to smallest, successively subtracting, // from the binary value while adding to the roman representation. for (int i = 0; i < RCODE_1.length; i++) { while (binary >= BVAL[i]) { binary -= BVAL[i]; roman += oldFashion ? RCODE_2[i] : RCODE_1[i]; } } return roman; } public static int romanToDecimal(String roman) { int number = 0; String romanSubstring = roman; for (int i = 0; i < RCODE_1.length && !"".equals(romanSubstring); i++) { if (romanSubstring.startsWith(RCODE_1[i])) { number += BVAL[i]; romanSubstring = romanSubstring.substring(RCODE_1[i].length()); i--; } } for (int i = 0; i < RCODE_2.length && !"".equals(romanSubstring); i++) { if (romanSubstring.startsWith(RCODE_2[i])) { number += BVAL[i]; romanSubstring = romanSubstring.substring(RCODE_2[i].length()); i--; } } if ("".equals(romanSubstring)) return number; return Integer.MIN_VALUE; } /** * String.format is not accessible on the gwt client-side * * @param format * @param args * @return formatted string */ public static String format(final String format, final char escapeCharacter, final Object... args) { final RegExp regex = RegExp.compile("%" + escapeCharacter); final SplitResult split = regex.split(format); final StringBuffer msg = new StringBuffer(); for (int pos = 0; pos < split.length() - 1; pos += 1) { msg.append(split.get(pos)); msg.append(args[pos].toString()); } msg.append(split.get(split.length() - 1)); return msg.toString(); } public static class SimpleDateFormat { private DateTimeFormat format; public SimpleDateFormat() { super(); } protected SimpleDateFormat(DateTimeFormat format) { this.format = format; } public SimpleDateFormat(String pattern) { applyPattern(pattern); } public void applyPattern(String pattern) { this.format = DateTimeFormat.getFormat(pattern); } public String format(Date date) { return format.format(date); } /** * Parses text and returns the corresponding date object. */ public Date parse(String source) { return format.parse(source); } } public static List<TreeStructureNode> toNodes(Record[] records) { List<TreeStructureNode> retList = new ArrayList<TreeStructureNode>(); for (int i = 0; i < records.length; i++) { TreeStructureNode node = toNode(records[i]); if (node != null) { retList.add(node); } else { return null; } } return retList; } private static TreeStructureNode toNode(Record treeNode) { String modelId = treeNode.getAttribute(Constants.ATTR_MODEL_ID); String attrId = modelId == null ? null : treeNode.getAttribute(Constants.ATTR_ID); - if (!attrId.equals(SubstructureTreeNode.ROOT_ID)) { + if (attrId == null || !attrId.equals(SubstructureTreeNode.ROOT_ID)) { return new TreeStructureNode(attrId, treeNode.getAttribute(Constants.ATTR_PARENT), trimLabel(treeNode.getAttribute(Constants.ATTR_NAME), 255), treeNode.getAttribute(Constants.ATTR_PICTURE_OR_UUID), modelId == null ? treeNode.getAttribute(Constants.ATTR_MODEL) : modelId, treeNode.getAttribute(Constants.ATTR_TYPE), modelId == null ? treeNode.getAttribute(Constants.ATTR_ID) : treeNode .getAttribute(Constants.ATTR_DATE_OR_INT_PART_NAME), treeNode.getAttribute(Constants.ATTR_NOTE_OR_INT_SUBTITLE), treeNode.getAttribute(Constants.ATTR_PART_NUMBER_OR_ALTO), treeNode.getAttribute(Constants.ATTR_ADITIONAL_INFO_OR_OCR), treeNode.getAttributeAsBoolean(Constants.ATTR_EXIST)); } return null; } public static ScanRecord toScanRecord(TreeStructureNode node) { ScanRecord rec = new ScanRecord(node.getPropName(), node.getPropModelId(), node.getPropPictureOrUuid(), node.getPropType()); rec.setAttribute(Constants.ATTR_ADITIONAL_INFO_OR_OCR, node.getPropAditionalInfoOrOcr()); return rec; } public static SubstructureTreeNode toTreeNode(TreeStructureNode node) { SubstructureTreeNode subNode = new SubstructureTreeNode(node.getPropId(), node.getPropParent(), node.getPropName(), node.getPropPictureOrUuid(), node.getPropModelId(), node.getPropType(), node.getPropDateOrIntPartName(), node.getPropNoteOrIntSubtitle(), node.getPropPartNumberOrAlto(), node.getPropAditionalInfoOrOcr(), true, toBoolean(node.getPropName())); return subNode; } public static String recordsToString(Record[] records) { if (records == null || records.length == 0) { return ""; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < records.length; i++) { sb.append(" "); String fyzNum = String.valueOf(i + 1); for (int j = fyzNum.length(); j < 3; j++) { sb.append(' '); } sb.append(fyzNum); sb.append(records[i].getAttribute(Constants.ATTR_TYPE)); sb.append(" -- "); sb.append(records[i].getAttribute(Constants.ATTR_NAME)); sb.append("\n"); } return sb.toString(); } public static String trimLabel(String originalString, int maxLength) { if (originalString == null) return ""; if (originalString.length() <= maxLength) { return originalString; } else { return originalString.substring(0, maxLength - Constants.OVER_MAX_LENGTH_SUFFIX.length()) + Constants.OVER_MAX_LENGTH_SUFFIX; } } /** * Redirect. * * @param url * the url */ public static native void redirect(String url)/*-{ $wnd.location = url; }-*/; }
true
false
null
null
diff --git a/src/org/opensolaris/opengrok/index/IndexDatabase.java b/src/org/opensolaris/opengrok/index/IndexDatabase.java index 6d74d2a..9015c8a 100644 --- a/src/org/opensolaris/opengrok/index/IndexDatabase.java +++ b/src/org/opensolaris/opengrok/index/IndexDatabase.java @@ -1,821 +1,821 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution 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.txt. * 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 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ package org.opensolaris.opengrok.index; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.lucene.document.DateTools; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermEnum; import org.apache.lucene.search.spell.LuceneDictionary; import org.apache.lucene.search.spell.SpellChecker; import org.apache.lucene.store.FSDirectory; import org.opensolaris.opengrok.analysis.AnalyzerGuru; import org.opensolaris.opengrok.analysis.FileAnalyzer; import org.opensolaris.opengrok.analysis.FileAnalyzer.Genre; import org.opensolaris.opengrok.configuration.Project; import org.opensolaris.opengrok.configuration.RuntimeEnvironment; import org.opensolaris.opengrok.history.HistoryGuru; import org.opensolaris.opengrok.web.Util; /** * This class is used to create / update the index databases. Currently we use * one index database per project. * * @author Trond Norbye */ public class IndexDatabase { private Project project; private FSDirectory indexDirectory; private FSDirectory spellDirectory; private IndexWriter writer; private TermEnum uidIter; private IgnoredNames ignoredNames; private AnalyzerGuru analyzerGuru; private File xrefDir; private boolean interrupted; private List<IndexChangedListener> listeners; private File dirtyFile; private final Object lock = new Object(); private boolean dirty; private boolean running; private List<String> directories; private static final Logger log = Logger.getLogger(IndexDatabase.class.getName()); /** * Create a new instance of the Index Database. Use this constructor if * you don't use any projects * * @throws java.io.IOException if an error occurs while creating directories */ public IndexDatabase() throws IOException { initialize(); } /** * Create a new instance of an Index Database for a given project * @param project the project to create the database for * @throws java.io.IOException if an errror occurs while creating directories */ public IndexDatabase(Project project) throws IOException { this.project = project; initialize(); } /** * Update the index database for all of the projects. Print progress to * standard out. * @param executor An executor to run the job * @throws IOException if an error occurs */ public static void updateAll(ExecutorService executor) throws IOException { updateAll(executor, null); } /** * Update the index database for all of the projects * @param executor An executor to run the job * @param listener where to signal the changes to the database * @throws IOException if an error occurs */ static void updateAll(ExecutorService executor, IndexChangedListener listener) throws IOException { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); List<IndexDatabase> dbs = new ArrayList<IndexDatabase>(); if (env.hasProjects()) { for (Project project : env.getProjects()) { dbs.add(new IndexDatabase(project)); } } else { dbs.add(new IndexDatabase()); } for (IndexDatabase d : dbs) { final IndexDatabase db = d; if (listener != null) { db.addIndexChangedListener(listener); } executor.submit(new Runnable() { public void run() { try { db.update(); } catch (Exception e) { log.log(Level.FINE,"Problem updating lucene index database: ",e); } } }); } } @SuppressWarnings("PMD.CollapsibleIfStatements") private void initialize() throws IOException { synchronized (this) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); File indexDir = new File(env.getDataRootFile(), "index"); File spellDir = new File(env.getDataRootFile(), "spellIndex"); if (project != null) { indexDir = new File(indexDir, project.getPath()); spellDir = new File(spellDir, project.getPath()); } if (!indexDir.exists() && !indexDir.mkdirs()) { // to avoid race conditions, just recheck.. if (!indexDir.exists()) { throw new FileNotFoundException("Failed to create root directory [" + indexDir.getAbsolutePath() + "]"); } } if (!spellDir.exists() && !spellDir.mkdirs()) { if (!spellDir.exists()) { throw new FileNotFoundException("Failed to create root directory [" + spellDir.getAbsolutePath() + "]"); } } if (!env.isUsingLuceneLocking()) { FSDirectory.setDisableLocks(true); } indexDirectory = FSDirectory.getDirectory(indexDir); spellDirectory = FSDirectory.getDirectory(spellDir); ignoredNames = env.getIgnoredNames(); analyzerGuru = new AnalyzerGuru(); if (env.isGenerateHtml()) { xrefDir = new File(env.getDataRootFile(), "xref"); } listeners = new ArrayList<IndexChangedListener>(); dirtyFile = new File(indexDir, "dirty"); dirty = dirtyFile.exists(); directories = new ArrayList<String>(); } } /** * By default the indexer will traverse all directories in the project. * If you add directories with this function update will just process * the specified directories. * * @param dir The directory to scan * @return <code>true</code> if the file is added, false oth */ @SuppressWarnings("PMD.UseStringBufferForStringAppends") public boolean addDirectory(String dir) { String directory = dir; if (directory.startsWith("\\")) { directory = directory.replace('\\', '/'); } else if (directory.charAt(0) != '/') { directory = "/" + directory; } File file = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), directory); if (file.exists()) { directories.add(directory); return true; } else { return false; } } /** * Update the content of this index database * @throws IOException if an error occurs */ public void update() throws IOException { synchronized (lock) { if (running) { throw new IOException("Indexer already running!"); } running = true; interrupted = false; } try { writer = new IndexWriter(indexDirectory, AnalyzerGuru.getAnalyzer()); writer.setMaxFieldLength(RuntimeEnvironment.getInstance().getIndexWordLimit()); if (directories.isEmpty()) { if (project == null) { directories.add(""); } else { directories.add(project.getPath()); } } for (String dir : directories) { File sourceRoot; if ("".equals(dir)) { sourceRoot = RuntimeEnvironment.getInstance().getSourceRootFile(); } else { sourceRoot = new File(RuntimeEnvironment.getInstance().getSourceRootFile(), dir); } String startuid = Util.uid(dir, ""); IndexReader reader = IndexReader.open(indexDirectory); // open existing index try { uidIter = reader.terms(new Term("u", startuid)); // init uid iterator indexDown(sourceRoot, dir); while (uidIter.term() != null && uidIter.term().field().equals("u") && uidIter.term().text().startsWith(startuid)) { removeFile(); uidIter.next(); } } finally { reader.close(); } } } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { log.log(Level.WARNING, "An error occured while closing writer", e); } } synchronized (lock) { running = false; } } if (!isInterrupted() && isDirty()) { if (RuntimeEnvironment.getInstance().isOptimizeDatabase()) { optimize(); } createSpellingSuggestions(); } } /** * Optimize all index databases * @param executor An executor to run the job * @throws IOException if an error occurs */ static void optimizeAll(ExecutorService executor) throws IOException { List<IndexDatabase> dbs = new ArrayList<IndexDatabase>(); RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (env.hasProjects()) { for (Project project : env.getProjects()) { dbs.add(new IndexDatabase(project)); } } else { dbs.add(new IndexDatabase()); } for (IndexDatabase d : dbs) { final IndexDatabase db = d; if (db.isDirty()) { executor.submit(new Runnable() { public void run() { try { db.update(); } catch (IOException e) { log.log(Level.FINE,"Problem updating lucene index database: ",e); } } }); } } } /** * Optimize the index database */ public void optimize() { synchronized (lock) { if (running) { log.warning("Optimize terminated... Someone else is updating / optimizing it!"); return ; } running = true; } IndexWriter wrt = null; try { if (RuntimeEnvironment.getInstance().isVerbose()) { log.info("Optimizing the index ... "); } wrt = new IndexWriter(indexDirectory, null, false); wrt.optimize(); if (RuntimeEnvironment.getInstance().isVerbose()) { log.info("done"); } synchronized (lock) { if (dirtyFile.exists() && !dirtyFile.delete()) { log.fine("Failed to remove \"dirty-file\": " + dirtyFile.getAbsolutePath()); } dirty = false; } } catch (IOException e) { log.severe("ERROR: optimizing index: " + e); } finally { if (wrt != null) { try { wrt.close(); } catch (IOException e) { log.log(Level.WARNING, "An error occured while closing writer", e); } } synchronized (lock) { running = false; } } } /** * Generate a spelling suggestion for the definitions stored in defs */ public void createSpellingSuggestions() { IndexReader indexReader = null; SpellChecker checker = null; try { if (RuntimeEnvironment.getInstance().isVerbose()) { log.info("Generating spelling suggestion index ... "); } indexReader = IndexReader.open(indexDirectory); checker = new SpellChecker(spellDirectory); checker.indexDictionary(new LuceneDictionary(indexReader, "defs")); if (RuntimeEnvironment.getInstance().isVerbose()) { log.info("done"); } } catch (IOException e) { log.severe("ERROR: Generating spelling: " + e); } finally { if (indexReader != null) { try { indexReader.close(); } catch (IOException e) { log.log(Level.WARNING, "An error occured while closing reader", e); } } if (spellDirectory != null) { spellDirectory.close(); } } } private boolean isDirty() { synchronized (lock) { return dirty; } } private void setDirty() { synchronized (lock) { try { if (!dirty && !dirtyFile.createNewFile()) { if (!dirtyFile.exists()) { log.log(Level.FINE, "Failed to create \"dirty-file\": ", dirtyFile.getAbsolutePath()); } dirty = true; } } catch (IOException e) { log.log(Level.FINE,"When creating dirty file: ",e); } } } /** * Remove a stale file (uidIter.term().text()) from the index database * (and the xref file) * @throws java.io.IOException if an error occurs */ private void removeFile() throws IOException { String path = Util.uid2url(uidIter.term().text()); for (IndexChangedListener listener : listeners) { listener.fileRemoved(path); } writer.deleteDocuments(uidIter.term()); File xrefFile; if (RuntimeEnvironment.getInstance().isCompressXref()) { xrefFile = new File(xrefDir, path + ".gz"); } else { xrefFile = new File(xrefDir, path); } File parent = xrefFile.getParentFile(); - if (!xrefFile.delete()) { + if (!xrefFile.delete() && xrefFile.exists()) { log.info("Failed to remove obsolete xref-file: " + xrefFile.getAbsolutePath()); } // Remove the parent directory if it's empty if (parent.delete()) { log.fine("Removed empty xref dir:" + parent.getAbsolutePath()); } setDirty(); } /** * Add a file to the Lucene index (and generate a xref file) * @param file The file to add * @param path The path to the file (from source root) * @throws java.io.IOException if an error occurs */ private void addFile(File file, String path) throws IOException { final InputStream in = new BufferedInputStream(new FileInputStream(file)); try { FileAnalyzer fa = AnalyzerGuru.getAnalyzer(in, path); Document d = analyzerGuru.getDocument(file, in, path, fa); if (d == null) { log.warning("Warning: did not add " + path); } else { writer.addDocument(d, fa); Genre g = fa.getFactory().getGenre(); if (xrefDir != null && (g == Genre.PLAIN || g == Genre.XREFABLE)) { File xrefFile = new File(xrefDir, path); // If mkdirs() returns false, the failure is most likely // because the file already exists. But to check for the // file first and only add it if it doesn't exists would // only increase the file IO... if (!xrefFile.getParentFile().mkdirs()) { assert xrefFile.getParentFile().exists(); } fa.writeXref(xrefDir, path); } setDirty(); for (IndexChangedListener listener : listeners) { listener.fileAdded(path, fa.getClass().getSimpleName()); } } } finally { in.close(); } } /** * Check if I should accept this file into the index database * @param file the file to check * @return true if the file should be included, false otherwise */ private boolean accept(File file) { if (ignoredNames.ignore(file)) { return false; } if (!file.canRead()) { log.warning("Warning: could not read " + file.getAbsolutePath()); return false; } try { if (!file.getAbsolutePath().equals(file.getCanonicalPath())) { if (file.getParentFile().equals(file.getCanonicalFile().getParentFile())) { // Lets support symlinks within the same directory, this // should probably be extended to within the same repository return true; } else { log.warning("Warning: ignored non-local symlink " + file.getAbsolutePath() + " -> " + file.getCanonicalPath()); return false; } } } catch (IOException exp) { log.warning("Warning: Failed to resolve name: " + file.getAbsolutePath()); log.log(Level.FINE,"Stack Trace: ",exp); } if (file.isDirectory()) { // always accept directories so that their files can be examined return true; } if (HistoryGuru.getInstance().hasHistory(file)) { // versioned files should always be accepted return true; } // this is an unversioned file, check if it should be indexed return !RuntimeEnvironment.getInstance().isIndexVersionedFilesOnly(); } /** * Generate indexes recursively * @param dir the root indexDirectory to generate indexes for * @param path the path */ private void indexDown(File dir, String parent) throws IOException { if (isInterrupted()) { return; } if (!accept(dir)) { return; } File[] files = dir.listFiles(); if (files == null) { log.severe("Failed to get file listing for: " + dir.getAbsolutePath()); return; } Arrays.sort(files, new Comparator<File>() { public int compare(File p1, File p2) { return p1.getName().compareTo(p2.getName()); } }); for (File file : files) { if (accept(file)) { String path = parent + '/' + file.getName(); if (file.isDirectory()) { indexDown(file, path); } else { if (uidIter != null) { String uid = Util.uid(path, DateTools.timeToString(file.lastModified(), DateTools.Resolution.MILLISECOND)); // construct uid for doc while (uidIter.term() != null && uidIter.term().field().equals("u") && uidIter.term().text().compareTo(uid) < 0) { removeFile(); uidIter.next(); } if (uidIter.term() != null && uidIter.term().field().equals("u") && uidIter.term().text().compareTo(uid) == 0) { uidIter.next(); // keep matching docs continue; } } try { addFile(file, path); } catch (Exception e) { log.log(Level.WARNING, "Failed to add file " + file.getAbsolutePath(), e); } } } } } /** * Interrupt the index generation (and the index generation will stop as * soon as possible) */ public void interrupt() { synchronized (lock) { interrupted = true; } } private boolean isInterrupted() { synchronized (lock) { return interrupted; } } /** * Register an object to receive events when modifications is done to the * index database. * * @param listener the object to receive the events */ public void addIndexChangedListener(IndexChangedListener listener) { listeners.add(listener); } /** * Remove an object from the lists of objects to receive events when * modifications is done to the index database * * @param listener the object to remove */ public void removeIndexChangedListener(IndexChangedListener listener) { listeners.remove(listener); } /** * List all files in all of the index databases * @throws IOException if an error occurs */ public static void listAllFiles() throws IOException { listAllFiles(null); } /** * List all files in some of the index databases * @param subFiles Subdirectories for the various projects to list the files * for (or null or an empty list to dump all projects) * @throws IOException if an error occurs */ public static void listAllFiles(List<String> subFiles) throws IOException { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (env.hasProjects()) { if (subFiles == null || subFiles.isEmpty()) { for (Project project : env.getProjects()) { IndexDatabase db = new IndexDatabase(project); db.listFiles(); } } else { for (String path : subFiles) { Project project = Project.getProject(path); if (project == null) { log.warning("Warning: Could not find a project for \"" + path + "\""); } else { IndexDatabase db = new IndexDatabase(project); db.listFiles(); } } } } else { IndexDatabase db = new IndexDatabase(); db.listFiles(); } } /** * List all of the files in this index database * * @throws IOException If an IO error occurs while reading from the database */ public void listFiles() throws IOException { IndexReader ireader = null; TermEnum iter = null; try { ireader = IndexReader.open(indexDirectory); // open existing index iter = ireader.terms(new Term("u", "")); // init uid iterator while (iter.term() != null) { log.info(Util.uid2url(iter.term().text())); iter.next(); } } finally { if (iter != null) { try { iter.close(); } catch (IOException e) { log.log(Level.WARNING, "An error occured while closing index iterator", e); } } if (ireader != null) { try { ireader.close(); } catch (IOException e) { log.log(Level.WARNING, "An error occured while closing index reader", e); } } } } static void listFrequentTokens() throws IOException { listFrequentTokens(null); } static void listFrequentTokens(List<String> subFiles) throws IOException { final int limit = 4; RuntimeEnvironment env = RuntimeEnvironment.getInstance(); if (env.hasProjects()) { if (subFiles == null || subFiles.isEmpty()) { for (Project project : env.getProjects()) { IndexDatabase db = new IndexDatabase(project); db.listTokens(4); } } else { for (String path : subFiles) { Project project = Project.getProject(path); if (project == null) { log.warning("Warning: Could not find a project for \"" + path + "\""); } else { IndexDatabase db = new IndexDatabase(project); db.listTokens(4); } } } } else { IndexDatabase db = new IndexDatabase(); db.listTokens(limit); } } public void listTokens(int freq) throws IOException { IndexReader ireader = null; TermEnum iter = null; try { ireader = IndexReader.open(indexDirectory); iter = ireader.terms(new Term("defs", "")); while (iter.term() != null) { if (iter.term().field().startsWith("f")) { if (iter.docFreq() > 16 && iter.term().text().length() > freq) { log.warning(iter.term().text()); } iter.next(); } else { break; } } } finally { if (iter != null) { try { iter.close(); } catch (IOException e) { log.log(Level.WARNING, "An error occured while closing index iterator", e); } } if (ireader != null) { try { ireader.close(); } catch (IOException e) { log.log(Level.WARNING, "An error occured while closing index reader", e); } } } } /** * Get an indexReader for the Index database where a given file * @param path the file to get the database for * @return The index database where the file should be located or null if * it cannot be located. */ public static IndexReader getIndexReader(String path) { IndexReader ret = null; RuntimeEnvironment env = RuntimeEnvironment.getInstance(); File indexDir = new File(env.getDataRootFile(), "index"); if (env.hasProjects()) { Project p = Project.getProject(path); if (p == null) { return null; } else { indexDir = new File(indexDir, p.getPath()); } } if (indexDir.exists() && IndexReader.indexExists(indexDir)) { try { ret = IndexReader.open(indexDir); } catch (Exception ex) { log.severe("Failed to open index: " + indexDir.getAbsolutePath()); log.log(Level.FINE,"Stack Trace: ",ex); } } return ret; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final IndexDatabase other = (IndexDatabase) obj; if (this.project != other.project && (this.project == null || !this.project.equals(other.project))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 41 * hash + (this.project == null ? 0 : this.project.hashCode()); return hash; } }
true
false
null
null
diff --git a/cat-home/src/main/java/com/dianping/cat/report/page/model/transaction/HdfsTransactionService.java b/cat-home/src/main/java/com/dianping/cat/report/page/model/transaction/HdfsTransactionService.java index a9f86dc3..dfce5a86 100644 --- a/cat-home/src/main/java/com/dianping/cat/report/page/model/transaction/HdfsTransactionService.java +++ b/cat-home/src/main/java/com/dianping/cat/report/page/model/transaction/HdfsTransactionService.java @@ -1,56 +1,56 @@ package com.dianping.cat.report.page.model.transaction; import java.util.Date; import com.dianping.cat.consumer.transaction.model.entity.TransactionReport; import com.dianping.cat.consumer.transaction.model.transform.DefaultXmlParser; import com.dianping.cat.message.spi.MessagePathBuilder; import com.dianping.cat.report.page.model.spi.ModelRequest; import com.dianping.cat.report.page.model.spi.ModelResponse; import com.dianping.cat.report.page.model.spi.ModelService; import com.dianping.cat.storage.Bucket; import com.dianping.cat.storage.BucketManager; import com.site.lookup.annotation.Inject; public class HdfsTransactionService implements ModelService<TransactionReport> { @Inject private BucketManager m_bucketManager; @Inject private MessagePathBuilder m_pathBuilder; @Override public ModelResponse<TransactionReport> invoke(ModelRequest request) { String domain = request.getDomain(); long date = Long.parseLong(request.getProperty("date")); String path = m_pathBuilder.getReportPath(new Date(date)); ModelResponse<TransactionReport> response = new ModelResponse<TransactionReport>(); Bucket<byte[]> bucket = null; try { bucket = m_bucketManager.getHdfsBucket(path); byte[] data = bucket.findById("transaction-" + domain); - if (data == null) { + if (data != null) { String xml = new String(data, "utf-8"); TransactionReport report = new DefaultXmlParser().parse(xml); response.setModel(report); } } catch (Exception e) { response.setException(e); } finally { if (bucket != null) { m_bucketManager.closeBucket(bucket); } } return response; } @Override public boolean isEligable(ModelRequest request) { return request.getPeriod().isHistorical(); } }
true
true
public ModelResponse<TransactionReport> invoke(ModelRequest request) { String domain = request.getDomain(); long date = Long.parseLong(request.getProperty("date")); String path = m_pathBuilder.getReportPath(new Date(date)); ModelResponse<TransactionReport> response = new ModelResponse<TransactionReport>(); Bucket<byte[]> bucket = null; try { bucket = m_bucketManager.getHdfsBucket(path); byte[] data = bucket.findById("transaction-" + domain); if (data == null) { String xml = new String(data, "utf-8"); TransactionReport report = new DefaultXmlParser().parse(xml); response.setModel(report); } } catch (Exception e) { response.setException(e); } finally { if (bucket != null) { m_bucketManager.closeBucket(bucket); } } return response; }
public ModelResponse<TransactionReport> invoke(ModelRequest request) { String domain = request.getDomain(); long date = Long.parseLong(request.getProperty("date")); String path = m_pathBuilder.getReportPath(new Date(date)); ModelResponse<TransactionReport> response = new ModelResponse<TransactionReport>(); Bucket<byte[]> bucket = null; try { bucket = m_bucketManager.getHdfsBucket(path); byte[] data = bucket.findById("transaction-" + domain); if (data != null) { String xml = new String(data, "utf-8"); TransactionReport report = new DefaultXmlParser().parse(xml); response.setModel(report); } } catch (Exception e) { response.setException(e); } finally { if (bucket != null) { m_bucketManager.closeBucket(bucket); } } return response; }
diff --git a/src/edu/washington/cs/games/ktuite/pointcraft/KdTreeOfPoints.java b/src/edu/washington/cs/games/ktuite/pointcraft/KdTreeOfPoints.java index 576bcd0..52e0327 100644 --- a/src/edu/washington/cs/games/ktuite/pointcraft/KdTreeOfPoints.java +++ b/src/edu/washington/cs/games/ktuite/pointcraft/KdTreeOfPoints.java @@ -1,266 +1,270 @@ package edu.washington.cs.games.ktuite.pointcraft; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.util.ArrayList; import org.lwjgl.BufferUtils; import org.lwjgl.util.vector.Vector3f; import toxi.geom.PointOctree; import toxi.geom.Vec3D; public class KdTreeOfPoints { // stuff about the point cloud public static int num_points; public static DoubleBuffer point_positions; public static DoubleBuffer point_colors; private static PointOctree tree; public static float min_corner[] = { Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE }; public static float max_corner[] = { -1 * Float.MAX_VALUE, -1 * Float.MAX_VALUE, -1 * Float.MAX_VALUE }; public static void loadRandom() { num_points = 200; point_colors = BufferUtils.createDoubleBuffer(num_points * 3); point_positions = BufferUtils.createDoubleBuffer(num_points * 3); for (int i = 0; i < num_points; i++) { for (int k = 0; k < 3; k++) { point_colors.put(i * 3 + k, Math.random()); point_positions.put(i * 3 + k, Math.random() * 0.01 - 0.005); } } } public static void load(String filename) { try { BufferedReader buf = new BufferedReader(new FileReader(filename)); if (buf.readLine().startsWith("ply")) { parsePlyFile(buf, filename); buildLookupTree(); } } catch (Exception e) { e.printStackTrace(); } } public static int queryKdTree(float x, float y, float z, float radius) { ArrayList<Vec3D> results = tree.getPointsWithinSphere( new Vec3D(x, y, z), radius); if (results != null) return results.size(); else return 0; } public static Vector3f getCenter(float x, float y, float z, float radius) { Vector3f center = new Vector3f(); ArrayList<Vec3D> results = tree.getPointsWithinSphere( new Vec3D(x, y, z), radius); if (results != null) { for (Vec3D p : results) { center.x += p.x; center.y += p.y; center.z += p.z; } center.scale(1f / results.size()); return center; } else { return null; } } private static void buildLookupTree() { System.out.println("starting to build lookup tree"); Vec3D center = new Vec3D(min_corner[0], min_corner[1], min_corner[2]); float max_span = max_corner[0] - min_corner[0]; if (max_corner[1] - min_corner[1] > max_span) max_span = max_corner[1] - min_corner[1]; if (max_corner[2] - min_corner[2] > max_span) max_span = max_corner[2] - min_corner[2]; tree = new PointOctree(center, max_span); tree.setMinNodeSize(max_span / 5); for (int i = 0; i < num_points; i++) { tree.addPoint(new Vec3D((float) point_positions.get(i * 3 + 0), (float) point_positions.get(i * 3 + 1), (float) point_positions.get(i * 3 + 2))); } System.out.println("done adding " + tree.getPoints().size() + " points to lookup tree"); } private static void parsePlyFile(BufferedReader buf, String filename) { try { int r_idx, g_idx, b_idx; int x_idx, y_idx, z_idx; r_idx = g_idx = b_idx = x_idx = y_idx = z_idx = 0; boolean binary = false; int chars_read = 0; int count = 0; String line = buf.readLine(); chars_read += (line.length() + 1); while (!line.startsWith("end_header")) { if (line.startsWith("element vertex")) { num_points = Integer.parseInt(line.split("\\s+")[2]); count = 0; } if (line.contains("binary_little_endian")) { binary = true; } if (line.contains(" x")) x_idx = count; else if (line.contains(" y")) y_idx = count; else if (line.contains(" z")) z_idx = count; else if (line.contains("red")) r_idx = count; else if (line.contains("green")) g_idx = count; else if (line.contains("blue")) b_idx = count; if (line.contains("property")) count++; line = buf.readLine(); chars_read += (line.length() + 1); } chars_read += 4; System.out.println(x_idx + "," + y_idx + "," + z_idx + " " + r_idx + "," + g_idx + "," + b_idx); point_colors = BufferUtils.createDoubleBuffer(num_points * 3); point_positions = BufferUtils.createDoubleBuffer(num_points * 3); point_colors.rewind(); point_positions.rewind(); if (!binary) { int i = 0; line = buf.readLine(); while (line != null) { String[] split_line = line.split("\\s+"); point_colors .put(Integer.parseInt(split_line[r_idx]) / 255.0); point_colors .put(Integer.parseInt(split_line[g_idx]) / 255.0); point_colors .put(Integer.parseInt(split_line[b_idx]) / 255.0); point_positions.put(Double.parseDouble(split_line[x_idx])); point_positions.put(Double.parseDouble(split_line[y_idx])); point_positions.put(Double.parseDouble(split_line[z_idx])); for (int k = 0; k < 3; k++) { if (point_positions.get(i * 3 + k) < min_corner[k]) { min_corner[k] = (float) point_positions.get(i * 3 + k); } if (point_positions.get(i * 3 + k) > max_corner[k]) { max_corner[k] = (float) point_positions.get(i * 3 + k); } } line = buf.readLine(); i++; if (i % 10000 == 0) System.out.println("points loaded: " + i + "/" + num_points); } } else { // advance the binary thing forward past the ascii DataInputStream stream = new DataInputStream( new FileInputStream(filename)); byte[] header = new byte[chars_read]; stream.read(header, 0, chars_read); int len = count * 4 - 9; byte[] pt = new byte[len]; ByteBuffer bb = BufferUtils.createByteBuffer(len); bb.order(ByteOrder.LITTLE_ENDIAN); System.out.println("reading " + count + " values with " + len + " bytes"); for (int h = 0; h < num_points; h++) { stream.read(pt, 0, len); bb.rewind(); bb.put(pt, 0, len); bb.rewind(); - int r = 0, g = 0, b = 0; + byte r = 0, g = 0, b = 0; double x = 0, y = 0, z = 0; for (int i = 0; i < count; i++) { if (i == r_idx) { r = bb.get(); // System.out.print(r + ", "); } else if (i == g_idx) { g = bb.get(); // System.out.print(g + ", "); } else if (i == b_idx) { b = bb.get(); // System.out.print(b + ", "); } else if (i == x_idx) { x = bb.getFloat(); } else if (i == y_idx) { y = bb.getFloat(); } else if (i == z_idx) { z = bb.getFloat(); } else { float f = bb.getFloat(); // System.out.print(f + ", "); } } // System.out.println(""); + point_colors.put(r / 255.0); point_colors.put(g / 255.0); point_colors.put(b / 255.0); point_positions.put(x); point_positions.put(y); point_positions.put(z); for (int k = 0; k < 3; k++) { if (point_positions.get(h * 3 + k) < min_corner[k]) { min_corner[k] = (float) point_positions.get(h * 3 + k); } if (point_positions.get(h * 3 + k) > max_corner[k]) { max_corner[k] = (float) point_positions.get(h * 3 + k); } } - if (h % 10000 == 0) + if (h % 10000 == 0){ System.out.println("points loaded: " + h + "/" + num_points); + + + } } } point_colors.rewind(); point_positions.rewind(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } diff --git a/src/edu/washington/cs/games/ktuite/pointcraft/Main.java b/src/edu/washington/cs/games/ktuite/pointcraft/Main.java index 824b3f0..b66b582 100644 --- a/src/edu/washington/cs/games/ktuite/pointcraft/Main.java +++ b/src/edu/washington/cs/games/ktuite/pointcraft/Main.java @@ -1,1296 +1,1302 @@ package edu.washington.cs.games.ktuite.pointcraft; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.util.glu.GLU.*; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.Stack; import org.lwjgl.BufferUtils; import org.lwjgl.LWJGLException; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.*; import org.lwjgl.util.Timer; import org.lwjgl.util.vector.Vector2f; import org.lwjgl.util.vector.Vector3f; import org.newdawn.slick.Color; import org.newdawn.slick.openal.Audio; import org.newdawn.slick.openal.AudioLoader; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureLoader; import org.newdawn.slick.util.ResourceLoader; import de.matthiasmann.twl.GUI; import de.matthiasmann.twl.renderer.lwjgl.LWJGLRenderer; import de.matthiasmann.twl.theme.ThemeManager; public class Main { // stuff about the atmosphere private float FOG_COLOR[] = new float[] { .89f, .89f, .89f, 1.0f }; public static Audio launch_effect; public static Audio attach_effect; // stuff about the display private static float point_size = 2; private static float fog_density = 5; // stuff about the world and how you move around public static float world_scale = 1f; private Vector3f pos; private Vector3f vel; private float tilt_angle; private float pan_angle; private float veldecay = .90f; private static float walkforce = 1 / 4000f * world_scale; private double max_speed = 1 * world_scale; private Texture skybox = null; // stuff about the point cloud private int num_points; private DoubleBuffer point_positions; private DoubleBuffer point_colors; // stuff about general guns and general list of pellets/things shot private Vector3f gun_direction; private float gun_speed = 0.001f * world_scale; public static float pellet_scale = 1f; public static Timer timer = new Timer(); public static Stack<Pellet> all_pellets_in_world; public static Stack<Pellet> all_dead_pellets_in_world; public static Stack<Pellet> new_pellets_to_add_to_world; // TODO: move out of here and put somewhere else since this is a certain // kind of geometry public static Stack<Primitive> geometry; public static Stack<Scaffold> geometry_v; public static boolean draw_points = true; public static boolean draw_scaffolding = true; public static boolean draw_pellets = true; public static int picked_polygon = -1; public static ServerCommunicator server; // overhead view stuff public static float last_tilt = 0; public static boolean tilt_locked = false; public static int tilt_animation = 0; public static DoubleBuffer proj_ortho; public static DoubleBuffer proj_persp; public static DoubleBuffer proj_intermediate; public float overhead_scale = 1; public enum GunMode { PELLET, ORB, LINE, VERTICAL_LINE, PLANE, ARC, CIRCLE, POLYGON, DESTRUCTOR, DOUBLE } public GunMode which_gun; private GUI onscreen_gui; private GUI instructional_gui; private OnscreenOverlay onscreen_overlay; public static void main(String[] args) { Main main = new Main(); main.InitDisplay(); main.InitGUI(); main.InitGraphics(); main.InitData(); main.InitGameVariables(); main.Start(); } private void InitDisplay() { try { Display.setDisplayMode(new DisplayMode(800, 600)); Display.setResizable(true); Display.setVSyncEnabled(true); Display.create(); Display.setTitle("PointCraft FPS-3D-Modeler"); Mouse.setGrabbed(true); } catch (LWJGLException e) { e.printStackTrace(); System.out.println("ERROR running InitDisplay... game exiting"); System.exit(1); } } @SuppressWarnings("deprecation") private void InitGUI() { LWJGLRenderer renderer; try { renderer = new LWJGLRenderer(); onscreen_overlay = new OnscreenOverlay(); onscreen_gui = new GUI(onscreen_overlay, renderer); URL url = new File("assets/theme/onscreen.xml").toURL(); ThemeManager themeManager = ThemeManager.createThemeManager(url, renderer); onscreen_gui.applyTheme(themeManager); instructional_gui = new GUI(new InstructionalOverlay(), renderer); URL url2 = new File("assets/theme/guiTheme.xml").toURL(); ThemeManager themeManager2 = ThemeManager.createThemeManager(url2, renderer); instructional_gui.applyTheme(themeManager2); } catch (LWJGLException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void InitGraphics() { float width = Display.getDisplayMode().getWidth(); float height = Display.getDisplayMode().getHeight(); System.out.println("init graphics: " + width + "," + height); // view matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1 * width / height, width / height, -1f, 1f, 0.001f, 1000.0f); // glScalef(40, 40, 40); proj_ortho = BufferUtils.createDoubleBuffer(16); glGetDouble(GL_PROJECTION_MATRIX, proj_ortho); proj_ortho.put(0, proj_ortho.get(0) * 40f); proj_ortho.put(5, proj_ortho.get(5) * 40f); glLoadIdentity(); gluPerspective(60, width / height, .001f, 1000.0f); proj_persp = BufferUtils.createDoubleBuffer(16); glGetDouble(GL_PROJECTION_MATRIX, proj_persp); proj_intermediate = BufferUtils.createDoubleBuffer(16); // glOrtho(-800.0f / 600.0f, 800.0f / 600.0f, -1f, 1f, 0.001f, 1000.0f); // gluLookAt(0, 0, 0, 0, 0, -1, 0.05343333f, 0.9966372f, -0.062121693f); glMatrixMode(GL_MODELVIEW); // fog FloatBuffer fogColorBuffer = ByteBuffer.allocateDirect(4 * 4) .order(ByteOrder.nativeOrder()).asFloatBuffer(); fogColorBuffer.put(FOG_COLOR); fogColorBuffer.rewind(); glFog(GL_FOG_COLOR, fogColorBuffer); glFogi(GL_FOG_MODE, GL_EXP2); glFogf(GL_FOG_END, 3.0f); glFogf(GL_FOG_START, .25f); glFogf(GL_FOG_DENSITY, fog_density); // getting the ordering of the points right glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_LINE_SMOOTH); // skybox texture loaded try { skybox = TextureLoader.getTexture("JPG", ResourceLoader.getResourceAsStream("assets/gray_sky.jpg")); System.out.println("Texture loaded: " + skybox); System.out.println(">> Image width: " + skybox.getImageWidth()); System.out.println(">> Image height: " + skybox.getImageHeight()); System.out.println(">> Texture width: " + skybox.getTextureWidth()); System.out.println(">> Texture height: " + skybox.getTextureHeight()); System.out.println(">> Texture ID: " + skybox.getTextureID()); } catch (IOException e) { e.printStackTrace(); System.out.println("Couldn't load skybox"); System.exit(1); } } private void InitGameVariables() { pos = new Vector3f(); vel = new Vector3f(); tilt_angle = 0; pan_angle = 0; System.out.println("Starting position: " + pos + " Starting velocity: " + vel); gun_direction = new Vector3f(); all_pellets_in_world = new Stack<Pellet>(); all_dead_pellets_in_world = new Stack<Pellet>(); new_pellets_to_add_to_world = new Stack<Pellet>(); which_gun = GunMode.POLYGON; OrbPellet.orb_pellet = new OrbPellet(all_pellets_in_world); // TODO: Move this crap elsewhere... init the different geometry // containers individually geometry = new Stack<Primitive>(); geometry_v = new Stack<Scaffold>(); geometry_v.push(LinePellet.current_line); geometry_v.push(PlanePellet.current_plane); try { launch_effect = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream("assets/launch.wav")); attach_effect = AudioLoader.getAudio("WAV", ResourceLoader.getResourceAsStream("assets/attach.wav")); } catch (IOException e) { e.printStackTrace(); System.out.println("couldn't load sounds"); System.exit(1); } server = new ServerCommunicator( "http://phci03.cs.washington.edu/pointcraft/"); } private void InitData() { KdTreeOfPoints .load("/Users/ktuite/Downloads/final_cloud-1300484491-518929104.ply"); world_scale = (float) ((float) ((KdTreeOfPoints.max_corner[1] - KdTreeOfPoints.min_corner[1])) / 0.071716); // lewis hall height for scale ref... System.out.println("world scale: " + world_scale); walkforce = 1 / 4000f * world_scale; max_speed = 1 * world_scale; gun_speed = 0.001f * world_scale; + + glFogf(GL_FOG_END, 3.0f * world_scale); + glFogf(GL_FOG_START, .25f * world_scale); + fog_density /= world_scale; + glFogf(GL_FOG_DENSITY, fog_density); + // load("assets/models/lewis-hall.ply"); num_points = KdTreeOfPoints.num_points; point_positions = KdTreeOfPoints.point_positions; point_colors = KdTreeOfPoints.point_colors; /* * // data of the point cloud itself, loaded in from C++ * * LibPointCloud // * .load("/Users/ktuite/Desktop/sketchymodeler/server_code/Uris.bin"); * .load("assets/models/lewis-hall.bin"); // * .loadBundle("/Users/ktuite/Desktop/sketchymodeler/models/lewis.bundle" * ); // .load( * "/Users/ktuite/Desktop/sketchymodeler/instances/lewis-hall/model.bin" * ); // * .load("/Users/ktuite/Desktop/sketchymodeler/server_code/Parr.bin"); * // .loadBundle( * "/Users/ktuite/Desktop/sketchymodeler/texviewer/cse/bundle.out"); // * . * load("/Users/ktuite/Desktop/sketchymodeler/server_code/SageChapel.bin" * ); // * .load("/Users/ktuite/Desktop/sketchymodeler/server_code/HOC_culdesac.bin" * ); // * .load("/Users/ktuite/Desktop/sketchymodeler/server_code/fountainplus.bin" * ); System.out.println("number of points: " + * LibPointCloud.getNumPoints()); * * num_points = LibPointCloud.getNumPoints(); point_positions = * LibPointCloud.getPointPositions() .getByteBuffer(0, num_points * 3 * * 8).asDoubleBuffer(); point_colors = LibPointCloud.getPointColors() * .getByteBuffer(0, num_points * 3 * 8).asDoubleBuffer(); * * System.out.println("first point: " + point_positions.get(0)); * System.out.println("first color: " + point_colors.get(0)); * * // FindMinMaxOfWorld(); * * LibPointCloud.makeKdTree(); */ } @SuppressWarnings("unused") private void FindMinMaxOfWorld() { float[] min_point = new float[3]; float[] max_point = new float[3]; for (int k = 0; k < 3; k++) { min_point[k] = Float.MAX_VALUE; max_point[k] = Float.MIN_VALUE; } for (int i = 0; i < num_points; i++) { for (int k = 0; k < 3; k++) { float p = (float) point_positions.get(k * num_points + i); if (p < min_point[k]) min_point[k] = p; if (p > max_point[k]) max_point[k] = p; } } world_scale = (float) (((max_point[1] - min_point[1])) / 0.071716); // lewis hall height for scale ref... System.out.println("world scale: " + world_scale); walkforce = 1 / 4000f * world_scale; max_speed = 1 * world_scale; } private void Start() { while (!Display.isCloseRequested()) { Timer.tick(); if (Mouse.isGrabbed()) { EventLoop(); // input like mouse and keyboard UpdateGameObjects(); DisplayLoop(); // draw things on the screen } else { UpdateInstructionalGui(); InstructionalEventLoop(); } if ((Display.getWidth() != Display.getDisplayMode().getWidth() || Display .getHeight() != Display.getDisplayMode().getHeight()) && Mouse.isButtonDown(0)) { dealWithDisplayResize(); } } Display.destroy(); } private void dealWithDisplayResize() { System.out.println("Display was resized... " + Display.getWidth()); try { Display.setDisplayMode(new DisplayMode(Display.getWidth(), Display .getHeight())); } catch (LWJGLException e) { System.out.println(e); } InitGUI(); InitGraphics(); } /* * private static void undoLastPellet() { if * (PolygonPellet.current_cycle.size() > 0) { * PolygonPellet.current_cycle.pop(); // all_pellets_in_world.pop(); } if * (geometry.size() > 0 && geometry.peek().isPolygon()) { Primitive * last_poly = geometry.pop(); for (int i = 0; i < last_poly.numVertices() - * 1; i++) { geometry.pop(); if (all_pellets_in_world.size() > 0) { // * all_pellets_in_world.pop(); } } PolygonPellet.current_cycle.clear(); } * else if (geometry.size() > 0) { geometry.pop(); } // TODO: horribly broke * undoing for making cycles except it wasnt that // great to begin with * * } */ private void UpdateGameObjects() { for (Pellet pellet : all_pellets_in_world) { pellet.update(); } for (Pellet pellet : new_pellets_to_add_to_world) { all_pellets_in_world.add(pellet); } new_pellets_to_add_to_world.clear(); if (which_gun == GunMode.ORB) { OrbPellet .updateOrbPellet(pos, gun_direction, pan_angle, tilt_angle); } } private void InstructionalEventLoop() { while (Keyboard.next()) { if (Keyboard.getEventKeyState()) { if (Keyboard.getEventKey() == Keyboard.KEY_ESCAPE) { Mouse.setGrabbed(!Mouse.isGrabbed()); } } } } private void EventLoop() { // WASD key motion, with a little bit of gliding if (Keyboard.isKeyDown(Keyboard.KEY_W) || Keyboard.isKeyDown(Keyboard.KEY_UP)) { vel.x += Math.sin(pan_angle * 3.14159 / 180f) * walkforce * pellet_scale; vel.z -= Math.cos(pan_angle * 3.14159 / 180f) * walkforce * pellet_scale; } if (Keyboard.isKeyDown(Keyboard.KEY_S) || Keyboard.isKeyDown(Keyboard.KEY_DOWN)) { vel.x -= Math.sin(pan_angle * 3.14159 / 180f) * walkforce * pellet_scale; vel.z += Math.cos(pan_angle * 3.14159 / 180f) * walkforce * pellet_scale; } if (Keyboard.isKeyDown(Keyboard.KEY_A) || Keyboard.isKeyDown(Keyboard.KEY_LEFT)) { vel.x -= Math.cos(pan_angle * 3.14159 / 180f) * walkforce / 2 * pellet_scale; vel.z -= Math.sin(pan_angle * 3.14159 / 180f) * walkforce / 2 * pellet_scale; } if (Keyboard.isKeyDown(Keyboard.KEY_D) || Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) { vel.x += Math.cos(pan_angle * 3.14159 / 180f) * walkforce / 2 * pellet_scale; vel.z += Math.sin(pan_angle * 3.14159 / 180f) * walkforce / 2 * pellet_scale; } if (!tilt_locked) { if (Keyboard.isKeyDown(Keyboard.KEY_E)) { vel.y += walkforce / 2 * pellet_scale; } if (Keyboard.isKeyDown(Keyboard.KEY_Q)) { vel.y -= walkforce / 2 * pellet_scale; } } else { if (Keyboard.isKeyDown(Keyboard.KEY_E)) { overhead_scale /= 1.05f; } if (Keyboard.isKeyDown(Keyboard.KEY_Q)) { overhead_scale *= 1.05f; } } // this is like putting on or taking off some stilts // (numerous pairs of stilts) // basically it increases or decreases your vertical world height while (Keyboard.next()) { if (Keyboard.getEventKeyState()) { /* * if (Keyboard.getEventKey() == Keyboard.KEY_S && * (Keyboard.isKeyDown(219) || Keyboard.isKeyDown(29))) { * Save.saveHeckaData(); } if (Keyboard.getEventKey() == * Keyboard.KEY_L) { Save.loadHeckaData(); } */ if (Keyboard.getEventKey() == Keyboard.KEY_Z && (Keyboard.isKeyDown(219) || Keyboard.isKeyDown(29))) { ActionTracker.undo(); } if (Keyboard.getEventKey() == Keyboard.KEY_ESCAPE) { Mouse.setGrabbed(!Mouse.isGrabbed()); } if (Keyboard.getEventKey() == Keyboard.KEY_P || Keyboard.getEventKey() == Keyboard.KEY_C) { draw_points = !draw_points; } if (Keyboard.getEventKey() == Keyboard.KEY_O) { draw_scaffolding = !draw_scaffolding; } if (Keyboard.getEventKey() == Keyboard.KEY_I) { draw_pellets = !draw_pellets; } if (Keyboard.getEventKey() == Keyboard.KEY_1) { which_gun = GunMode.POLYGON; System.out.println("regular pellet gun selected"); } if (Keyboard.getEventKey() == Keyboard.KEY_2) { which_gun = GunMode.PELLET; System.out.println("regular pellet gun selected"); } if (Keyboard.getEventKey() == Keyboard.KEY_3) { which_gun = GunMode.LINE; System.out.println("line fitting pellet gun selected"); } if (Keyboard.getEventKey() == Keyboard.KEY_4) { which_gun = GunMode.PLANE; System.out.println("plane fitting pellet gun selected"); } if (Keyboard.getEventKey() == Keyboard.KEY_5) { which_gun = GunMode.VERTICAL_LINE; System.out.println("vertical line pellet gun selected"); } if (Keyboard.getEventKey() == Keyboard.KEY_6) { which_gun = GunMode.DOUBLE; System.out.println("double pellet gun"); } if (Keyboard.getEventKey() == Keyboard.KEY_9) { which_gun = GunMode.ORB; System.out .println("orb gun (where you can just place pellets in space without them sticking to things) selected"); } if (Keyboard.getEventKey() == Keyboard.KEY_0) { which_gun = GunMode.DESTRUCTOR; System.out.println("the gun that deletes things"); } if (Keyboard.getEventKey() == Keyboard.KEY_T) { tilt_locked = !tilt_locked; if (tilt_locked) { last_tilt = tilt_angle; tilt_animation = 30; } else { tilt_animation = -30; } } if (Keyboard.getEventKey() == Keyboard.KEY_N) { if (which_gun == GunMode.PLANE) PlanePellet.startNewPlane(); else if (which_gun == GunMode.LINE) LinePellet.startNewLine(); else if (which_gun == GunMode.POLYGON) PolygonPellet.startNewPolygon(); else if (which_gun == GunMode.VERTICAL_LINE) VerticalLinePellet.clearAllVerticalLines(); } if (Keyboard.getEventKey() == Keyboard.KEY_EQUALS) { point_size++; if (point_size > 10) point_size = 10; } if (Keyboard.getEventKey() == Keyboard.KEY_MINUS) { point_size--; if (point_size < 1) point_size = 1; } if (Keyboard.getEventKey() == Keyboard.KEY_LBRACKET) { - fog_density -= 5; + fog_density -= 5/world_scale; if (fog_density < 0) fog_density = 0; glFogf(GL_FOG_DENSITY, fog_density); } if (Keyboard.getEventKey() == Keyboard.KEY_RBRACKET) { - fog_density += 5; - if (fog_density > 50) - fog_density = 50; + fog_density += 5/world_scale; + if (fog_density > 50/world_scale) + fog_density = 50/world_scale; glFogf(GL_FOG_DENSITY, fog_density); } if (Keyboard.getEventKey() == Keyboard.KEY_U) { WiggleTool.fixModel(); } if (Keyboard.getEventKey() == Keyboard.KEY_X) { ActionTracker.printStack(); } } } /* * if (tilt_locked && which_gun != GunMode.OVERHEAD && tilt_animation == * 0) { tilt_animation = -30; tilt_locked = true; // set to true until * done animating } */ // normalize the speed double speed = Math.sqrt(vel.length()); if (speed > 0.000001) { float ratio = (float) (Math.min(speed, max_speed) / speed); vel.scale(ratio); } // sneak / go slowly if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) vel.scale(.3f); if (tilt_locked) vel.scale(.5f); // pos += vel Vector3f.add(pos, vel, pos); // friction (let player glide to a stop) vel.scale(veldecay); // use mouse to control where player is looking if (!tilt_locked) tilt_angle -= Mouse.getDY() / 10f; if (tilt_animation != 0) animateTilt(); pan_angle += Mouse.getDX() / 10f; if (tilt_angle > 90) tilt_angle = 90; if (tilt_angle < -90) tilt_angle = -90; if (pan_angle > 360) pan_angle -= 360; if (pan_angle < -360) pan_angle += 360; while (Mouse.next()) { if (Mouse.getEventButtonState()) { if (Mouse.getEventButton() == 0) { ShootGun(); } else if (Mouse.getEventButton() == 1) { ShootDeleteGun(); } } } // use scroll wheel to change orb gun distance // so far the only gun mode that uses extra stuff to determine its state int wheel = Mouse.getDWheel(); if (which_gun == GunMode.ORB) { if (wheel < 0) { OrbPellet.orb_pellet.decreaseDistance(); } else if (wheel > 0) { OrbPellet.orb_pellet.increaseDistance(); } } else { if (wheel < 0) { pellet_scale -= .1f; if (pellet_scale <= 0) pellet_scale = 0.1f; } else if (wheel > 0) { pellet_scale += .1f; if (pellet_scale > 3) pellet_scale = 3f; } } } private void animateTilt() { glGetDouble(GL_PROJECTION_MATRIX, proj_intermediate); if (tilt_animation > 0) { // animate down tilt_angle += (90f - tilt_angle) / tilt_animation; tilt_animation--; int indices[] = { 0, 5, 11, 15 }; for (int i : indices) { double k = proj_intermediate.get(i); k = proj_persp.get(i) + (proj_ortho.get(i) - proj_persp.get(i)) * (1.0 - (float) tilt_animation / 30.0); proj_intermediate.put(i, k); } } else if (tilt_animation < 0) { // animate up tilt_angle -= (last_tilt - tilt_angle) / tilt_animation; tilt_animation++; if (tilt_animation == 0) { tilt_locked = false; Mouse.getDY(); } int indices[] = { 0, 5, 11, 15 }; for (int i : indices) { double k = proj_intermediate.get(i); k = proj_ortho.get(i) + (proj_persp.get(i) - proj_ortho.get(i)) * (1.0 + (float) tilt_animation / 30.0); proj_intermediate.put(i, k); } } glMatrixMode(GL_PROJECTION); glLoadMatrix(proj_intermediate); glMatrixMode(GL_MODELVIEW); } private void DisplayLoop() { glClearColor(FOG_COLOR[0], FOG_COLOR[1], FOG_COLOR[2], 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); glRotatef(tilt_angle, 1.0f, 0.0f, 0.0f); // rotate our camera up/down glRotatef(pan_angle, 0.0f, 1.0f, 0.0f); // rotate our camera left/right DrawSkybox(); // draw skybox before translate glScalef(overhead_scale, overhead_scale, overhead_scale); glTranslated(-pos.x, -pos.y, -pos.z); // translate the screen glEnable(GL_FOG); if (draw_points) DrawPoints(); // draw the actual 3d things if (draw_pellets) { DrawPellets(); if (which_gun == GunMode.ORB) OrbPellet.drawOrbPellet(); } for (Primitive geom : geometry) { geom.draw(); } if (draw_scaffolding) { for (Scaffold geom : geometry_v) { geom.draw(); } } glDisable(GL_FOG); glPopMatrix(); pickPolygon(); DrawHud(); UpdateOnscreenGui(); Display.update(); } private void UpdateOnscreenGui() { if (onscreen_gui != null) { onscreen_overlay.label_current_mode.setText("Current Gun: " + which_gun); onscreen_overlay.label_last_action.setText("Last Action: " + ActionTracker.showLatestAction()); onscreen_gui.update(); } } private void UpdateInstructionalGui() { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); if (instructional_gui != null) { instructional_gui.update(); } Display.update(); } private void pickPolygon() { int x = Display.getDisplayMode().getWidth() / 2; int y = Display.getDisplayMode().getHeight() / 2; final int BUFSIZE = 512; int[] selectBuf = new int[BUFSIZE]; IntBuffer selectBuffer = BufferUtils.createIntBuffer(BUFSIZE); IntBuffer viewport = BufferUtils.createIntBuffer(16); int hits; glGetInteger(GL_VIEWPORT, viewport); glSelectBuffer(selectBuffer); glRenderMode(GL_SELECT); glInitNames(); glPushName(-1); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); /* create 5x5 pixel picking region near cursor location */ gluPickMatrix((float) x, (float) (viewport.get(3) - y), 5.0f, 5.0f, viewport); gluPerspective(60, Display.getDisplayMode().getWidth() / Display.getDisplayMode().getHeight(), .001f, 1000.0f); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glRotatef(tilt_angle, 1.0f, 0.0f, 0.0f); // rotate our camera up/down glRotatef(pan_angle, 0.0f, 1.0f, 0.0f); // rotate our camera left/right glTranslated(-pos.x, -pos.y, -pos.z); // translate the screen // draw polygons for picking for (int i = 0; i < geometry.size(); i++) { Primitive g = geometry.get(i); if (g.isPolygon()) { glLoadName(i); g.draw(); } } glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glFlush(); hits = glRenderMode(GL_RENDER); selectBuffer.get(selectBuf); picked_polygon = processHits(hits, selectBuf); // which polygon actually // selected } private int processHits(int hits, int buffer[]) { int names, ptr = 0; int selected_geometry = -1; int min_dist = Integer.MAX_VALUE; // System.out.println("hits = " + hits); // ptr = (GLuint *) buffer; for (int i = 0; i < hits; i++) { /* for each hit */ names = buffer[ptr]; // System.out.println(" number of names for hit = " + names); ptr++; // System.out.println(" z1 is " + buffer[ptr]); int temp_min_dist = buffer[ptr]; ptr++; // System.out.println(" z2 is " + buffer[ptr]); ptr++; // System.out.print("\n the name is "); for (int j = 0; j < names; j++) { /* for each name */ // System.out.println("" + buffer[ptr]); if (temp_min_dist < min_dist) { min_dist = temp_min_dist; selected_geometry = buffer[ptr]; } ptr++; } // System.out.println(); } return selected_geometry; } private void DrawPoints() { /* * glPointSize(point_size); glBegin(GL_POINTS); for (int i = 0; i < * num_points; i += 1) { float r = (float) (point_colors.get(0 + 3 * * i)); float g = (float) (point_colors.get(1 + 3 * i)); float b = * (float) (point_colors.get(2 + 3 * i)); glColor3f(r, g, b); * glVertex3d(point_positions.get(0 + 3 * i), point_positions.get(1 + 3 * * i), point_positions.get(2 + 3 * i)); } glEnd(); */ glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); GL11.glVertexPointer(3, 0, point_positions); GL11.glColorPointer(3, 0, point_colors); glPointSize(point_size); glDrawArrays(GL_POINTS, 0, num_points); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); } private void DrawPellets() { // temp /* * for (LinePellet pellet : LinePellet.intersection_points) { if * (pellet.alive) { glPushMatrix(); glTranslatef(pellet.pos.x, * pellet.pos.y, pellet.pos.z); pellet.draw(); glPopMatrix(); } else { * all_dead_pellets_in_world.add(pellet); } } * * for (PlanePellet pellet : PlanePellet.intersection_points) { if * (pellet.alive) { glPushMatrix(); glTranslatef(pellet.pos.x, * pellet.pos.y, pellet.pos.z); pellet.draw(); glPopMatrix(); } else { * all_dead_pellets_in_world.add(pellet); } } */ for (Pellet pellet : all_pellets_in_world) { if (pellet.alive) { if (pellet.visible) { glPushMatrix(); glTranslatef(pellet.pos.x, pellet.pos.y, pellet.pos.z); pellet.draw(); glPopMatrix(); } } else { all_dead_pellets_in_world.add(pellet); } } for (Pellet pellet : all_dead_pellets_in_world) { all_pellets_in_world.remove(pellet); } all_dead_pellets_in_world.clear(); } private void DrawSkybox() { glEnable(GL_TEXTURE_2D); glDisable(GL_FOG); glDisable(GL_DEPTH_TEST); Color.white.bind(); skybox.bind(); glPointSize(10); float s = .1f; glBegin(GL_QUADS); // tex coords of .99 and .01 used here and there // to prevent wrap around and dark edges on light things // top glTexCoord2f(.75f, 0.01f); glVertex3f(s, s, s); glTexCoord2f(.5f, 0.01f); glVertex3f(-s, s, s); glTexCoord2f(.5f, .5f); glVertex3f(-s, s, -s); glTexCoord2f(.75f, .5f); glVertex3f(s, s, -s); // one side.... glTexCoord2f(0f, .5f); glVertex3f(s, s, s); glTexCoord2f(.25f, .5f); glVertex3f(-s, s, s); glTexCoord2f(.25f, .99f); glVertex3f(-s, -s, s); glTexCoord2f(0f, .99f); glVertex3f(s, -s, s); // two side.... glTexCoord2f(.25f, .5f); glVertex3f(-s, s, s); glVertex3f(-s, s, -s); glTexCoord2f(.5f, .99f); glVertex3f(-s, -s, -s); glTexCoord2f(.25f, .99f); glVertex3f(-s, -s, s); // red side.... (third side) glTexCoord2f(.5f, .5f); glVertex3f(-s, s, -s); glTexCoord2f(.75f, .5f); glVertex3f(s, s, -s); glTexCoord2f(.75f, .99f); glVertex3f(s, -s, -s); glTexCoord2f(.5f, .99f); glVertex3f(-s, -s, -s); // blue side.... (fourth side) glTexCoord2f(.75f, .5f); glVertex3f(s, s, -s); glTexCoord2f(1.0f, .5f); glVertex3f(s, s, s); glTexCoord2f(1.0f, .99f); glVertex3f(s, -s, s); glTexCoord2f(.75f, .99f); glVertex3f(s, -s, -s); // down side.... glTexCoord2f(.75f, .99f); glVertex3f(s, -s, s); glTexCoord2f(.75f, .99f); glVertex3f(-s, -s, s); glTexCoord2f(.75f, .99f); glVertex3f(-s, -s, -s); glTexCoord2f(.75f, .99f); glVertex3f(s, -s, -s); glEnd(); glDisable(GL_TEXTURE_2D); // glEnable(GL_FOG); glEnable(GL_DEPTH_TEST); } private void DrawHud() { glDisable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(-1, 1, 1, -1, -1, 1); glColor3f(1f, 1f, 1f); float f = (float) (0.05f * Math.sqrt(pellet_scale)); glLineWidth(2); int n = 30; switch (which_gun) { case POLYGON: int m = 5; glBegin(GL_LINE_LOOP); for (int i = 0; i < m; i++) { float angle = (float) (Math.PI * 2 * i / m); float x = (float) (Math.cos(angle) * f * 0.75 * 600 / 800); float y = (float) (Math.sin(angle) * f * 0.75); glVertex2f(x, y); } glEnd(); break; case PELLET: glBegin(GL_LINES); glVertex2f(0, f); glVertex2f(0, -f); glVertex2f(f * 600 / 800, 0); glVertex2f(-f * 600 / 800, 0); glEnd(); glBegin(GL_LINE_LOOP); for (int i = 0; i < n; i++) { float angle = (float) (Math.PI * 2 * i / n); float x = (float) (Math.cos(angle) * f * 0.75 * 600 / 800); float y = (float) (Math.sin(angle) * f * 0.75); glVertex2f(x, y); } glEnd(); break; case ORB: glBegin(GL_LINE_LOOP); for (int i = 0; i < n; i++) { float angle = (float) (Math.PI * 2 * i / n); float x = (float) (Math.cos(angle) * f * 0.75 * 600 / 800); float y = (float) (Math.sin(angle) * f * 0.75); glVertex2f(x, y); } glEnd(); glBegin(GL_LINE_LOOP); for (int i = 0; i < n; i++) { float angle = (float) (Math.PI * 2 * i / n); float x = (float) (Math.cos(angle) * f * 0.55 * 600 / 800); float y = (float) (Math.sin(angle) * f * 0.55); glVertex2f(x, y); } glEnd(); break; case PLANE: glBegin(GL_LINE_LOOP); glVertex2f(0, f); glVertex2f(f * 600 / 800, 0); glVertex2f(0, -f); glVertex2f(-f * 600 / 800, 0); glEnd(); break; case LINE: glBegin(GL_LINES); glVertex2f(f * 600 / 800, f); glVertex2f(-f * 600 / 800, -f); glVertex2f(-f * .2f * 600 / 800, f * .2f); glVertex2f(f * .2f * 600 / 800, -f * .2f); glEnd(); break; case VERTICAL_LINE: glBegin(GL_LINES); glVertex2f(0, f); glVertex2f(0, -f); glEnd(); glBegin(GL_LINE_LOOP); for (int i = 0; i < n; i++) { float angle = (float) (Math.PI * 2 * i / n); float x = (float) (Math.cos(angle) * f * 0.25 * 600 / 800); float y = (float) (Math.sin(angle) * f * 0.25); glVertex2f(x, y); } glEnd(); break; case DESTRUCTOR: glBegin(GL_LINES); glVertex2f(f * 600 / 800, f); glVertex2f(-f * 600 / 800, -f); glVertex2f(-f * 600 / 800, f); glVertex2f(f * 600 / 800, -f); glEnd(); glBegin(GL_LINE_LOOP); for (int i = 0; i < n; i++) { float angle = (float) (Math.PI * 2 * i / n); float x = (float) (Math.cos(angle) * f * 0.75 * 600 / 800); float y = (float) (Math.sin(angle) * f * 0.75); glVertex2f(x, y); } glEnd(); break; case DOUBLE: glBegin(GL_LINE_LOOP); for (int i = 0; i < n; i++) { float angle = (float) (Math.PI * 2 * i / n); float x = (float) (Math.cos(angle) * f * 0.45 * 600 / 800); float y = (float) (Math.sin(angle) * f * 0.45 + f / 2); glVertex2f(x, y); } glEnd(); glBegin(GL_LINE_LOOP); for (int i = 0; i < n; i++) { float angle = (float) (Math.PI * 2 * i / n); float x = (float) (Math.cos(angle) * f * 0.45 * 600 / 800); float y = (float) (Math.sin(angle) * f * 0.45 - f / 2); glVertex2f(x, y); } glEnd(); break; default: break; } glPopMatrix(); glMatrixMode(GL_MODELVIEW); glEnable(GL_DEPTH_TEST); } @SuppressWarnings("unused") private void ShootPelletGun() { System.out.println("shooting gun"); // do all this extra stuff with horizontal angle so that shooting up in // the air makes the pellet go up in the air Vector2f horiz = new Vector2f(); horiz.x = (float) Math.sin(pan_angle * 3.14159 / 180f); horiz.y = -1 * (float) Math.cos(pan_angle * 3.14159 / 180f); horiz.normalise(); horiz.scale((float) Math.cos(tilt_angle * 3.14159 / 180f)); gun_direction.x = horiz.x; gun_direction.z = horiz.y; gun_direction.y = -1 * (float) Math.sin(tilt_angle * 3.14159 / 180f); gun_direction.normalise(); Pellet pellet = new Pellet(all_pellets_in_world); pellet.vel.set(gun_direction); pellet.vel.scale(gun_speed); pellet.pos.set(pos); all_pellets_in_world.add(pellet); } private void ShootGun() { if (which_gun == GunMode.ORB) { OrbPellet new_pellet = new OrbPellet(all_pellets_in_world); new_pellet.pos.set(OrbPellet.orb_pellet.pos); new_pellet.constructing = true; all_pellets_in_world.add(new_pellet); System.out.println(all_pellets_in_world); } else if (which_gun != GunMode.ORB) { System.out.println("shooting gun"); computeGunDirection(); Pellet pellet = null; if (which_gun == GunMode.PELLET) { pellet = new ScaffoldPellet(all_pellets_in_world); } else if (which_gun == GunMode.PLANE) { pellet = new PlanePellet(all_pellets_in_world); } else if (which_gun == GunMode.LINE) { pellet = new LinePellet(all_pellets_in_world); } else if (which_gun == GunMode.VERTICAL_LINE) { pellet = new VerticalLinePellet(all_pellets_in_world); } else if (which_gun == GunMode.DOUBLE) { pellet = new DoublePellet(all_pellets_in_world); } else if (which_gun == GunMode.DESTRUCTOR) { pellet = new DestructorPellet(all_pellets_in_world); } else { pellet = new PolygonPellet(all_pellets_in_world); } pellet.vel.set(gun_direction); pellet.vel.scale(gun_speed); pellet.vel.scale(pellet_scale); pellet.pos.set(pos); all_pellets_in_world.add(pellet); } } private void ShootDeleteGun() { System.out.println("shooting DESTRUCTOR gun"); computeGunDirection(); Pellet pellet = new DestructorPellet(all_pellets_in_world); pellet.vel.set(gun_direction); pellet.vel.scale(gun_speed); pellet.vel.scale(pellet_scale); pellet.pos.set(pos); all_pellets_in_world.add(pellet); } private void computeGunDirection() { // do all this extra stuff with horizontal angle so that shooting up // in the air makes the pellet go up in the air Vector2f horiz = new Vector2f(); horiz.x = (float) Math.sin(pan_angle * 3.14159 / 180f); horiz.y = -1 * (float) Math.cos(pan_angle * 3.14159 / 180f); horiz.normalise(); horiz.scale((float) Math.cos(tilt_angle * 3.14159 / 180f)); gun_direction.x = horiz.x; gun_direction.z = horiz.y; gun_direction.y = -1 * (float) Math.sin(tilt_angle * 3.14159 / 180f); gun_direction.normalise(); // System.out.println("gun direction:" + gun_direction); // calculateUpVectorAdjustment(new Vector3f(gun_direction)); } @SuppressWarnings("unused") private void calculateUpVectorAdjustment(Vector3f new_up) { new_up.set(-0.05343333f, -0.9966372f, 0.062121693f); Vector3f old_up = new Vector3f(0, 1, 0); new_up.negate(); Vector3f rotation_axis = new Vector3f(); Vector3f.cross(old_up, new_up, rotation_axis); float rotation_angle = -1 * (float) Math.acos(Vector3f.dot(old_up, new_up)) * 180 / (float) Math.PI; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotatef(rotation_angle, rotation_axis.x, rotation_axis.y, rotation_axis.z); System.out.println("rotation angle: " + rotation_angle); System.out.println("rotation axis: " + rotation_axis); } /** * Set the display mode to be used * * @param width * The width of the display required * @param height * The height of the display required * @param fullscreen * True if we want fullscreen mode */ public void setDisplayMode(int width, int height, boolean fullscreen) { // return if requested DisplayMode is already set if ((Display.getDisplayMode().getWidth() == width) && (Display.getDisplayMode().getHeight() == height) && (Display.isFullscreen() == fullscreen)) { return; } try { DisplayMode targetDisplayMode = null; if (fullscreen) { DisplayMode[] modes = Display.getAvailableDisplayModes(); int freq = 0; for (int i = 0; i < modes.length; i++) { DisplayMode current = modes[i]; if ((current.getWidth() == width) && (current.getHeight() == height)) { if ((targetDisplayMode == null) || (current.getFrequency() >= freq)) { if ((targetDisplayMode == null) || (current.getBitsPerPixel() > targetDisplayMode .getBitsPerPixel())) { targetDisplayMode = current; freq = targetDisplayMode.getFrequency(); } } // if we've found a match for bpp and frequence against // the // original display mode then it's probably best to go // for this one // since it's most likely compatible with the monitor if ((current.getBitsPerPixel() == Display .getDesktopDisplayMode().getBitsPerPixel()) && (current.getFrequency() == Display .getDesktopDisplayMode().getFrequency())) { targetDisplayMode = current; break; } } } } else { targetDisplayMode = new DisplayMode(width, height); } if (targetDisplayMode == null) { System.out.println("Failed to find value mode: " + width + "x" + height + " fs=" + fullscreen); return; } Display.setDisplayMode(targetDisplayMode); Display.setFullscreen(fullscreen); } catch (LWJGLException e) { System.out.println("Unable to setup mode " + width + "x" + height + " fullscreen=" + fullscreen + e); } } }
false
false
null
null
diff --git a/src/fi/mikuz/boarder/app/BoarderService.java b/src/fi/mikuz/boarder/app/BoarderService.java new file mode 100644 index 0000000..7dd7607 --- /dev/null +++ b/src/fi/mikuz/boarder/app/BoarderService.java @@ -0,0 +1,20 @@ +package fi.mikuz.boarder.app; + +import fi.mikuz.boarder.util.GlobalSettings; +import android.app.Service; +import android.content.Intent; +import android.os.IBinder; + +public class BoarderService extends Service { + + @Override + public void onCreate() { + GlobalSettings.init(this); + } + + @Override + public IBinder onBind(Intent intent) { + return null; + } + +} diff --git a/src/fi/mikuz/boarder/service/TogglePlayPauseService.java b/src/fi/mikuz/boarder/service/TogglePlayPauseService.java index 0feaba4..86ee6d0 100644 --- a/src/fi/mikuz/boarder/service/TogglePlayPauseService.java +++ b/src/fi/mikuz/boarder/service/TogglePlayPauseService.java @@ -1,31 +1,33 @@ package fi.mikuz.boarder.service; -import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; +import fi.mikuz.boarder.app.BoarderService; import fi.mikuz.boarder.util.SoundPlayerControl; /** * * @author Jan Mikael Lindl�f */ -public class TogglePlayPauseService extends Service { +public class TogglePlayPauseService extends BoarderService { public static final String TAG = "TogglePlayPauseService"; @Override public void onCreate() { + super.onCreate(); + try { SoundPlayerControl.togglePlayPause(); } catch (NullPointerException e) { Log.w(TAG, "Boarder is not running, nothing to do", e); } this.stopSelf(); } @Override public IBinder onBind(Intent intent) { return null; } }
false
false
null
null
diff --git a/src/org/openstreetmap/josm/actions/mapmode/ExtrudeAction.java b/src/org/openstreetmap/josm/actions/mapmode/ExtrudeAction.java index 18d2b20a..07fff6a7 100644 --- a/src/org/openstreetmap/josm/actions/mapmode/ExtrudeAction.java +++ b/src/org/openstreetmap/josm/actions/mapmode/ExtrudeAction.java @@ -1,265 +1,266 @@ // License: GPL. Copyright 2007 by Immanuel Scholz and others package org.openstreetmap.josm.actions.mapmode; import static org.openstreetmap.josm.tools.I18n.marktr; import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.geom.GeneralPath; import java.util.Collection; import java.util.LinkedList; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.command.AddCommand; import org.openstreetmap.josm.command.ChangeCommand; import org.openstreetmap.josm.command.Command; import org.openstreetmap.josm.command.SequenceCommand; import org.openstreetmap.josm.data.coor.EastNorth; import org.openstreetmap.josm.data.osm.Node; import org.openstreetmap.josm.data.osm.Way; import org.openstreetmap.josm.data.osm.WaySegment; import org.openstreetmap.josm.gui.MapFrame; import org.openstreetmap.josm.gui.MapView; import org.openstreetmap.josm.gui.layer.MapViewPaintable; import org.openstreetmap.josm.tools.ImageProvider; import org.openstreetmap.josm.tools.Shortcut; /** * Makes a rectangle from a line, or modifies a rectangle. * * This class currently contains some "sleeping" code copied from DrawAction (move and rotate) * which can eventually be removed, but it may also get activated here and removed in DrawAction. */ public class ExtrudeAction extends MapMode implements MapViewPaintable { enum Mode { EXTRUDE, rotate, select } private Mode mode = null; private long mouseDownTime = 0; private WaySegment selectedSegment = null; private Color selectedColor; double xoff; double yoff; double distance; /** * The old cursor before the user pressed the mouse button. */ private Cursor oldCursor; /** * The current position of the mouse */ private Point mousePos; /** * The position of the mouse cursor when the drag action was initiated. */ private Point initialMousePos; /** * The time which needs to pass between click and release before something * counts as a move, in milliseconds */ private int initialMoveDelay = 200; /** * Create a new SelectAction * @param mapFrame The MapFrame this action belongs to. */ public ExtrudeAction(MapFrame mapFrame) { super(tr("Extrude"), "extrude/extrude", tr("Create areas"), Shortcut.registerShortcut("mapmode:extrude", tr("Mode: {0}", tr("Extrude")), KeyEvent.VK_X, Shortcut.GROUP_EDIT), mapFrame, - getCursor("normal", "selection", Cursor.DEFAULT_CURSOR)); + getCursor("normal", "rectangle", Cursor.DEFAULT_CURSOR)); putValue("help", "Action/Extrude/Extrude"); initialMoveDelay = Main.pref.getInteger("edit.initial-move-delay",200); selectedColor = Main.pref.getColor(marktr("selected"), Color.YELLOW); } private static Cursor getCursor(String name, String mod, int def) { try { return ImageProvider.getCursor(name, mod); } catch (Exception e) { } return Cursor.getPredefinedCursor(def); } private void setCursor(Cursor c) { if (oldCursor == null) { oldCursor = Main.map.mapView.getCursor(); Main.map.mapView.setCursor(c); } } private void restoreCursor() { if (oldCursor != null) { Main.map.mapView.setCursor(oldCursor); oldCursor = null; } } @Override public void enterMode() { super.enterMode(); Main.map.mapView.addMouseListener(this); Main.map.mapView.addMouseMotionListener(this); } @Override public void exitMode() { super.exitMode(); Main.map.mapView.removeMouseListener(this); Main.map.mapView.removeMouseMotionListener(this); Main.map.mapView.removeTemporaryLayer(this); } /** * If the left mouse button is pressed, move all currently selected * objects (if one of them is under the mouse) or the current one under the * mouse (which will become selected). */ @Override public void mouseDragged(MouseEvent e) { if (mode == Mode.select) return; // do not count anything as a move if it lasts less than 100 milliseconds. if ((mode == Mode.EXTRUDE) && (System.currentTimeMillis() - mouseDownTime < initialMoveDelay)) return; if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) == 0) return; if (mode == Mode.EXTRUDE) { setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); } if (mousePos == null) { mousePos = e.getPoint(); return; } Main.map.mapView.repaint(); mousePos = e.getPoint(); } public void paint(Graphics g, MapView mv) { if (selectedSegment != null) { Node n1 = selectedSegment.way.nodes.get(selectedSegment.lowerIndex); Node n2 = selectedSegment.way.nodes.get(selectedSegment.lowerIndex+1); EastNorth en1 = n1.eastNorth; EastNorth en2 = n2.eastNorth; if (en1.east() < en2.east()) { en2 = en1; en1 = n2.eastNorth; } EastNorth en3 = mv.getEastNorth(mousePos.x, mousePos.y); double u = ((en3.east()-en1.east())*(en2.east()-en1.east()) + (en3.north()-en1.north())*(en2.north()-en1.north()))/en2.distanceSq(en1); // the point on the segment from which the distance to mouse pos is shortest EastNorth base = new EastNorth(en1.east()+u*(en2.east()-en1.east()), en1.north()+u*(en2.north()-en1.north())); // the distance, in projection units, between the base point and the mouse cursor double len = base.distance(en3); // find out the distance, in metres, between the base point and the mouse cursor distance = Main.proj.eastNorth2latlon(base).greatCircleDistance(Main.proj.eastNorth2latlon(en3)); Main.map.statusLine.setDist(distance); updateStatusLine(); // compute the angle at which the segment is drawn // and use it to compute the x and y offsets for the // corner points. double sin_alpha = (en2.north()-en1.north())/en2.distance(en1); // this is a kludge because sometimes extrusion just goes the wrong direction if ((en3.east()>base.east()) ^ (sin_alpha < 0)) len=-len; xoff = sin_alpha * len; yoff = Math.sqrt(1-sin_alpha*sin_alpha) * len; Graphics2D g2 = (Graphics2D) g; g2.setColor(selectedColor); g2.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); GeneralPath b = new GeneralPath(); Point p1=mv.getPoint(en1); Point p2=mv.getPoint(en2); Point p3=mv.getPoint(en1.add(-xoff, -yoff)); Point p4=mv.getPoint(en2.add(-xoff, -yoff)); b.moveTo(p1.x,p1.y); b.lineTo(p3.x, p3.y); b.lineTo(p4.x, p4.y); b.lineTo(p2.x, p2.y); b.lineTo(p1.x,p1.y); g2.draw(b); g2.setStroke(new BasicStroke(1)); } } /** */ @Override public void mousePressed(MouseEvent e) { if (!(Boolean)this.getValue("active")) return; if (e.getButton() != MouseEvent.BUTTON1) return; // boolean ctrl = (e.getModifiers() & ActionEvent.CTRL_MASK) != 0; // boolean alt = (e.getModifiers() & ActionEvent.ALT_MASK) != 0; // boolean shift = (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0; mouseDownTime = System.currentTimeMillis(); selectedSegment = Main.map.mapView.getNearestWaySegment(e.getPoint()); mode = (selectedSegment == null) ? Mode.select : Mode.EXTRUDE; oldCursor = Main.map.mapView.getCursor(); updateStatusLine(); Main.map.mapView.addTemporaryLayer(this); Main.map.mapView.repaint(); mousePos = e.getPoint(); initialMousePos = e.getPoint(); } /** * Restore the old mouse cursor. */ @Override public void mouseReleased(MouseEvent e) { restoreCursor(); if (selectedSegment == null) return; if (mousePos.distance(initialMousePos) > 10) { Node n1 = selectedSegment.way.nodes.get(selectedSegment.lowerIndex); Node n2 = selectedSegment.way.nodes.get(selectedSegment.lowerIndex+1); EastNorth en3 = n2.eastNorth.add(-xoff, -yoff); Node n3 = new Node(Main.proj.eastNorth2latlon(en3)); EastNorth en4 = n1.eastNorth.add(-xoff, -yoff); Node n4 = new Node(Main.proj.eastNorth2latlon(en4)); Way wnew = new Way(selectedSegment.way); wnew.nodes.add(selectedSegment.lowerIndex+1, n3); wnew.nodes.add(selectedSegment.lowerIndex+1, n4); if (wnew.nodes.size() == 4) wnew.nodes.add(n1); Collection<Command> cmds = new LinkedList<Command>(); cmds.add(new AddCommand(n4)); cmds.add(new AddCommand(n3)); cmds.add(new ChangeCommand(selectedSegment.way, wnew)); Command c = new SequenceCommand(tr("Extrude Way"), cmds); Main.main.undoRedo.add(c); } Main.map.mapView.removeTemporaryLayer(this); + selectedSegment = null; mode = null; updateStatusLine(); Main.map.mapView.repaint(); } @Override public String getModeHelpText() { if (mode == Mode.select) { return tr("Release the mouse button to select the objects in the rectangle."); } else if (mode == Mode.EXTRUDE) { return tr("Draw a rectangle of the desired size, then release the mouse button."); } else if (mode == Mode.rotate) { return tr("Release the mouse button to stop rotating."); } else { return tr("Drag a way segment to make a rectangle."); } } }
false
false
null
null
diff --git a/src/android/XSecurityExt.java b/src/android/XSecurityExt.java index 8fbbf13..505ba61 100644 --- a/src/android/XSecurityExt.java +++ b/src/android/XSecurityExt.java @@ -1,366 +1,371 @@ /* Copyright 2012-2013, Polyvi Inc. (http://polyvi.github.io/openxface) This program is distributed under the terms of the GNU General Public License. This file is part of xFace. xFace 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. xFace 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 xFace. If not, see <http://www.gnu.org/licenses/>. */ package com.polyvi.xface.extension; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.polyvi.xface.exception.XCryptionException; import com.polyvi.xface.util.XBase64; import com.polyvi.xface.util.XCryptor; import com.polyvi.xface.util.XFileUtils; import com.polyvi.xface.util.XLog; import com.polyvi.xface.util.XPathResolver; import com.polyvi.xface.util.XStringUtils; import com.polyvi.xface.view.XAppWebView; public class XSecurityExt extends CordovaPlugin { private static final String CLASS_NAME = XSecurityExt.class.getSimpleName(); /** Security 提供给js用户的接口名字 */ private static final String COMMAND_ENCRYPT = "encrypt"; private static final String COMMAND_DECRYPT = "decrypt"; private static final String COMMAND_ENCRYPT_FILE = "encryptFile"; private static final String COMMAND_DECRYPT_FILE = "decryptFile"; private static final String COMMAND_DIGEST = "digest"; /** 加解密过程中的错误 */ private static final int FILE_NOT_FOUND_ERR = 1; private static final int PATH_ERR = 2; private static final int OPERATION_ERR = 3; /**加解密报错*/ private static final String KEY_EMPTY_ERROR = "Error:key null or empty"; private static final String FILE_NOT_FOUND_ERROR = "Error: file not found"; private static final String CRYPTION_ERROR = "Error:cryption error"; /**加密算法选择*/ private static final int DES_ALOGRITHEM = 1; //DES方式加解密 private static final int TRIPLE_DES_ALOGRITHEM = 2; //3DES方式加解密 private static final int RSA_ALOGRITHEM = 3; //RSA方式加解密 /**返回数据类型选择*/ private static final int ENCODE_TYPE_STRING = 0; //返回数据为String private static final int ENCODE_TYPE_BASE64 = 1; //返回的数据以Base64编码格式 private static final int ENCODE_TYPE_HEX = 2; //返回的数据以16进制编码格式 /** 加解密配置选项的属性名称 */ private static final String KEY_CRYPT_ALGORITHM = "CryptAlgorithm"; private static final String KEY_ENCODE_DATA_TYPE = "EncodeDataType"; private static final String KEY_ENCODE_KEY_TYPE = "EncodeKeyType"; /**加解密工具类*/ XCryptor mCryptor = new XCryptor(); private String getWorkspacePath(){ XAppWebView xAppWebView = (XAppWebView) webView; String appWorkspace = xAppWebView.getOwnerApp().getWorkSpace(); return appWorkspace; } /** * 对文件进行加解密时检查文件路径是否正确 * * @param appWorkspacePath 工作空间路径 * @param filename 文件名称,不带路径 * @param sourceOrTarget true,当前路径是源文件路径,false,当前路径是目标文件路径 * @return 所请求文件路径的绝对路径 * @throws FileNotFoundException */ private String getAbsoluteFilePath(String appWorkspacePath, String filename, boolean sourceOrTarget) throws FileNotFoundException{ // 检查传入文件路径是否为空 if (XStringUtils.isEmptyString(filename) ) { throw new IllegalArgumentException(); } XPathResolver pathResolver = new XPathResolver(filename, appWorkspacePath, null); String absFilePath = pathResolver.resolve(); - if((null == absFilePath) || !XFileUtils.isFileAncestorOf(appWorkspacePath, absFilePath)) { - throw new IllegalArgumentException(); + + if((null == absFilePath) ||!XFileUtils.isFileAncestorOf(appWorkspacePath, absFilePath)) { + if(sourceOrTarget){ // 加密原文件不存在应该抛出FileNotFoundException异常 + throw new FileNotFoundException(); + }else {// 加密目的文件路径有问题应该抛出IllegalArgumentException异常 + throw new IllegalArgumentException(); + } } // 对文件作路径解析和检测 File requestFile = new File(absFilePath); String absRequestFilePath = getAbsFilePath(requestFile); if(null == absRequestFilePath) { throw new IllegalArgumentException(); } - if (sourceOrTarget) { //当前文件是源文件,该文件必须存在 + if (sourceOrTarget) { //当前文件是源文件,该文件必须存在 if(!requestFile.exists()){ throw new FileNotFoundException(); } - }else { //当前文件是目的文件,该文件必须不存在 + }else { //当前文件是目的文件,该文件必须不存在 if(requestFile.exists()){ requestFile.delete(); } if (!XFileUtils.createFile(absRequestFilePath)) { throw new FileNotFoundException(); } } return absRequestFilePath; } public boolean execute(String action, JSONArray args, CallbackContext callbackCtx) throws JSONException { String result = "Unsupported Operation: " + action; try { // 检查key值 String sKey = args.getString(0); if (XStringUtils.isEmptyString(sKey)) { XLog.e(CLASS_NAME, KEY_EMPTY_ERROR); throw new XCryptionException(KEY_EMPTY_ERROR); } if (action.equals(COMMAND_ENCRYPT)) { result = encrypt(sKey, args.getString(1),args.optJSONObject(2)); } else if (action.equals(COMMAND_DECRYPT)) { result = decrypt(sKey, args.getString(1), args.optJSONObject(2)); } else if (action.equals(COMMAND_ENCRYPT_FILE)) { String appWorkSpace = getWorkspacePath(); result = encryptFile(sKey, getAbsoluteFilePath(appWorkSpace,args.getString(1), true), getAbsoluteFilePath(appWorkSpace,args.getString(2), false)); } else if (action.equals(COMMAND_DECRYPT_FILE)) { String appWorkSpace = getWorkspacePath(); result = decryptFile(sKey, getAbsoluteFilePath(appWorkSpace,args.getString(1), true), getAbsoluteFilePath(appWorkSpace,args.getString(2), false)); } else if (action.equals(COMMAND_DIGEST)) { result = digest(sKey); } else { return false; // Invalid action, return false } callbackCtx.success(result); PluginResult status = new PluginResult(PluginResult.Status.OK); callbackCtx.sendPluginResult(status); } catch (IllegalArgumentException e) { e.printStackTrace(); callbackCtx.error(PATH_ERR); return false; } catch (FileNotFoundException e) { e.printStackTrace(); XLog.e(CLASS_NAME, FILE_NOT_FOUND_ERROR, e); callbackCtx.error(FILE_NOT_FOUND_ERR); return false; } catch (XCryptionException e) { e.printStackTrace(); XLog.e(CLASS_NAME, CRYPTION_ERROR, e); callbackCtx.error(OPERATION_ERR); return false; } return true; } /** * 对称加密字节数组并返回 * * @param sKey 密钥 * @param sourceData 需要加密的数据 * @param options 加解密配置选项 * @return 经过加密的数据 */ private String encrypt(String sKey, String sourceData, JSONObject options) throws XCryptionException { int cryptAlgorithm = DES_ALOGRITHEM; int encodeDataType = ENCODE_TYPE_STRING; int encodeKeyType = ENCODE_TYPE_STRING; if (options != null) { cryptAlgorithm = options.optInt(KEY_CRYPT_ALGORITHM, DES_ALOGRITHEM); encodeDataType = options.optInt(KEY_ENCODE_DATA_TYPE, ENCODE_TYPE_BASE64); encodeKeyType = options.optInt(KEY_ENCODE_KEY_TYPE, ENCODE_TYPE_STRING); } byte[] keyBytes = null; keyBytes = getBytesEncode(encodeKeyType, sKey); switch (cryptAlgorithm) { case TRIPLE_DES_ALOGRITHEM: switch (encodeDataType) { case ENCODE_TYPE_HEX: return XStringUtils.hexEncode(mCryptor.encryptBytesFor3DES( sourceData.getBytes(), keyBytes)); default: return XBase64.encodeToString((mCryptor.encryptBytesFor3DES( sourceData.getBytes(), keyBytes)), XBase64.NO_WRAP); } case RSA_ALOGRITHEM: switch (encodeDataType) { case ENCODE_TYPE_HEX: return XStringUtils.hexEncode(mCryptor.encryptRSA( sourceData.getBytes(), keyBytes)); default: return XBase64.encodeToString((mCryptor.encryptRSA( sourceData.getBytes(), keyBytes)), XBase64.NO_WRAP); } default: switch (encodeDataType) { case ENCODE_TYPE_HEX: return XStringUtils.hexEncode(mCryptor.encryptBytesForDES( sourceData.getBytes(), keyBytes)); default: return XBase64.encodeToString((mCryptor.encryptBytesForDES( sourceData.getBytes(), keyBytes)), XBase64.NO_WRAP); } } } /** * 对称加密文件并返回 * * @param sKey 密钥 * @param sourceFilePath 需要加密的文件的路径(绝对路径) * @param targetFilePath 经过加密得到的文件的路径 * @return 加密后文件的相对路径 * @throws XCryptionException * @throws FileNotFoundException */ private String encryptFile(String sKey, String sourceFilePath, String targetFilePath) throws FileNotFoundException, XCryptionException { return doFileCrypt(sKey, sourceFilePath, targetFilePath, true); } /** * 对称解密字节数组并返回 * * @param sKey 密钥 * @param sourceData 需要解密的数据 * @param options 加解密配置选项 * @return 经过解密的数据 */ private String decrypt(String sKey, String sourceData, JSONObject options) throws XCryptionException { int cryptAlgorithm = DES_ALOGRITHEM; int encodeDataType = ENCODE_TYPE_STRING; int encodeKeyType = ENCODE_TYPE_STRING; if (options != null) { cryptAlgorithm = options.optInt(KEY_CRYPT_ALGORITHM, DES_ALOGRITHEM); encodeDataType = options.optInt(KEY_ENCODE_DATA_TYPE, ENCODE_TYPE_STRING); encodeKeyType = options.optInt(KEY_ENCODE_KEY_TYPE, ENCODE_TYPE_STRING); } byte[] keyBytes = null; keyBytes = getBytesEncode(encodeKeyType, sKey); switch (cryptAlgorithm) { case TRIPLE_DES_ALOGRITHEM: switch (encodeDataType) { case ENCODE_TYPE_HEX: return new String(mCryptor.decryptBytesFor3DES( XStringUtils.hexDecode(sourceData), keyBytes)); default: return new String(mCryptor.decryptBytesFor3DES( XBase64.decode(sourceData,XBase64.NO_WRAP), keyBytes)); } case RSA_ALOGRITHEM: switch (encodeDataType) { case ENCODE_TYPE_HEX: return new String(mCryptor.decryptRSA( XStringUtils.hexDecode(sourceData), keyBytes)); default: return new String(mCryptor.decryptRSA( XBase64.decode(sourceData, XBase64.NO_WRAP), keyBytes)); } default: switch (encodeDataType) { case ENCODE_TYPE_HEX: return new String(mCryptor.decryptBytesForDES( XStringUtils.hexDecode(sourceData), keyBytes)); default: return new String(mCryptor.decryptBytesForDES( XBase64.decode(sourceData,XBase64.NO_WRAP), keyBytes)); } } } /** * 对称解密文件并返回 * * @param sKey 密钥 * @param sourceFilePath 需要解密的文件的路径(绝对路径) * @param targetFilePath 经过解密得到的文件的路径 * @return 解密后文件的相对路径 * @throws FileNotFoundException */ private String decryptFile(String sKey, String sourceFilePath, String targetFilePath) throws XCryptionException, FileNotFoundException { return doFileCrypt(sKey, sourceFilePath, targetFilePath, false); } private String doFileCrypt(String sKey, String absSourceFilePath, String absTargetFilePath, boolean isEncrypt) throws XCryptionException{ String targetFilePath = absTargetFilePath; byte[] keyBytes = getBytesEncode(ENCODE_TYPE_STRING, sKey); if( isEncrypt ? mCryptor.encryptFileForDES(keyBytes, absSourceFilePath, absTargetFilePath) : mCryptor.decryptFileForDES(keyBytes, absSourceFilePath, absTargetFilePath)){ return targetFilePath; } throw new XCryptionException(CRYPTION_ERROR); } private String digest(String data) { XCryptor cryptor = new XCryptor(); try { return cryptor.calMD5Value(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { XLog.e(CLASS_NAME, "digest failed: UnsupportedEncodingException"); e.printStackTrace(); } return null; } /** * 获取文件的绝对路径 * @param targetFile * @return */ private String getAbsFilePath (File targetFile) throws IllegalArgumentException{ try { return targetFile.getCanonicalPath(); } catch (IOException e) { throw new IllegalArgumentException(); } } /** * 获取按直接编码解码后的keyBytes * @param encodeKeyType:编码类型 * @param keyString :解码前的keyString * @return 解码后的二进制串 */ private byte[] getBytesEncode(int encodeKeyType, String keyString) { if(XStringUtils.isEmptyString(keyString)) { return null; } switch (encodeKeyType) { case ENCODE_TYPE_BASE64: return XBase64.decode(keyString, XBase64.NO_WRAP); case ENCODE_TYPE_HEX: return XStringUtils.hexDecode(keyString); default: return keyString.getBytes(); } } }
false
false
null
null
diff --git a/msv/src/com/sun/msv/reader/xmlschema/AnyState.java b/msv/src/com/sun/msv/reader/xmlschema/AnyState.java index f0767b15..dae5a0db 100644 --- a/msv/src/com/sun/msv/reader/xmlschema/AnyState.java +++ b/msv/src/com/sun/msv/reader/xmlschema/AnyState.java @@ -1,113 +1,115 @@ /* * @(#)$Id$ * * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. * * This software is the proprietary information of Sun Microsystems, Inc. * Use is subject to license terms. * */ package com.sun.msv.reader.xmlschema; import com.sun.msv.grammar.Expression; import com.sun.msv.grammar.ReferenceExp; import com.sun.msv.grammar.NameClass; import com.sun.msv.grammar.NotNameClass; import com.sun.msv.grammar.NamespaceNameClass; import com.sun.msv.grammar.ChoiceNameClass; import com.sun.msv.grammar.AnyNameClass; import com.sun.msv.grammar.SimpleNameClass; +import com.sun.msv.grammar.trex.DifferenceNameClass; import com.sun.msv.grammar.xmlschema.ElementDeclExp; import com.sun.msv.grammar.xmlschema.LaxDefaultNameClass; import com.sun.msv.grammar.xmlschema.XMLSchemaSchema; import com.sun.msv.reader.ExpressionWithoutChildState; import java.util.StringTokenizer; import java.util.Iterator; /** * base implementation of AnyAttributeState and AnyElementState. * * @author <a href="mailto:kohsuke.kawaguchi@eng.sun.com">Kohsuke KAWAGUCHI</a> */ public abstract class AnyState extends ExpressionWithoutChildState { protected final Expression makeExpression() { return createExpression( startTag.getDefaultedAttribute("namespace","##any"), startTag.getDefaultedAttribute("processContents","strict") ); } protected abstract Expression createExpression( String namespace, String process ); /** * processes 'namepsace' attribute and gets corresponding NameClass object. */ protected NameClass getNameClass( String namespace, XMLSchemaSchema currentSchema ) { // we have to get currentSchema through parameter because // this method is also used while back-patching, and // reader.currentSchema points to the invalid schema in that case. final XMLSchemaReader reader = (XMLSchemaReader)this.reader; namespace = namespace.trim(); if( namespace.equals("##any") ) return AnyNameClass.theInstance; if( namespace.equals("##other") ) return new NotNameClass( new NamespaceNameClass(currentSchema.targetNamespace) ); NameClass choices=null; StringTokenizer tokens = new StringTokenizer(namespace); while( tokens.hasMoreTokens() ) { String token = tokens.nextToken(); NameClass nc; if( token.equals("##targetNamespace") ) nc = new NamespaceNameClass(currentSchema.targetNamespace); else if( token.equals("##local") ) nc = new NamespaceNameClass(""); else nc = new NamespaceNameClass(token); if( choices==null ) choices = nc; else choices = new ChoiceNameClass(choices,nc); } if( choices==null ) { // no item was found. reader.reportError( reader.ERR_BAD_ATTRIBUTE_VALUE, "namespace", namespace ); return AnyNameClass.theInstance; } return choices; } protected NameClass createLaxNameClass( NameClass allowedNc, XMLSchemaReader.RefResolver res ) { final XMLSchemaReader reader = (XMLSchemaReader)this.reader; LaxDefaultNameClass laxNc = new LaxDefaultNameClass(); Iterator itr = reader.grammar.schemata.values().iterator(); while( itr.hasNext() ) { XMLSchemaSchema schema = (XMLSchemaSchema)itr.next(); if(allowedNc.accepts( schema.targetNamespace, NameClass.LOCALNAME_WILDCARD )) { ReferenceExp[] refs = res.get(schema).getAll(); for( int i=0; i<refs.length; i++ ) { ElementDeclExp decl = (ElementDeclExp)refs[i]; NameClass elementName = decl.self.getNameClass(); if(!(elementName instanceof SimpleNameClass )) // assertion failed. // XML Schema's element declaration is always simple name. throw new Error(); SimpleNameClass snc = (SimpleNameClass)elementName; laxNc.addAllowedName(snc.namespaceURI,snc.localName); } } } - return laxNc; + // laxNc - names in namespaces that are not allowed. + return new DifferenceNameClass( laxNc, new NotNameClass(allowedNc) ); } }
false
false
null
null
diff --git a/src/net/othercraft/steelsecurity/listeners/ChatFilter.java b/src/net/othercraft/steelsecurity/listeners/ChatFilter.java index 4e5de18..135b72c 100644 --- a/src/net/othercraft/steelsecurity/listeners/ChatFilter.java +++ b/src/net/othercraft/steelsecurity/listeners/ChatFilter.java @@ -1,76 +1,69 @@ package net.othercraft.steelsecurity.listeners; -import java.util.List; - -import net.othercraft.steelsecurity.Config; import net.othercraft.steelsecurity.Main; import net.othercraft.steelsecurity.utils.SSCmdExe; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerChatEvent; -import org.bukkit.plugin.java.JavaPlugin; public class ChatFilter extends SSCmdExe implements Listener { + public ChatFilter(String name) { + super(name, true);//true only if its a listener, false if it isnt + } + public Main plugin; - public SSCmdExe scme; - - public ChatFilter(Main instance) { - plugin = instance; - } - - @EventHandler public void onPlayerChat(PlayerChatEvent event){ try{ String message = event.getMessage(); if (plugin.getConfig().getBoolean("AntiSpam.Censoring.Enabled") && event.getPlayer().hasPermission("steelsecurity.antispam.bypasscensor") == false) { String[] list = (String[]) plugin.getConfig().getList("AntiSpam.Censoring.Block_Words").toArray(); int wordcount = list.length; int wordcounter = 0; while (wordcounter<wordcount) { int lettercount = list[wordcounter].toCharArray().length; int lettercounter = 0; String newword = ""; String badword = list[wordcounter].toString(); while (lettercounter<lettercount) { newword = (newword + "*"); lettercounter = lettercounter + 1; } message = message.replaceAll("(?i)" + badword, newword); wordcounter = wordcounter + 1; } } if (event.getMessage().length()>plugin.getConfig().getInt("AntiSpam.AntiCaps.Minimum_Length")){ if (plugin.getConfig().getBoolean("AntiSpam.AntiCaps.Enabled") && event.getPlayer().hasPermission("steelsecurity.antispam.bypassanticaps") == false) { int percent = plugin.getConfig().getInt("AntiSpam.AntiCaps.Percent"); int capcount = message.length(); int capcounter = 0; Double uppercase = 0.0; Double lowercase = 0.0; while (capcounter<capcount) { if (message.toCharArray()[capcounter] == message.toLowerCase().toCharArray()[capcounter]) { lowercase = lowercase + 1.0; } else { uppercase = uppercase + 1.0; } capcounter = capcounter + 1; } double total = uppercase + lowercase; double result = uppercase/total; percent = percent/100; if (percent<result){ message = message.toLowerCase(); } } } event.setMessage(message); } catch(Exception e){//note, catch GENERIC exception catchListenerException(e); } } }
false
false
null
null
diff --git a/appCore.Personnel/src/main/java/com/appCore/personnel/Core/Service/DepartmentService.java b/appCore.Personnel/src/main/java/com/appCore/personnel/Core/Service/DepartmentService.java index 4b70137..c9e61d7 100644 --- a/appCore.Personnel/src/main/java/com/appCore/personnel/Core/Service/DepartmentService.java +++ b/appCore.Personnel/src/main/java/com/appCore/personnel/Core/Service/DepartmentService.java @@ -1,154 +1,151 @@ package com.appCore.personnel.Core.Service; import java.util.List; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.apache.log4j.Logger; +import com.appCore.personnel.Core.Entity.Branch; import com.appCore.personnel.Core.Entity.BranchInfo; import com.appCore.personnel.Core.Entity.Department; import com.appCore.personnel.Core.Entity.DepartmentInfo; import com.appCore.personnel.Core.Entity.DepartmentSummary; import com.appCore.personnel.Core.Entity.Section; @Service("departmentService") @Transactional public class DepartmentService { @Resource(name="sessionFactory") private SessionFactory sessionFactory; protected static Logger logger = Logger.getLogger("service"); public DepartmentSummary getSummary(Integer companyId) { int summaryResultCount = 3; Session session = sessionFactory.getCurrentSession(); Query queryCount = session.createQuery("select count(*) from Department where companyId = :companyId"); queryCount.setParameter("companyId", companyId); Long summaryCount = ((Long) queryCount.uniqueResult()).longValue(); Query query = session.createQuery("FROM Department where companyId = :companyId"); query.setParameter("companyId", companyId); List<Department> list = query.setMaxResults(summaryResultCount).list(); DepartmentSummary summary = new DepartmentSummary(); summary.setCount(summaryCount); summary.setListDepartment(list); return summary; } public List<Department> getAll() { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("FROM Department"); List<Department> deptList = query.list(); return query.list(); } public List<Department> getAllByCompany(Integer id) { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("FROM Department WHERE CompanyId = :id"); query.setParameter("id", id); return query.list(); } public Department get(Integer id) { Session session = sessionFactory.getCurrentSession(); Department department = (Department) session.get(Department.class, id); Query query = session.createQuery("FROM DepartmentInfo WHERE RefEntity = :id"); query.setParameter("id", id); List<DepartmentInfo> info = query.list(); department.setDepartmentInfo(info); return department; } public List<Department> getByDivisionId(Integer id) { Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery("From Department where DivisionId = :divisionId"); query.setParameter("divisionId", id); return query.list(); } public void add(Department department) { Session session = sessionFactory.getCurrentSession(); Integer savedInstance = (Integer) session.save(department); for (DepartmentInfo info : department.getDepartmentInfo()) { info.setRefEntity(savedInstance); session.save(info); } /*for (Section section : department.getSection()) { logger.debug("Traversing section code : " + section.getSectionCode()); section.setDepartmentId(savedInteger); session.save(section); }*/ } public void saveOrUpdate(Department department) { Session session = sessionFactory.getCurrentSession(); session.saveOrUpdate(department); } public void save(Department department) { Session session = sessionFactory.getCurrentSession(); session.save(department); } public void delete(Integer id) { Session session = sessionFactory.getCurrentSession(); Department department = (Department) session.get(Department.class, id); - - Query deleteQuery = session.createQuery("Delete FROM Section where DepartmentId = :id"); - deleteQuery.setParameter("id", id); - deleteQuery.executeUpdate(); session.delete(department); } public void edit(Department department) { Session session = sessionFactory.getCurrentSession(); Department target = (Department) session.get(Department.class, department.getNid()); target.setNid(department.getNid()); target.setDepartmentCode(department.getDepartmentCode()); target.setDepartmentInfo(department.getDepartmentInfo()); target.setDepartmentName(department.getDepartmentName()); target.setRemark(department.getRemark()); target.setDisabled(department.getDisabled()); target.setLastUpdate(department.getLastUpdate()); session.save(target); } } \ No newline at end of file
false
false
null
null
diff --git a/frontend/src/main/java/cl/own/usi/gateway/netty/controller/RankingController.java b/frontend/src/main/java/cl/own/usi/gateway/netty/controller/RankingController.java index 0424850..eb676ba 100644 --- a/frontend/src/main/java/cl/own/usi/gateway/netty/controller/RankingController.java +++ b/frontend/src/main/java/cl/own/usi/gateway/netty/controller/RankingController.java @@ -1,86 +1,86 @@ package cl.own.usi.gateway.netty.controller; import static cl.own.usi.gateway.netty.ResponseHelper.writeResponse; import static cl.own.usi.gateway.netty.ResponseHelper.writeStringToReponse; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK; import static org.jboss.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.handler.codec.http.HttpRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import cl.own.usi.gateway.client.BeforeAndAfterScores; import cl.own.usi.gateway.client.UserAndScore; import cl.own.usi.gateway.client.WorkerClient; import cl.own.usi.gateway.utils.ScoresHelper; import cl.own.usi.service.GameService; /** * Controller that return the rank and scores * * @author bperroud * @author nicolas */ @Component public class RankingController extends AbstractController { @Autowired private WorkerClient workerClient; @Autowired private GameService gameService; @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); String userId = getCookie(request, COOKIE_AUTH_NAME); if (userId == null) { writeResponse(e, UNAUTHORIZED); getLogger().info("User not authorized"); } else { if (!gameService.isRankingRequestAllowed()) { writeResponse(e, BAD_REQUEST); } else { UserAndScore userAndScore = workerClient .validateUserAndGetScore(userId); if (userAndScore.getUserId() == null) { writeResponse(e, UNAUTHORIZED); getLogger().info("Invalid userId {}", userId); } else { StringBuilder sb = new StringBuilder("{"); sb.append(" \"my_score\" : ") .append(userAndScore.getScore()).append(", "); sb.append(" \"top_scores\" : { ") .append(gameService.getTop100AsString()) .append(" }, "); BeforeAndAfterScores beforeAndAfterScores = workerClient.get50BeforeAnd50After(userId); - sb.append(" \"before_me\" : { "); + sb.append(" \"before\" : { "); ScoresHelper.appendUsersScores(beforeAndAfterScores.getScoresBefore(), sb); sb.append(" }, "); - sb.append(" \"after_me\" : { "); + sb.append(" \"after\" : { "); ScoresHelper.appendUsersScores(beforeAndAfterScores.getScoresAfter(), sb); sb.append(" } "); sb.append(" } "); writeStringToReponse(sb.toString(), e, OK); } } } } }
false
true
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); String userId = getCookie(request, COOKIE_AUTH_NAME); if (userId == null) { writeResponse(e, UNAUTHORIZED); getLogger().info("User not authorized"); } else { if (!gameService.isRankingRequestAllowed()) { writeResponse(e, BAD_REQUEST); } else { UserAndScore userAndScore = workerClient .validateUserAndGetScore(userId); if (userAndScore.getUserId() == null) { writeResponse(e, UNAUTHORIZED); getLogger().info("Invalid userId {}", userId); } else { StringBuilder sb = new StringBuilder("{"); sb.append(" \"my_score\" : ") .append(userAndScore.getScore()).append(", "); sb.append(" \"top_scores\" : { ") .append(gameService.getTop100AsString()) .append(" }, "); BeforeAndAfterScores beforeAndAfterScores = workerClient.get50BeforeAnd50After(userId); sb.append(" \"before_me\" : { "); ScoresHelper.appendUsersScores(beforeAndAfterScores.getScoresBefore(), sb); sb.append(" }, "); sb.append(" \"after_me\" : { "); ScoresHelper.appendUsersScores(beforeAndAfterScores.getScoresAfter(), sb); sb.append(" } "); sb.append(" } "); writeStringToReponse(sb.toString(), e, OK); } } } }
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); String userId = getCookie(request, COOKIE_AUTH_NAME); if (userId == null) { writeResponse(e, UNAUTHORIZED); getLogger().info("User not authorized"); } else { if (!gameService.isRankingRequestAllowed()) { writeResponse(e, BAD_REQUEST); } else { UserAndScore userAndScore = workerClient .validateUserAndGetScore(userId); if (userAndScore.getUserId() == null) { writeResponse(e, UNAUTHORIZED); getLogger().info("Invalid userId {}", userId); } else { StringBuilder sb = new StringBuilder("{"); sb.append(" \"my_score\" : ") .append(userAndScore.getScore()).append(", "); sb.append(" \"top_scores\" : { ") .append(gameService.getTop100AsString()) .append(" }, "); BeforeAndAfterScores beforeAndAfterScores = workerClient.get50BeforeAnd50After(userId); sb.append(" \"before\" : { "); ScoresHelper.appendUsersScores(beforeAndAfterScores.getScoresBefore(), sb); sb.append(" }, "); sb.append(" \"after\" : { "); ScoresHelper.appendUsersScores(beforeAndAfterScores.getScoresAfter(), sb); sb.append(" } "); sb.append(" } "); writeStringToReponse(sb.toString(), e, OK); } } } }
diff --git a/core/PApplet.java b/core/PApplet.java index 982d63842..307487d3f 100644 --- a/core/PApplet.java +++ b/core/PApplet.java @@ -1,5494 +1,5499 @@ /* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* PApplet - applet base class for the bagel engine Part of the Processing project - http://processing.org Copyright (c) 2004- Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology 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 processing.core; import java.applet.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.text.*; import java.util.*; import java.util.zip.*; public class PApplet extends Applet implements PConstants, Runnable, MouseListener, MouseMotionListener, KeyListener, FocusListener { // JDK_VERSION_STR = "1.3" or "1.1" or whatever public static final String JDK_VERSION_STRING = System.getProperty("java.version").substring(0,3); public static final double JDK_VERSION = new Double(JDK_VERSION_STRING).doubleValue(); //toFloat(System.getProperty("java.version").substring(0,3)); public PGraphics g; protected Object glock = new Object(); // for sync public Frame frame; protected PMethods recorder; /** Command line options passed in from main() */ public String args[]; /** Path to sketch folder */ public String folder; // = System.getProperty("user.dir"); /** When debugging headaches */ static final boolean THREAD_DEBUG = false; public int pixels[]; public int mouseX, mouseY; public int pmouseX, pmouseY; /** * previous mouseX/Y for the draw loop, separated out because this is * separate from the pmouseX/Y when inside the mouse event handlers. */ protected int dmouseX, dmouseY; /** * pmouseX/Y for the event handlers (mousePressed(), mouseDragged() etc) * these are different because mouse events are queued to the end of * draw, so the previous position has to be updated on each event, * as opposed to the pmouseX/Y that's used inside draw, which is expected * to be updated once per trip through draw(). */ protected int emouseX, emouseY; /** * used to set pmouseX/Y to mouseX/Y the first time mouseX/Y are used, * otherwise pmouseX/Y are always zero, causing a nasty jump. just using * (frameCount == 0) won't work since mouseXxxxx() may not be called * until a couple frames into things. */ public boolean firstMouse; public boolean mousePressed; public MouseEvent mouseEvent; /** * Last key pressed. If it's a coded key * (arrows or ctrl/shift/alt, this will be set to 0xffff or 65535). */ public char key; /** * If the key is a coded key, i.e. up/down/ctrl/shift/alt * the 'key' comes through as 0xffff (65535) */ public int keyCode; public boolean keyPressed; public KeyEvent keyEvent; /** * Gets set to true/false as the applet gains/loses focus. */ public boolean focused = false; /** * Is the applet online or not? This can be used to test how the * applet should behave since online situations are different. */ public boolean online = false; long millisOffset; // getting the frame rate protected float fps = 10; protected long fpsLastMillis = 0; // setting the frame rate protected long fpsLastDelayTime = 0; protected float fpsTarget = 0; //boolean drawMethod; //boolean loopMethod; protected boolean looping; protected boolean redraw; // true if inside the loop method //boolean insideLoop; // used for mouse tracking so that pmouseX doesn't get // updated too many times while still inside the loop // instead, it's updated only before/after the loop() //int qmouseX, qmouseY; // queue for whether to call the simple mouseDragged or // mouseMoved functions. these are called after beginFrame // but before loop() is called itself, to avoid problems // in synchronization. //boolean qmouseDragged; //boolean qmouseMoved; //boolean firstFrame; // current frame number (could this be used to replace firstFrame?) public int frameCount; // true if the feller has spun down public boolean finished; //boolean drawn; Thread thread; public Exception exception; // the last exception thrown static public final int DEFAULT_WIDTH = 100; static public final int DEFAULT_HEIGHT = 100; protected int INITIAL_WIDTH = DEFAULT_WIDTH; protected int INITIAL_HEIGHT = DEFAULT_HEIGHT; public int width, height; protected RegisteredMethods sizeMethods; protected RegisteredMethods preMethods, drawMethods, postMethods; protected RegisteredMethods mouseEventMethods, keyEventMethods; protected RegisteredMethods disposeMethods; //protected int libraryCount; //protected PLibrary libraries[]; //protected boolean libraryCalls[][]; //int setupCount = 0; // this text isn't seen unless PApplet is used on its // own and someone takes advantage of leechErr.. not likely static public final String LEECH_WAKEUP = "Error while running applet."; public PrintStream leechErr; // message to send if attached as an external vm //static public final String EXTERNAL_FLAG = "--external="; //static public final char EXTERNAL_EXACT_LOCATION = 'e'; static public final String EXT_LOCATION = "--location="; static public final String EXT_SIZE = "--size="; static public final String EXT_EXACT_LOCATION = "--exact-location="; static public final String EXT_SKETCH_FOLDER = "--sketch-folder="; static public final char EXTERNAL_STOP = 's'; static public final String EXTERNAL_QUIT = "__QUIT__"; static public final String EXTERNAL_MOVE = "__MOVE__"; //boolean externalRuntime; //static boolean setupComplete = false; public void init() { //checkParams(); // can/may be resized later //g = new PGraphics(DEFAULT_WIDTH, DEFAULT_HEIGHT); initGraphics(); // send tab keys through to the PApplet try { if (JDK_VERSION >= 1.4) { //setFocusTraversalKeysEnabled(false); // 1.4-only function Method defocus = Component.class.getMethod("setFocusTraversalKeysEnabled", new Class[] { Boolean.TYPE }); defocus.invoke(this, new Object[] { Boolean.FALSE }); } } catch (Exception e) { } // oh well millisOffset = System.currentTimeMillis(); finished = false; // just for clarity // this will be cleared by loop() if it is not overridden looping = true; redraw = true; // draw this guy once firstMouse = true; // these need to be inited before setup sizeMethods = new RegisteredMethods(); preMethods = new RegisteredMethods(); drawMethods = new RegisteredMethods(); postMethods = new RegisteredMethods(); mouseEventMethods = new RegisteredMethods(); keyEventMethods = new RegisteredMethods(); disposeMethods = new RegisteredMethods(); try { getAppletContext(); online = true; } catch (NullPointerException e) { online = false; } start(); } // override for subclasses (i.e. opengl) // so that init() doesn't have to be replicated public void initGraphics() { // 0073: moved here so that can be overridden for PAppletGL addMouseListener(this); addMouseMotionListener(this); addKeyListener(this); addFocusListener(this); } public void createGraphics() { Dimension size = getSize(); if (PApplet.JDK_VERSION >= 1.3) { g = new PGraphics2(INITIAL_WIDTH, INITIAL_HEIGHT); //g = new PGraphics2(size.width, size.height); //DEFAULT_WIDTH, DEFAULT_HEIGHT); } else { g = new PGraphics(INITIAL_WIDTH, INITIAL_HEIGHT); //g = new PGraphics(size.width, size.height); //g = new PGraphics(DEFAULT_WIDTH, DEFAULT_HEIGHT); } } public void depth() { if (g.textFont != null) { die("textFont() cannot be used before calling depth()"); } // OPT if PGraphics already exists, pass in its pixels[] // buffer so as not to re-allocate all that memory again if (g.width != 0) { g = new PGraphics3(g.width, g.height); } else { Dimension size = getSize(); g = new PGraphics3(size.width, size.height); } // re-call the beginframe with the new graphics g.beginFrame(); // it's ok to call this, because depth() is only getting called // at least inside of setup, so things can be drawn just // fine since it's post-beginFrame. g.defaults(); } /** * Called via the first call to PApplet.paint(), * because PAppletGL needs to have a usable screen * before getting things rolling. */ public void start() { if (thread != null) return; thread = new Thread(this); thread.start(); } // maybe start should also be used as the method for kicking // the thread on, instead of doing it inside paint() public void stop() { //finished = true; // why did i comment this out? // don't run stop and disposers twice if (thread == null) return; thread = null; disposeMethods.handle(); } /** * This also calls stop(), in case there was an inadvertent * override of the stop() function by a user. * * destroy() supposedly gets called as the applet viewer * is shutting down the applet. stop() is called * first, and then destroy() to really get rid of things. * no guarantees on when they're run (on browser quit, or * when moving between pages), though. */ public void destroy() { stop(); } public Dimension getPreferredSize() { return new Dimension(width, height); } // ------------------------------------------------------------ public class RegisteredMethods { int count; Object objects[]; Method methods[]; // convenience version for no args public void handle() { handle(new Object[] { }); } public void handle(Object args[]) { for (int i = 0; i < count; i++) { try { //System.out.println(objects[i] + " " + args); methods[i].invoke(objects[i], args); } catch (Exception e) { e.printStackTrace(); } } } public void add(Object object, Method method) { if (objects == null) { objects = new Object[5]; methods = new Method[5]; } if (count == objects.length) { Object otemp[] = new Object[count << 1]; System.arraycopy(objects, 0, otemp, 0, count); objects = otemp; Method mtemp[] = new Method[count << 1]; System.arraycopy(methods, 0, mtemp, 0, count); methods = mtemp; } objects[count] = object; methods[count] = method; count++; } } public void registerSize(Object o) { Class methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; registerWithArgs(preMethods, "size", o, methodArgs); } public void registerPre(Object o) { registerNoArgs(preMethods, "pre", o); } public void registerDraw(Object o) { registerNoArgs(drawMethods, "draw", o); } public void registerPost(Object o) { registerNoArgs(postMethods, "post", o); } public void registerMouseEvent(Object o) { Class methodArgs[] = new Class[] { MouseEvent.class }; registerWithArgs(mouseEventMethods, "mouseEvent", o, methodArgs); } public void registerKeyEvent(Object o) { Class methodArgs[] = new Class[] { KeyEvent.class }; registerWithArgs(keyEventMethods, "keyEvent", o, methodArgs); } public void registerDispose(Object o) { registerNoArgs(disposeMethods, "dispose", o); } protected void registerNoArgs(RegisteredMethods meth, String name, Object o) { Class c = o.getClass(); try { Method method = c.getMethod(name, new Class[] {}); meth.add(o, method); } catch (Exception e) { die("Could not register " + name + " + () for " + o, e); } } protected void registerWithArgs(RegisteredMethods meth, String name, Object o, Class args[]) { Class c = o.getClass(); try { Method method = c.getMethod(name, args); meth.add(o, method); } catch (Exception e) { die("Could not register " + name + " + () for " + o, e); } } // ------------------------------------------------------------ public void setup() { } public void draw() { - finished = true; // if no draw method, then... + // if no draw method, then shut things down + finished = true; } public void redraw() { if (!looping) { redraw = true; if (thread != null) { - //thread.interrupt(); // wake from sleep + // wake from sleep (necessary otherwise it'll be + // up to 10 seconds before update) + thread.interrupt(); } } } public void loop() { if (!looping) { looping = true; if (thread != null) { - //thread.interrupt(); // wake from sleep + // wake from sleep (necessary otherwise it'll be + // up to 10 seconds before update) + thread.interrupt(); } } } public void noLoop() { if (looping) { looping = false; // reset framerate delay times fpsLastDelayTime = 0; fpsLastMillis = 0; if (thread != null) { //thread.interrupt(); // wake from sleep } } } // ------------------------------------------------------------ public void size(int iwidth, int iheight) { if (g == null) return; g.resize(iwidth, iheight); this.pixels = g.pixels; this.width = g.width; this.height = g.height; Object methodArgs[] = new Object[] { new Integer(width), new Integer(height) }; sizeMethods.handle(methodArgs); if (frame != null) { Insets insets = frame.getInsets(); // msft windows has a limited minimum size for frames int minW = 120; int minH = 120; int winW = Math.max(width, minW) + insets.left + insets.right; int winH = Math.max(height, minH) + insets.top + insets.bottom; frame.setSize(winW, winH); setBounds((winW - width)/2, insets.top + ((winH - insets.top - insets.bottom) - height)/2, winW, winH); } else { //System.out.println("frame was null"); setBounds(0, 0, width, height); } } public void update(Graphics screen) { //System.out.println("PApplet.update()"); if (THREAD_DEBUG) println(Thread.currentThread().getName() + " 4 update() external"); paint(screen); } //synchronized public void paint(Graphics screen) { public void paint(Graphics screen) { //System.out.println("PApplet.paint()"); if (THREAD_DEBUG) println(Thread.currentThread().getName() + " 5a enter paint"); // ignore the very first call to paint, since it's coming // from the o.s., and the applet will soon update itself anyway. //if (firstFrame) return; if (frameCount == 0) { // paint() may be called more than once before things // are finally painted to the screen and the thread gets going /* if (thread == null) { initGraphics(); start(); } */ return; } // without ignoring the first call, the first several frames // are confused because paint() gets called in the midst of // the initial nextFrame() call, so there are multiple // updates fighting with one another. // g.image is synchronized so that draw/loop and paint don't // try to fight over it. this was causing a randomized slowdown // that would cut the framerate into a third on macosx, // and is probably related to the windows sluggishness bug too if (THREAD_DEBUG) println(Thread.currentThread().getName() + " 5b enter paint sync"); synchronized (g) { if (THREAD_DEBUG) println(Thread.currentThread().getName() + " 5c inside paint sync"); //System.out.println("5b paint has sync"); //Exception e = new Exception(); //e.printStackTrace(); // moving this into PGraphics caused weird sluggishness on win2k //g.mis.newPixels(pixels, g.cm, 0, width); // must call this // make sure the screen is visible and usable if (g != null) { screen.drawImage(g.image, 0, 0, null); } //if (THREAD_DEBUG) println("notifying all"); //notifyAll(); //thread.notify(); //System.out.println(" 6 exit paint"); } if (THREAD_DEBUG) println(Thread.currentThread().getName() + " 6 exit paint"); //updated = true; } public void run() { try { /* // first time around, call the applet's setup method setup(); // these are the same things as get run inside a call to size() this.pixels = g.pixels; this.width = g.width; this.height = g.height; */ while ((Thread.currentThread() == thread) && !finished) { //while (!finished) { //updated = false; if (PApplet.THREAD_DEBUG) println(Thread.currentThread().getName() + " formerly nextFrame()"); //if (looping || redraw) nextFrame(); if (looping || redraw) { if (frameCount == 0) { // needed here for the sync createGraphics(); } // g may be rebuilt inside here, so turning of the sync //synchronized (g) { // use a different sync object synchronized (glock) { if (THREAD_DEBUG) println(Thread.currentThread().getName() + " 1a beginFrame"); g.beginFrame(); if (THREAD_DEBUG) println(Thread.currentThread().getName() + " 1b draw"); if (frameCount == 0) { //initGraphics(); //createGraphics(); g.defaults(); setup(); // if depth() is called inside setup, pixels/width/height // will be ok by the time it's back out again this.pixels = g.pixels; this.width = g.width; this.height = g.height; } else { if (fpsTarget != 0) { if (fpsLastDelayTime == 0) { fpsLastDelayTime = System.currentTimeMillis(); } else { long timeToLeave = fpsLastDelayTime + (long)(1000.0f / fpsTarget); int napTime = (int) (timeToLeave - System.currentTimeMillis()); fpsLastDelayTime = timeToLeave; delay(napTime); } } preMethods.handle(); pmouseX = dmouseX; pmouseY = dmouseY; draw(); // dmouseX/Y is updated only once per frame dmouseX = mouseX; dmouseY = mouseY; // these are called *after* loop so that valid // drawing commands can be run inside them. it can't // be before, since a call to background() would wipe // out anything that had been drawn so far. dequeueMouseEvents(); dequeueKeyEvents(); if (THREAD_DEBUG) println(Thread.currentThread().getName() + " 2b endFrame"); drawMethods.handle(); //for (int i = 0; i < libraryCount; i++) { //if (libraryCalls[i][PLibrary.DRAW]) libraries[i].draw(); //} redraw = false; // unset 'redraw' flag in case it was set // (only do this once draw() has run, not just setup()) } g.endFrame(); if (recorder != null) { recorder.endFrame(); recorder = null; } //} // older end sync //update(); // formerly 'update' //if (firstFrame) firstFrame = false; // internal frame counter frameCount++; if (THREAD_DEBUG) println(Thread.currentThread().getName() + " 3a calling repaint() " + frameCount); repaint(); if (THREAD_DEBUG) println(Thread.currentThread().getName() + " 3b calling Toolkit.sync " + frameCount); getToolkit().sync(); // force repaint now (proper method) if (THREAD_DEBUG) println(Thread.currentThread().getName() + " 3c done " + frameCount); //if (THREAD_DEBUG) println(" 3d waiting"); //wait(); //if (THREAD_DEBUG) println(" 3d out of wait"); //frameCount++; postMethods.handle(); //for (int i = 0; i < libraryCount; i++) { //if (libraryCalls[i][PLibrary.POST]) libraries[i].post(); //} } // end of synchronize } // moving this to update() (for 0069+) for linux sync problems //if (firstFrame) firstFrame = false; // wait for update & paint to happen before drawing next frame // this is necessary since the drawing is sometimes in a // separate thread, meaning that the next frame will start // before the update/paint is completed //while (!updated) { try { if (THREAD_DEBUG) println(Thread.currentThread().getName() + " " + looping + " " + redraw); //Thread.yield(); // windows doesn't like 'yield', so have to sleep at least // for some small amount of time. if (THREAD_DEBUG) println(Thread.currentThread().getName() + " gonna sleep"); // can't remember when/why i changed that to '1' // (rather than 3 or 5, as has been traditional), but i // have a feeling that some platforms aren't gonna like that // if !looping, sleeps for a nice long time int nap = looping ? 1 : 10000; // don't nap after setup, because if noLoop() is called this // will make the first draw wait 10 seconds before showing up if (frameCount == 1) nap = 1; Thread.sleep(nap); if (THREAD_DEBUG) println(Thread.currentThread().getName() + " outta sleep"); } catch (InterruptedException e) { } //} } } catch (Exception e) { // formerly in kjcapplet, now just checks to see // if someone wants to leech off errors // note that this will not catch errors inside setup() // those are caught by the PdeRuntime finished = true; if (leechErr != null) { // if draw() mode, make sure that ui stops waiting // and the run button quits out leechErr.println(LEECH_WAKEUP); e.printStackTrace(leechErr); } else { System.err.println(LEECH_WAKEUP); e.printStackTrace(); } } if (THREAD_DEBUG) println(Thread.currentThread().getName() + " thread finished"); stop(); // call to shutdown libs? } // ------------------------------------------------------------ MouseEvent mouseEventQueue[] = new MouseEvent[10]; int mouseEventCount; protected void enqueueMouseEvent(MouseEvent e) { synchronized (mouseEventQueue) { if (mouseEventCount == mouseEventQueue.length) { MouseEvent temp[] = new MouseEvent[mouseEventCount << 1]; System.arraycopy(mouseEventQueue, 0, temp, 0, mouseEventCount); mouseEventQueue = temp; } mouseEventQueue[mouseEventCount++] = e; } } protected void dequeueMouseEvents() { synchronized (mouseEventQueue) { for (int i = 0; i < mouseEventCount; i++) { mouseEvent = mouseEventQueue[i]; handleMouseEvent(mouseEvent); } mouseEventCount = 0; } } /** * Actually take action based on a mouse event. * Internally updates mouseX, mouseY, mousePressed, and mouseEvent. * Then it calls the event type with no params, * i.e. mousePressed() or mouseReleased() that the user may have * overloaded to do something more useful. */ protected void handleMouseEvent(MouseEvent event) { pmouseX = emouseX; pmouseY = emouseY; mouseX = event.getX(); mouseY = event.getY(); mouseEvent = event; mouseEventMethods.handle(new Object[] { event }); /* for (int i = 0; i < libraryCount; i++) { if (libraryCalls[i][PLibrary.MOUSE]) { libraries[i].mouse(event); // endNet/endSerial etc } } */ // this used to only be called on mouseMoved and mouseDragged // change it back if people run into trouble if (firstMouse) { pmouseX = mouseX; pmouseY = mouseY; dmouseX = mouseX; dmouseY = mouseY; firstMouse = false; } switch (event.getID()) { case MouseEvent.MOUSE_PRESSED: mousePressed = true; mousePressed(); break; case MouseEvent.MOUSE_RELEASED: mousePressed = false; mouseReleased(); break; case MouseEvent.MOUSE_CLICKED: mouseClicked(); break; case MouseEvent.MOUSE_DRAGGED: mouseDragged(); break; case MouseEvent.MOUSE_MOVED: mouseMoved(); break; } emouseX = mouseX; emouseY = mouseY; } /** * Figure out how to process a mouse event. When loop() has been * called, the events will be queued up until drawing is complete. * If noLoop() has been called, then events will happen immediately. */ protected void checkMouseEvent(MouseEvent event) { if (looping) { enqueueMouseEvent(event); } else { handleMouseEvent(event); } } /** * If you override this or any function that takes a "MouseEvent e" * without calling its super.mouseXxxx() then mouseX, mouseY, * mousePressed, and mouseEvent will no longer be set. */ public void mousePressed(MouseEvent e) { checkMouseEvent(e); } public void mouseReleased(MouseEvent e) { checkMouseEvent(e); } public void mouseClicked(MouseEvent e) { checkMouseEvent(e); } public void mouseEntered(MouseEvent e) { checkMouseEvent(e); } public void mouseExited(MouseEvent e) { checkMouseEvent(e); } public void mouseDragged(MouseEvent e) { checkMouseEvent(e); } public void mouseMoved(MouseEvent e) { checkMouseEvent(e); } /** * Mouse has been pressed, and should be considered "down" * until mouseReleased() is called. If you must, use * int button = mouseEvent.getButton(); * to figure out which button was clicked. It will be one of: * MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3 * Note, however, that this is completely inconsistent across * platforms. */ public void mousePressed() { } /** * Mouse button has been released. */ public void mouseReleased() { } /** * When the mouse is clicked, mousePressed() will be called, * then mouseReleased(), then mouseClicked(). Note that * mousePressed is already false inside of mouseClicked(). */ public void mouseClicked() { } /** * Mouse button is pressed and the mouse has been dragged. */ public void mouseDragged() { } /** * Mouse button is not pressed but the mouse has changed locations. */ public void mouseMoved() { } // ------------------------------------------------------------ KeyEvent keyEventQueue[] = new KeyEvent[10]; int keyEventCount; protected void enqueueKeyEvent(KeyEvent e) { synchronized (keyEventQueue) { if (keyEventCount == keyEventQueue.length) { KeyEvent temp[] = new KeyEvent[keyEventCount << 1]; System.arraycopy(keyEventQueue, 0, temp, 0, keyEventCount); keyEventQueue = temp; } keyEventQueue[keyEventCount++] = e; } } protected void dequeueKeyEvents() { synchronized (keyEventQueue) { for (int i = 0; i < keyEventCount; i++) { keyEvent = keyEventQueue[i]; handleKeyEvent(keyEvent); } keyEventCount = 0; } } protected void handleKeyEvent(KeyEvent event) { keyEvent = event; key = event.getKeyChar(); keyCode = event.getKeyCode(); keyEventMethods.handle(new Object[] { event }); /* for (int i = 0; i < libraryCount; i++) { if (libraryCalls[i][PLibrary.KEY]) { libraries[i].key(event); // endNet/endSerial etc } } */ switch (event.getID()) { case KeyEvent.KEY_PRESSED: keyPressed = true; keyPressed(); break; case KeyEvent.KEY_RELEASED: keyPressed = false; keyReleased(); break; case KeyEvent.KEY_TYPED: keyTyped(); break; } } protected void checkKeyEvent(KeyEvent event) { if (looping) { enqueueKeyEvent(event); } else { handleKeyEvent(event); } } /** * Overriding keyXxxxx(KeyEvent e) functions will cause the 'key', * 'keyCode', and 'keyEvent' variables to no longer work; * key events will no longer be queued until the end of draw(); * and the keyPressed(), keyReleased() and keyTyped() methods * will no longer be called. */ public void keyPressed(KeyEvent e) { checkKeyEvent(e); } public void keyReleased(KeyEvent e) { checkKeyEvent(e); } public void keyTyped(KeyEvent e) { checkKeyEvent(e); } /** * Called each time a single key on the keyboard is pressed. * * Examples for key handling: * (Tested on Windows XP, please notify if different on other * platforms, I have a feeling Mac OS and Linux may do otherwise) * * 1. Pressing 'a' on the keyboard: * keyPressed with key == 'a' and keyCode == 'A' * keyTyped with key == 'a' and keyCode == 0 * keyReleased with key == 'a' and keyCode == 'A' * * 2. Pressing 'A' on the keyboard: * keyPressed with key == 'A' and keyCode == 'A' * keyTyped with key == 'A' and keyCode == 0 * keyReleased with key == 'A' and keyCode == 'A' * * 3. Pressing 'shift', then 'a' on the keyboard (caps lock is off): * keyPressed with key == CODED and keyCode == SHIFT * keyPressed with key == 'A' and keyCode == 'A' * keyTyped with key == 'A' and keyCode == 0 * keyReleased with key == 'A' and keyCode == 'A' * keyReleased with key == CODED and keyCode == SHIFT * * 4. Holding down the 'a' key. * The following will happen several times, * depending on your machine's "key repeat rate" settings: * keyPressed with key == 'a' and keyCode == 'A' * keyTyped with key == 'a' and keyCode == 0 * When you finally let go, you'll get: * keyReleased with key == 'a' and keyCode == 'A' * * 5. Pressing and releasing the 'shift' key * keyPressed with key == CODED and keyCode == SHIFT * keyReleased with key == CODED and keyCode == SHIFT * (note there is no keyTyped) * * 6. Pressing the tab key in an applet with Java 1.4 will * normally do nothing, but PApplet dynamically shuts * this behavior off if Java 1.4 is in use (tested 1.4.2_05 Windows). * Java 1.1 (Microsoft VM) passes the TAB key through normally. * Not tested on other platforms or for 1.3. */ public void keyPressed() { } /** * See keyPressed(). */ public void keyReleased() { } /** * Only called for "regular" keys like letters, * see keyPressed() for full documentation. */ public void keyTyped() { } // ------------------------------------------------------------ // i am focused man, and i'm not afraid of death. // and i'm going all out. i circle the vultures in a van // and i run the block. public void focusGained() { } public void focusGained(FocusEvent e) { focused = true; focusGained(); } public void focusLost() { } public void focusLost(FocusEvent e) { focused = false; focusLost(); } // ------------------------------------------------------------ // getting the time /** Get the number of milliseconds since the applet started. */ public int millis() { return (int) (System.currentTimeMillis() - millisOffset); } /** Seconds position of the current time. */ static public int second() { return Calendar.getInstance().get(Calendar.SECOND); } /** Minutes position of the current time. */ static public int minute() { return Calendar.getInstance().get(Calendar.MINUTE); } /** Hour position of the current time. */ static public int hour() { return Calendar.getInstance().get(Calendar.HOUR_OF_DAY); } /** * Get the current day of the month (1 through 31). * If you're looking for the day of the week (M-F or whatever) * or day of the year (1..365) then use java's Calendar.get() */ static public int day() { return Calendar.getInstance().get(Calendar.DAY_OF_MONTH); } /** * Get the current month in range 1 through 12. */ static public int month() { // months are number 0..11 so change to colloquial 1..12 return Calendar.getInstance().get(Calendar.MONTH) + 1; } /** * Get the current year. */ static public int year() { return Calendar.getInstance().get(Calendar.YEAR); } // ------------------------------------------------------------ // controlling time and playing god /** * I'm not sure if this is even helpful anymore. */ public void delay(int napTime) { if (frameCount == 0) return; if (napTime > 0) { try { Thread.sleep(napTime); } catch (InterruptedException e) { } } } /** * Get the current framerate. The initial value will be 10 fps, * and will be updated with each frame thereafter. The value is not * instantaneous (since that wouldn't be very useful since it would * jump around so much), but is instead averaged (integrated) * over roughly the last 10 frames. */ public float framerate() { if (fpsLastMillis != 0) { float elapsed = (float) (System.currentTimeMillis() - fpsLastMillis); if (elapsed != 0) { fps = (fps * 0.9f) + ((1.0f / (elapsed / 1000.0f)) * 0.1f); } } fpsLastMillis = System.currentTimeMillis(); return fps; } /** * Set a target framerate. This will cause delay() to be called * after each frame to allow for a specific rate to be set. */ public void framerate(float fpsTarget) { this.fpsTarget = fpsTarget; } // ------------------------------------------------------------ /** * Get a param from the web page, or (eventually) * from a properties file. */ public String param(String what) { if (online) { return getParameter(what); } else { System.err.println("param() only works inside a web browser"); } return null; } /** * Show status in the status bar of a web browser, or in the * System.out console. Eventually this might show status in the * p5 environment itself, rather than relying on the console. */ public void status(String what) { if (online) { showStatus(what); } else { System.out.println(what); // something more interesting? } } /** * Link to an external page without all the muss. Currently * only works for applets, but eventually should be implemented * for applications as well, using code from PdeBase. */ public void link(String here) { if (!online) { System.err.println("Can't open " + here); System.err.println("link() only works inside a web browser"); return; } try { getAppletContext().showDocument(new URL(here)); } catch (Exception e) { System.err.println("Could not open " + here); e.printStackTrace(); } } public void link(String here, String there) { if (!online) { System.err.println("Can't open " + here); System.err.println("link() only works inside a web browser"); return; } try { getAppletContext().showDocument(new URL(here), there); } catch (Exception e) { System.err.println("Could not open " + here); e.printStackTrace(); } } // ------------------------------------------------------------ /** * Function for an applet/application to kill itself and * display an error. Mostly this is here to be improved later. */ public void die(String what) { stop(); throw new RuntimeException(what); /* if (online) { System.err.println("i'm dead.. " + what); } else { System.err.println(what); System.exit(1); } */ } /** * Same as above but with an exception. Also needs work. */ public void die(String what, Exception e) { e.printStackTrace(); die(what); } /** * Explicitly exit the applet. Inserted as a call for static * mode apps, but is generally necessary because apps no longer * have draw/loop separation. */ public void exit() { stop(); // TODO if not running as an applet, do a System.exit() here } // ------------------------------------------------------------ // SCREEN GRABASS /** * grab an image of what's currently in the drawing area. * best used just before endFrame() at the end of your loop(). * only creates .tif or .tga images, so if extension isn't specified * it defaults to writing a tiff. */ public void saveFrame() { if (online) { System.err.println("Can't use saveFrame() when running in a browser."); return; } //File file = new File(folder, "screen-" + nf(frame, 4) + ".tif"); save(savePath("screen-" + nf(frameCount, 4) + ".tif")); //save("screen-" + nf(frame, 4) + ".tif"); } /** * Save the current frame as a .tif or .tga image. * * The String passed in can contain a series of # signs * that will be replaced with the screengrab number. * * i.e. saveFrame("blah-####.tif"); * // saves a numbered tiff image, replacing the * // # signs with zeros and the frame number */ public void saveFrame(String what) { if (online) { System.err.println("Can't use saveFrame() when running in a browser."); return; } int first = what.indexOf('#'); int last = what.lastIndexOf('#'); if (first == -1) { save(what); } else { String prefix = what.substring(0, first); int count = last - first + 1; String suffix = what.substring(last + 1); //File file = new File(folder, prefix + nf(frame, count) + suffix); // in case the user tries to make subdirs with the filename //new File(file.getParent()).mkdirs(); //save(file.getAbsolutePath()); save(savePath(prefix + nf(frameCount, count) + suffix)); } } // ------------------------------------------------------------ // CURSOR, base code contributed by amit pitaru int cursor_type = ARROW; // cursor type boolean cursor_visible = true; // cursor visibility flag PImage invisible_cursor; /** * Set the cursor type */ public void cursor(int _cursor_type) { //if (cursor_visible && _cursor_type != cursor_type) { setCursor(Cursor.getPredefinedCursor(_cursor_type)); //} cursor_visible = true; cursor_type = _cursor_type; } /** * Set a custom cursor to an image with a specific hotspot. * Only works with JDK 1.2 and later. * Currently seems to be broken on Java 1.4 for Mac OS X */ public void cursor(PImage image, int hotspotX, int hotspotY) { //if (!isOneTwoOrBetter()) { if (JDK_VERSION < 1.2) { System.err.println("cursor() error: Java 1.2 or higher is " + "required to set cursors"); System.err.println(" (You're using version " + JDK_VERSION_STRING + ")"); return; } // don't set this as cursor type, instead use cursor_type // to save the last cursor used in case cursor() is called //cursor_type = Cursor.CUSTOM_CURSOR; Image jimage = createImage(new MemoryImageSource(image.width, image.height, image.pixels, 0, image.width)); //Toolkit tk = Toolkit.getDefaultToolkit(); Point hotspot = new Point(hotspotX, hotspotY); try { Method mCustomCursor = Toolkit.class.getMethod("createCustomCursor", new Class[] { Image.class, Point.class, String.class, }); Cursor cursor = (Cursor)mCustomCursor.invoke(Toolkit.getDefaultToolkit(), new Object[] { jimage, hotspot, "no cursor" }); setCursor(cursor); cursor_visible = true; } catch (NoSuchMethodError e) { System.out.println("cursor() is not available on " + nf((float)JDK_VERSION, 1, 1)); } catch (IndexOutOfBoundsException e) { System.err.println("cursor() error: the hotspot " + hotspot + " is out of bounds for the given image."); } catch (Exception e) { System.err.println(e); } } /** * Show the cursor after noCursor() was called. * Notice that the program remembers the last set cursor type */ public void cursor() { // maybe should always set here? seems dangerous, since // it's likely that java will set the cursor to something // else on its own, and the applet will be stuck b/c bagel // thinks that the cursor is set to one particular thing if (!cursor_visible) { cursor_visible = true; setCursor(Cursor.getPredefinedCursor(cursor_type)); } } /** * Hide the cursor by creating a transparent image * and using it as a custom cursor. */ public void noCursor() { if (!cursor_visible) return; // don't hide if already hidden. if (invisible_cursor == null) { //invisible_cursor = new PImage(new int[32*32], 32, 32, RGBA); invisible_cursor = new PImage(new int[16*16], 16, 16, ARGB); } // was formerly 16x16, but the 0x0 was added by jdf as a fix // for macosx, which didn't wasn't honoring the invisible cursor cursor(invisible_cursor, 0, 0); cursor_visible = false; } // ------------------------------------------------------------ static public void print(byte what) { System.out.print(what); System.out.flush(); } static public void print(boolean what) { System.out.print(what); System.out.flush(); } static public void print(char what) { System.out.print(what); System.out.flush(); } static public void print(int what) { System.out.print(what); System.out.flush(); } static public void print(float what) { System.out.print(what); System.out.flush(); } static public void print(double what) { System.out.print(what); System.out.flush(); } static public void print(String what) { System.out.print(what); System.out.flush(); } static public void print(Object what) { System.out.print(what.toString()); System.out.flush(); } // static public void println() { System.out.println(); } // static public void println(byte what) { print(what); System.out.println(); } static public void println(boolean what) { print(what); System.out.println(); } static public void println(char what) { print(what); System.out.println(); } static public void println(int what) { print(what); System.out.println(); } static public void println(float what) { print(what); System.out.println(); } static public void println(double what) { print(what); System.out.println(); } static public void println(String what) { print(what); System.out.println(); } static public void println(Object what) { System.out.println(what.toString()); } // static public void printarr(byte what[]) { for (int i = 0; i < what.length; i++) System.out.println(what[i]); System.out.flush(); } static public void printarr(boolean what[]) { for (int i = 0; i < what.length; i++) System.out.println(what[i]); System.out.flush(); } static public void printarr(char what[]) { for (int i = 0; i < what.length; i++) System.out.println(what[i]); System.out.flush(); } static public void printarr(int what[]) { for (int i = 0; i < what.length; i++) System.out.println(what[i]); System.out.flush(); } static public void printarr(float what[]) { for (int i = 0; i < what.length; i++) System.out.println(what[i]); System.out.flush(); } static public void printarr(double what[]) { for (int i = 0; i < what.length; i++) System.out.println(what[i]); System.out.flush(); } static public void printarr(String what[]) { for (int i = 0; i < what.length; i++) System.out.println(what[i]); System.out.flush(); } static public void printarr(Object what[]) { for (int i = 0; i < what.length; i++) System.out.println(what[i]); System.out.flush(); } // /* public void printvar(String name) { try { Field field = getClass().getDeclaredField(name); println(name + " = " + field.get(this)); } catch (Exception e) { e.printStackTrace(); } } */ ////////////////////////////////////////////////////////////// // MATH // lots of convenience methods for math with floats. // doubles are overkill for processing applets, and casting // things all the time is annoying, thus the functions below. static public final float abs(float n) { return (n < 0) ? -n : n; } static public final int abs(int n) { return (n < 0) ? -n : n; } static public final float sq(float a) { return a*a; } static public final float sqrt(float a) { return (float)Math.sqrt(a); } static public final float log(float a) { return (float)Math.log(a); } static public final float exp(float a) { return (float)Math.exp(a); } static public final float pow(float a, float b) { return (float)Math.pow(a, b); } static public final float max(float a, float b) { return Math.max(a, b); } static public final float max(float a, float b, float c) { return Math.max(a, Math.max(b, c)); } static public final float min(float a, float b) { return Math.min(a, b); } static public final float min(float a, float b, float c) { return Math.min(a, Math.min(b, c)); } static public final float lerp(float a, float b, float amt) { return a + (b-a) * amt; } static public final float constrain(float amt, float low, float high) { return (amt < low) ? low : ((amt > high) ? high : amt); } static public final int max(int a, int b) { return (a > b) ? a : b; } static public final int max(int a, int b, int c) { return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); } static public final int min(int a, int b) { return (a < b) ? a : b; } static public final int min(int a, int b, int c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } static public final int constrain(int amt, int low, int high) { return (amt < low) ? low : ((amt > high) ? high : amt); } public final float sin(float angle) { if ((g != null) && (g.angleMode == DEGREES)) angle *= DEG_TO_RAD; return (float)Math.sin(angle); } public final float cos(float angle) { if ((g != null) && (g.angleMode == DEGREES)) angle *= DEG_TO_RAD; return (float)Math.cos(angle); } public final float tan(float angle) { if ((g != null) && (g.angleMode == DEGREES)) angle *= DEG_TO_RAD; return (float)Math.tan(angle); } public final float asin(float value) { return ((g != null) && (g.angleMode == DEGREES)) ? ((float)Math.asin(value) * RAD_TO_DEG) : (float)Math.asin(value); } public final float acos(float value) { return ((g != null) && (g.angleMode == DEGREES)) ? ((float)Math.acos(value) * RAD_TO_DEG) : (float)Math.acos(value); } public final float atan(float value) { return ((g != null) && (g.angleMode == DEGREES)) ? ((float)Math.atan(value) * RAD_TO_DEG) : (float)Math.atan(value); } public final float atan2(float a, float b) { return ((g != null) && (g.angleMode == DEGREES)) ? ((float)Math.atan2(a, b) * RAD_TO_DEG) : (float)Math.atan2(a, b); } static public final float degrees(float radians) { return radians * RAD_TO_DEG; } static public final float radians(float degrees) { return degrees * DEG_TO_RAD; } static public final float ceil(float what) { return (float) Math.ceil(what); } static public final float floor(float what) { return (float) Math.floor(what); } static public final float round(float what) { return Math.round(what); } static public final float mag(float a, float b) { return (float)Math.sqrt(a*a + b*b); } static public final float mag(float a, float b, float c) { return (float)Math.sqrt(a*a + b*b + c*c); } static public final float dist(float x1, float y1, float x2, float y2) { return sqrt(sq(x2-x1) + sq(y2-y1)); } static public final float dist(float x1, float y1, float z1, float x2, float y2, float z2) { return sqrt(sq(x2-x1) + sq(y2-y1) + sq(z2-z1)); } ////////////////////////////////////////////////////////////// // RANDOM NUMBERS Random internalRandom; /** * Return a random number in the range [0, howbig) * (0 is inclusive, non-inclusive of howbig) */ public final float random(float howbig) { // for some reason (rounding error?) Math.random() * 3 // can sometimes return '3' (once in ~30 million tries) // so a check was added to avoid the inclusion of 'howbig' // avoid an infinite loop if (howbig == 0) return 0; // internal random number object if (internalRandom == null) internalRandom = new Random(); float value = 0; do { //value = (float)Math.random() * howbig; value = internalRandom.nextFloat() * howbig; } while (value == howbig); return value; } /** * Return a random number in the range [howsmall, howbig) * (inclusive of howsmall, non-inclusive of howbig) * If howsmall is >= howbig, howsmall will be returned, * meaning that random(5, 5) will return 5 (useful) * and random(7, 4) will return 7 (not useful.. better idea?) */ public final float random(float howsmall, float howbig) { if (howsmall >= howbig) return howsmall; float diff = howbig - howsmall; return random(diff) + howsmall; } public final void randomSeed(long what) { // internal random number object if (internalRandom == null) internalRandom = new Random(); internalRandom.setSeed(what); } ////////////////////////////////////////////////////////////// // PERLIN NOISE // [toxi 040903] // octaves and amplitude amount per octave are now user controlled // via the noiseDetail() function. // [toxi 030902] // cleaned up code and now using bagel's cosine table to speed up // [toxi 030901] // implementation by the german demo group farbrausch // as used in their demo "art": http://www.farb-rausch.de/fr010src.zip static final int PERLIN_YWRAPB = 4; static final int PERLIN_YWRAP = 1<<PERLIN_YWRAPB; static final int PERLIN_ZWRAPB = 8; static final int PERLIN_ZWRAP = 1<<PERLIN_ZWRAPB; static final int PERLIN_SIZE = 4095; int perlin_octaves = 4; // default to medium smooth float perlin_amp_falloff = 0.5f; // 50% reduction/octave // [toxi 031112] // new vars needed due to recent change of cos table in PGraphics int perlin_TWOPI, perlin_PI; float[] perlin_cosTable; float perlin[]; Random perlinRandom; /** * Computes the Perlin noise function value at the point (x, y, z). * * @param x x coordinate * @param y y coordinate * @param z z coordinate * @return the noise function value at (x, y, z) */ public float noise(float x) { // is this legit? it's a dumb way to do it (but repair it later) return noise(x, 0f, 0f); } public float noise(float x, float y) { return noise(x, y, 0f); } public float noise(float x, float y, float z) { if (perlin == null) { if (perlinRandom == null) { perlinRandom = new Random(); } perlin = new float[PERLIN_SIZE + 1]; for (int i = 0; i < PERLIN_SIZE + 1; i++) { perlin[i] = perlinRandom.nextFloat(); //(float)Math.random(); } // [toxi 031112] // noise broke due to recent change of cos table in PGraphics // this will take care of it perlin_cosTable = PGraphics.cosLUT; perlin_TWOPI = perlin_PI = PGraphics.SINCOS_LENGTH; perlin_PI >>= 1; } if (x<0) x=-x; if (y<0) y=-y; if (z<0) z=-z; int xi=(int)x, yi=(int)y, zi=(int)z; float xf = (float)(x-xi); float yf = (float)(y-yi); float zf = (float)(z-zi); float rxf, ryf; float r=0; float ampl=0.5f; float n1,n2,n3; for (int i=0; i<perlin_octaves; i++) { int of=xi+(yi<<PERLIN_YWRAPB)+(zi<<PERLIN_ZWRAPB); rxf=noise_fsc(xf); ryf=noise_fsc(yf); n1 = perlin[of&PERLIN_SIZE]; n1 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n1); n2 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]; n2 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n2); n1 += ryf*(n2-n1); of += PERLIN_ZWRAP; n2 = perlin[of&PERLIN_SIZE]; n2 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n2); n3 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]; n3 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n3); n2 += ryf*(n3-n2); n1 += noise_fsc(zf)*(n2-n1); r += n1*ampl; ampl *= perlin_amp_falloff; xi<<=1; xf*=2; yi<<=1; yf*=2; zi<<=1; zf*=2; if (xf>=1.0f) { xi++; xf--; } if (yf>=1.0f) { yi++; yf--; } if (zf>=1.0f) { zi++; zf--; } } return r; } // [toxi 031112] // now adjusts to the size of the cosLUT used via // the new variables, defined above private float noise_fsc(float i) { // using bagel's cosine table instead return 0.5f*(1.0f-perlin_cosTable[(int)(i*perlin_PI)%perlin_TWOPI]); } // [toxi 040903] // make perlin noise quality user controlled to allow // for different levels of detail. lower values will produce // smoother results as higher octaves are surpressed public void noiseDetail(int lod) { if (lod>0) perlin_octaves=lod; } public void noiseDetail(int lod, float falloff) { if (lod>0) perlin_octaves=lod; if (falloff>0) perlin_amp_falloff=falloff; } public void noiseSeed(long what) { if (perlinRandom == null) perlinRandom = new Random(); perlinRandom.setSeed(what); } ////////////////////////////////////////////////////////////// // SOUND I/O public PSound loadSound(String filename) { if (PApplet.JDK_VERSION >= 1.3) { return new PSound2(this, openStream(filename)); } return new PSound(this, openStream(filename)); } ////////////////////////////////////////////////////////////// // IMAGE I/O public PImage loadImage(String filename) { if (filename.toLowerCase().endsWith(".tga")) { return loadImageTGA(filename); } return loadImage(filename, true); } // returns null if no image of that name is found public PImage loadImage(String filename, boolean force) { Image awtImage = Toolkit.getDefaultToolkit().createImage(loadBytes(filename)); MediaTracker tracker = new MediaTracker(this); tracker.addImage(awtImage, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { // don't bother, since this may be interrupted by draw // or noLoop or something like that //e.printStackTrace(); // non-fatal, right? } PImage image = new PImage(awtImage); // if it's a .gif image, test to see if it has transparency if (filename.toLowerCase().endsWith(".gif")) { for (int i = 0; i < image.pixels.length; i++) { // since transparency is often at corners, hopefully this // will find a non-transparent pixel quickly and exit if ((image.pixels[i] & 0xff000000) != 0xff000000) { image.format = ARGB; } } } return image; } /** * [toxi 040304] Targa bitmap loader for 24/32bit RGB(A) * * [fry] this could be optimized to not use loadBytes * which would help out memory situations with large images */ protected PImage loadImageTGA(String filename) { // load image file as byte array byte[] buffer = loadBytes(filename); // check if it's a TGA and has 8bits/colour channel if (buffer[2] == 2 && buffer[17] == 8) { // get image dimensions //int w=(b2i(buffer[13])<<8) + b2i(buffer[12]); int w = ((buffer[13] & 0xff) << 8) + (buffer[12] & 0xff); //int h=(b2i(buffer[15])<<8) + b2i(buffer[14]); int h = ((buffer[15] & 0xff) << 8) + (buffer[14] & 0xff); // check if image has alpha boolean hasAlpha=(buffer[16] == 32); // setup new image object PImage img = new PImage(w,h); img.format = (hasAlpha ? ARGB : RGB); // targa's are written upside down, so we need to parse it in reverse int index = (h-1) * w; // actual bitmap data starts at byte 18 int offset = 18; // read out line by line for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { img.pixels[index + x] = (buffer[offset++] & 0xff) | ((buffer[offset++] & 0xff) << 8) | ((buffer[offset++] & 0xff) << 16) | (hasAlpha ? ((buffer[offset++] & 0xff) << 24) : 0xff000000); } index -= w; } return img; } die("loadImage(): bad targa image format"); return null; } ////////////////////////////////////////////////////////////// // FONT I/O public PFont loadFont(String filename) { //if (g == null) { // just for good measure //die("loadFont() only be used inside setup() or draw()"); //} try { String lower = filename.toLowerCase(); InputStream input = openStream(filename); if (lower.endsWith(".vlw.gz")) { input = new GZIPInputStream(input); } else if (!lower.endsWith(".vlw")) { // this gets thrown down below throw new IOException("I don't know how to load a font named " + filename); } return new PFont(input); } catch (Exception e) { die("Could not load font " + filename + "\n" + "Make sure that the font has been copied\n" + "to the data folder of your sketch.", e); } return null; } ////////////////////////////////////////////////////////////// // FILE INPUT public File inputFile() { return inputFile("Select a file..."); } public File inputFile(String prompt) { Frame parentFrame = null; Component comp = getParent(); while (comp != null) { if (comp instanceof Frame) { parentFrame = (Frame) comp; break; } comp = comp.getParent(); } //System.out.println("found frame " + frame); if (parentFrame == null) parentFrame = new Frame(); FileDialog fd = new FileDialog(parentFrame, prompt, FileDialog.LOAD); fd.show(); String directory = fd.getDirectory(); String filename = fd.getFile(); if (filename == null) return null; return new File(directory, filename); } public File outputFile() { return outputFile("Save as..."); } public File outputFile(String prompt) { Frame parentFrame = null; Component comp = getParent(); //System.out.println(comp + " " + comp.getClass()); while (comp != null) { System.out.println(comp + " " + comp.getClass()); if (comp instanceof Frame) { parentFrame = (Frame) comp; break; } comp = comp.getParent(); } //System.out.println("found frame " + frame); if (parentFrame == null) parentFrame = new Frame(); FileDialog fd = new FileDialog(parentFrame, prompt, FileDialog.SAVE); fd.show(); String directory = fd.getDirectory(); String filename = fd.getFile(); if (filename == null) return null; return new File(directory, filename); } /** * I want to read lines from a file. I have RSI from typing these * eight lines of code so many times. */ public BufferedReader reader(String filename) { try { return reader(openStream(filename)); } catch (Exception e) { if (filename == null) { die("Filename passed to reader() was null", e); } else { die("Couldn't create a reader for " + filename, e); } } return null; } /** * I want to read lines from a file. And I'm still annoyed. */ public BufferedReader reader(File file) { try { return reader(new FileInputStream(file)); } catch (Exception e) { if (file == null) { die("File object passed to reader() was null", e); } else { die("Couldn't create a reader for " + file.getAbsolutePath(), e); } } return null; } /** * I want to read lines from a stream. If I have to type the * following lines any more I'm gonna send Sun my medical bills. */ public BufferedReader reader(InputStream input) { //try { InputStreamReader isr = new InputStreamReader(input); return new BufferedReader(isr); //} catch (IOException e) { //die("Couldn't create reader()", e); //} //return null; } /** * decode a gzip input stream */ public InputStream gzipInput(InputStream input) { try { return new GZIPInputStream(input); } catch (IOException e) { die("Problem with gzip input", e); } return null; } /** * decode a gzip output stream */ public OutputStream gzipOutput(OutputStream output) { try { return new GZIPOutputStream(output); } catch (IOException e) { die("Problem with gzip output", e); } return null; } /** * I want to print lines to a file. Why can't I? */ public PrintWriter writer(String filename) { try { return writer(new FileOutputStream(savePath(filename))); } catch (Exception e) { if (filename == null) { die("Filename passed to writer() was null", e); } else { die("Couldn't create a writer for " + filename, e); } } return null; } /** * I want to print lines to a file. I have RSI from typing these * eight lines of code so many times. */ public PrintWriter writer(File file) { try { return writer(new FileOutputStream(file)); } catch (Exception e) { if (file == null) { die("File object passed to writer() was null", e); } else { die("Couldn't create a writer for " + file.getAbsolutePath(), e); } } return null; } /** * I want to print lines to a file. Why am I always explaining myself? * It's the JavaSoft API engineers who need to explain themselves. */ public PrintWriter writer(OutputStream output) { //try { OutputStreamWriter osw = new OutputStreamWriter(output); return new PrintWriter(osw); //} catch (IOException e) { //die("Couldn't create writer()", e); //} } static public InputStream openStream(File file) { try { return new FileInputStream(file); } catch (IOException e) { e.printStackTrace(); if (file == null) { throw new RuntimeException("File passed to openStream() was null"); } else { throw new RuntimeException("Couldn't openStream() for " + file.getAbsolutePath()); } } //return null; } public InputStream openStream(String filename) { try { InputStream stream = null; if (filename.startsWith("http://")) { try { URL url = new URL(filename); stream = url.openStream(); return stream; } catch (MalformedURLException e) { e.printStackTrace(); return null; } } stream = getClass().getResourceAsStream(filename); if (stream != null) return stream; stream = getClass().getResourceAsStream("data/" + filename); if (stream != null) return stream; try { try { String location = folder + File.separator + "data"; File file = new File(location, filename); stream = new FileInputStream(file); if (stream != null) return stream; } catch (Exception e) { } // ignored try { File file = new File(folder, filename); stream = new FileInputStream(file); if (stream != null) return stream; } catch (Exception e) { } // ignored try { stream = new FileInputStream(new File("data", filename)); if (stream != null) return stream; } catch (IOException e2) { } try { stream = new FileInputStream(filename); if (stream != null) return stream; } catch (IOException e1) { } } catch (SecurityException se) { } // online, whups if (stream == null) { throw new IOException("openStream() could not open " + filename); } } catch (Exception e) { die(e.getMessage(), e); } return null; // #$(*@ compiler } public byte[] loadBytes(String filename) { return loadBytes(openStream(filename)); } public byte[] loadBytes(InputStream input) { try { BufferedInputStream bis = new BufferedInputStream(input); ByteArrayOutputStream out = new ByteArrayOutputStream(); int c = bis.read(); while (c != -1) { out.write(c); c = bis.read(); } return out.toByteArray(); } catch (IOException e) { die("Couldn't load bytes from stream", e); } return null; } static public String[] loadStrings(File file) { InputStream is = openStream(file); if (is != null) return loadStrings(is); //die("Couldn't open " + file.getAbsolutePath()); return null; } public String[] loadStrings(String filename) { InputStream is = openStream(filename); if (is != null) return loadStrings(is); die("Couldn't open " + filename); return null; } static public String[] loadStrings(InputStream input) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String lines[] = new String[100]; int lineCount = 0; String line = null; while ((line = reader.readLine()) != null) { if (lineCount == lines.length) { String temp[] = new String[lineCount << 1]; System.arraycopy(lines, 0, temp, 0, lineCount); lines = temp; } lines[lineCount++] = line; } reader.close(); if (lineCount == lines.length) { return lines; } // resize array to appropraite amount for these lines String output[] = new String[lineCount]; System.arraycopy(lines, 0, output, 0, lineCount); return output; } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Error inside loadStrings()"); } //return null; } ////////////////////////////////////////////////////////////// // FILE OUTPUT /** * Saves bytes to a file to inside the sketch folder. * The filename can be a relative path, i.e. "poo/bytefun.txt" * would save to a file named "bytefun.txt" to a subfolder * called 'poo' inside the sketch folder. If the in-between * subfolders don't exist, they'll be created. */ public void saveBytes(String filename, byte buffer[]) { try { String location = savePath(filename); FileOutputStream fos = new FileOutputStream(location); saveBytes(fos, buffer); fos.close(); } catch (IOException e) { System.err.println("error saving bytes to " + filename); e.printStackTrace(); } } /** * Saves bytes to a specific File location specified by the user. */ public void saveBytes(File file, byte buffer[]) { try { String filename = file.getAbsolutePath(); createPath(filename); FileOutputStream fos = new FileOutputStream(file); saveBytes(fos, buffer); fos.close(); } catch (IOException e) { System.err.println("error saving bytes to " + file); e.printStackTrace(); } } /** * Spews a buffer of bytes to an OutputStream. */ public void saveBytes(OutputStream output, byte buffer[]) { try { //BufferedOutputStream bos = new BufferedOutputStream(output); output.write(buffer); output.flush(); } catch (IOException e) { System.err.println("error while saving bytes"); e.printStackTrace(); } } // public void saveStrings(String filename, String strings[]) { try { String location = savePath(filename); FileOutputStream fos = new FileOutputStream(location); saveStrings(fos, strings); fos.close(); } catch (IOException e) { System.err.println("error while saving strings"); e.printStackTrace(); } } public void saveStrings(File file, String strings[]) { try { String location = file.getAbsolutePath(); createPath(location); FileOutputStream fos = new FileOutputStream(location); saveStrings(fos, strings); fos.close(); } catch (IOException e) { System.err.println("error while saving strings"); e.printStackTrace(); } } public void saveStrings(OutputStream output, String strings[]) { PrintWriter writer = new PrintWriter(new OutputStreamWriter(output)); for (int i = 0; i < strings.length; i++) { writer.println(strings[i]); } writer.flush(); } // /** * Figures out the full path for where to save things. * Can be used by external libraries to save to the sketch folder. */ public String savePath(String where) { String filename = folder + File.separator + where; createPath(filename); return filename; } /** * Creates in-between folders if they don't already exist. */ static public void createPath(String filename) { File file = new File(filename); String parent = file.getParent(); if (parent != null) { File unit = new File(parent); if (!unit.exists()) unit.mkdirs(); } } ////////////////////////////////////////////////////////////// // SORT int sort_mode; static final int BYTES = 1; static final int CHARS = 2; static final int INTS = 3; static final int FLOATS = 4; static final int STRINGS = 5; byte sort_bytes[]; char sort_chars[]; int sort_ints[]; float sort_floats[]; String sort_strings[]; public byte[] sort(byte what[]) { return sort(what, what.length); } public char[] sort(char what[]) { return sort(what, what.length); } public int[] sort(int what[]) { return sort(what, what.length); } public float[] sort(float what[]) { return sort(what, what.length); } public String[] sort(String what[]) { return sort(what, what.length); } // public byte[] sort(byte what[], int count) { if (count == 0) return null; sort_mode = BYTES; sort_bytes = new byte[count]; System.arraycopy(what, 0, sort_bytes, 0, count); sort_internal(0, count-1); return sort_bytes; } public char[] sort(char what[], int count) { if (count == 0) return null; sort_mode = CHARS; sort_chars = new char[count]; System.arraycopy(what, 0, sort_chars, 0, count); sort_internal(0, count-1); return sort_chars; } public int[] sort(int what[], int count) { if (count == 0) return null; sort_mode = INTS; sort_ints = new int[count]; System.arraycopy(what, 0, sort_ints, 0, count); sort_internal(0, count-1); return sort_ints; } public float[] sort(float what[], int count) { if (count == 0) return null; sort_mode = FLOATS; sort_floats = new float[count]; System.arraycopy(what, 0, sort_floats, 0, count); sort_internal(0, count-1); return sort_floats; } public String[] sort(String what[], int count) { if (count == 0) return null; sort_mode = STRINGS; sort_strings = new String[count]; System.arraycopy(what, 0, sort_strings, 0, count); sort_internal(0, count-1); return sort_strings; } // protected void sort_internal(int i, int j) { int pivotIndex = (i+j)/2; sort_swap(pivotIndex, j); int k = sort_partition(i-1, j); sort_swap(k, j); if ((k-i) > 1) sort_internal(i, k-1); if ((j-k) > 1) sort_internal(k+1, j); } protected int sort_partition(int left, int right) { int pivot = right; do { while (sort_compare(++left, pivot) < 0) { } while ((right != 0) && (sort_compare(--right, pivot) > 0)) { } sort_swap(left, right); } while (left < right); sort_swap(left, right); return left; } protected void sort_swap(int a, int b) { switch (sort_mode) { case BYTES: byte btemp = sort_bytes[a]; sort_bytes[a] = sort_bytes[b]; sort_bytes[b] = btemp; break; case CHARS: char ctemp = sort_chars[a]; sort_chars[a] = sort_chars[b]; sort_chars[b] = ctemp; break; case INTS: int itemp = sort_ints[a]; sort_ints[a] = sort_ints[b]; sort_ints[b] = itemp; break; case FLOATS: float ftemp = sort_floats[a]; sort_floats[a] = sort_floats[b]; sort_floats[b] = ftemp; break; case STRINGS: String stemp = sort_strings[a]; sort_strings[a] = sort_strings[b]; sort_strings[b] = stemp; break; } } protected int sort_compare(int a, int b) { switch (sort_mode) { case BYTES: return sort_bytes[a] - sort_bytes[b]; //if (sort_bytes[a] < sort_bytes[b]) return -1; //return (sort_bytes[a] == sort_bytes[b]) ? 0 : 1; case CHARS: return sort_chars[a] - sort_chars[b]; //if (sort_chars[a] < sort_chars[b]) return -1; //return (sort_chars[a] == sort_chars[b]) ? 0 : 1; case INTS: return sort_ints[a] - sort_ints[b]; //if (sort_ints[a] < sort_ints[b]) return -1; //return (sort_ints[a] == sort_ints[b]) ? 0 : 1; case FLOATS: if (sort_floats[a] < sort_floats[b]) return -1; return (sort_floats[a] == sort_floats[b]) ? 0 : 1; case STRINGS: return sort_strings[a].compareTo(sort_strings[b]); } return 0; } ////////////////////////////////////////////////////////////// // ARRAY UTILITIES static public boolean[] expand(boolean list[]) { return expand(list, list.length << 1); } static public boolean[] expand(boolean list[], int newSize) { boolean temp[] = new boolean[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public byte[] expand(byte list[]) { return expand(list, list.length << 1); } static public byte[] expand(byte list[], int newSize) { byte temp[] = new byte[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public char[] expand(char list[]) { return expand(list, list.length << 1); } static public char[] expand(char list[], int newSize) { char temp[] = new char[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public int[] expand(int list[]) { return expand(list, list.length << 1); } static public int[] expand(int list[], int newSize) { int temp[] = new int[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public float[] expand(float list[]) { return expand(list, list.length << 1); } static public float[] expand(float list[], int newSize) { float temp[] = new float[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public String[] expand(String list[]) { return expand(list, list.length << 1); } static public String[] expand(String list[], int newSize) { String temp[] = new String[newSize]; // in case the new size is smaller than list.length System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } // static public boolean[] contract(boolean list[], int newSize) { return expand(list, newSize); } static public byte[] contract(byte list[], int newSize) { return expand(list, newSize); } static public char[] contract(char list[], int newSize) { return expand(list, newSize); } static public int[] contract(int list[], int newSize) { return expand(list, newSize); } static public float[] contract(float list[], int newSize) { return expand(list, newSize); } static public String[] contract(String list[], int newSize) { return expand(list, newSize); } // static public byte[] append(byte b[], byte value) { b = expand(b, b.length + 1); b[b.length-1] = value; return b; } static public char[] append(char b[], char value) { b = expand(b, b.length + 1); b[b.length-1] = value; return b; } static public int[] append(int b[], int value) { b = expand(b, b.length + 1); b[b.length-1] = value; return b; } static public float[] append(float b[], float value) { b = expand(b, b.length + 1); b[b.length-1] = value; return b; } static public String[] append(String b[], String value) { b = expand(b, b.length + 1); b[b.length-1] = value; return b; } // static public boolean[] shorten(boolean list[]) { return contract(list, list.length-1); } static public byte[] shorten(byte list[]) { return contract(list, list.length-1); } static public char[] shorten(char list[]) { return contract(list, list.length-1); } static public int[] shorten(int list[]) { return contract(list, list.length-1); } static public float[] shorten(float list[]) { return contract(list, list.length-1); } static public String[] shorten(String list[]) { return contract(list, list.length-1); } // static final public boolean[] splice(boolean list[], boolean v, int index) { boolean outgoing[] = new boolean[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = v; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public boolean[] splice(boolean list[], boolean v[], int index) { boolean outgoing[] = new boolean[list.length + v.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, v.length); System.arraycopy(list, index, outgoing, index + v.length, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte v, int index) { byte outgoing[] = new byte[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = v; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte v[], int index) { byte outgoing[] = new byte[list.length + v.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, v.length); System.arraycopy(list, index, outgoing, index + v.length, list.length - index); return outgoing; } static final public char[] splice(char list[], char v, int index) { char outgoing[] = new char[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = v; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public char[] splice(char list[], char v[], int index) { char outgoing[] = new char[list.length + v.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, v.length); System.arraycopy(list, index, outgoing, index + v.length, list.length - index); return outgoing; } static final public int[] splice(int list[], int v, int index) { int outgoing[] = new int[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = v; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public int[] splice(int list[], int v[], int index) { int outgoing[] = new int[list.length + v.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, v.length); System.arraycopy(list, index, outgoing, index + v.length, list.length - index); return outgoing; } static final public float[] splice(float list[], float v, int index) { float outgoing[] = new float[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = v; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public float[] splice(float list[], float v[], int index) { float outgoing[] = new float[list.length + v.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, v.length); System.arraycopy(list, index, outgoing, index + v.length, list.length - index); return outgoing; } static final public String[] splice(String list[], String v, int index) { String outgoing[] = new String[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = v; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public String[] splice(String list[], String v[], int index) { String outgoing[] = new String[list.length + v.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, v.length); System.arraycopy(list, index, outgoing, index + v.length, list.length - index); return outgoing; } // static public int[] subset(int list[], int start) { return subset(list, start, list.length - start); } static public int[] subset(int list[], int start, int count) { int output[] = new int[count]; System.arraycopy(list, start, output, 0, count); return output; } static public float[] subset(float list[], int start) { return subset(list, start, list.length - start); } static public float[] subset(float list[], int start, int count) { float output[] = new float[count]; System.arraycopy(list, start, output, 0, count); return output; } static public String[] subset(String list[], int start) { return subset(list, start, list.length - start); } static public String[] subset(String list[], int start, int count) { String output[] = new String[count]; System.arraycopy(list, start, output, 0, count); return output; } // static public boolean[] concat(boolean a[], boolean b[]) { boolean c[] = new boolean[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public byte[] concat(byte a[], byte b[]) { byte c[] = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public char[] concat(char a[], char b[]) { char c[] = new char[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public int[] concat(int a[], int b[]) { int c[] = new int[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public float[] concat(float a[], float b[]) { float c[] = new float[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public String[] concat(String a[], String b[]) { String c[] = new String[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } // static public boolean[] reverse(boolean list[]) { boolean outgoing[] = new boolean[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public byte[] reverse(byte list[]) { byte outgoing[] = new byte[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public char[] reverse(char list[]) { char outgoing[] = new char[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public int[] reverse(int list[]) { int outgoing[] = new int[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public float[] reverse(float list[]) { float outgoing[] = new float[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public String[] reverse(String list[]) { String outgoing[] = new String[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } ////////////////////////////////////////////////////////////// // STRINGS /** * Remove whitespace characters from the beginning and ending * of a String. Works like String.trim() but includes the * unicode nbsp character as well. */ static public String trim(String str) { return str.replace('\u00A0', ' ').trim(); /* int left = 0; int right = str.length() - 1; while ((left <= right) && (WHITESPACE.indexOf(str.charAt(left)) != -1)) left++; if (left == right) return ""; while (WHITESPACE.indexOf(str.charAt(right)) != -1) --right; return str.substring(left, right-left+1); */ } /** * Join an array of Strings together as a single String, * separated by the whatever's passed in for the separator. * * To use this on numbers, first pass the array to nf() or nfs() * to get a list of String objects, then use join on that. * * e.g. String stuff[] = { "apple", "bear", "cat" }; * String list = join(stuff, ", "); * // list is now "apple, bear, cat" */ static public String join(String str[], String separator) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < str.length; i++) { if (i != 0) buffer.append(separator); buffer.append(str[i]); } return buffer.toString(); } /** * Split the provided String at wherever whitespace occurs. * Multiple whitespace (extra spaces or tabs or whatever) * between items will count as a single break. * * The whitespace characters are "\t\n\r\f", which are the defaults * for java.util.StringTokenizer, plus the unicode non-breaking space * character, which is found commonly on files created by or used * in conjunction with Mac OS X (character 160, or 0x00A0 in hex). * * i.e. split("a b") -> { "a", "b" } * split("a b") -> { "a", "b" } * split("a\tb") -> { "a", "b" } * split("a \t b ") -> { "a", "b" } */ static public String[] split(String what) { return split(what, WHITESPACE); } /** * Splits a string into pieces, using any of the chars in the * String 'delim' as separator characters. For instance, * in addition to white space, you might want to treat commas * as a separator. The delimeter characters won't appear in * the returned String array. * * i.e. split("a, b", " ,") -> { "a", "b" } * * To include all the whitespace possibilities, use the variable * WHITESPACE, found in PConstants: * * i.e. split("a | b", WHITESPACE + "|"); -> { "a", "b" } */ static public String[] split(String what, String delim) { StringTokenizer toker = new StringTokenizer(what, delim); String pieces[] = new String[toker.countTokens()]; int index = 0; while (toker.hasMoreTokens()) { pieces[index++] = toker.nextToken(); } return pieces; } /** * Split a string into pieces along a specific character. * Most commonly used to break up a String along tab characters. * * This operates differently than the others, where the * single delimeter is the only breaking point, and consecutive * delimeters will produce an empty string (""). This way, * one can split on tab characters, but maintain the column * alignments (of say an excel file) where there are empty columns. */ static public String[] split(String what, char delim) { // do this so that the exception occurs inside the user's // program, rather than appearing to be a bug inside split() if (what == null) return null; //return split(what, String.valueOf(delim)); // huh char chars[] = what.toCharArray(); int splitCount = 0; //1; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) splitCount++; } // make sure that there is something in the input string //if (chars.length > 0) { // if the last char is a delimeter, get rid of it.. //if (chars[chars.length-1] == delim) splitCount--; // on second thought, i don't agree with this, will disable //} if (splitCount == 0) { String splits[] = new String[1]; splits[0] = new String(what); return splits; } //int pieceCount = splitCount + 1; String splits[] = new String[splitCount + 1]; int splitIndex = 0; int startIndex = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) { splits[splitIndex++] = new String(chars, startIndex, i-startIndex); startIndex = i + 1; } } //if (startIndex != chars.length) { splits[splitIndex] = new String(chars, startIndex, chars.length-startIndex); //} return splits; } ////////////////////////////////////////////////////////////// // CASTING FUNCTIONS, INSERTED BY PREPROC static final public boolean toBoolean(char what) { return ((what == 't') || (what == 'T') || (what == '1')); } static final public boolean toBoolean(int what) { // this will cover byte return (what != 0); } static final public boolean toBoolean(float what) { return (what != 0); } static final public boolean toBoolean(String what) { return new Boolean(what).booleanValue(); } // static final public boolean[] toBoolean(char what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = ((what[i] == 't') || (what[i] == 'T') || (what[i] == '1')); } return outgoing; } static final public boolean[] toBoolean(byte what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } static final public boolean[] toBoolean(float what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } static final public boolean[] toBoolean(String what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = new Boolean(what[i]).booleanValue(); } return outgoing; } // static final public byte toByte(boolean what) { return what ? (byte)1 : 0; } static final public byte toByte(char what) { return (byte) what; } static final public byte toByte(int what) { return (byte) what; } static final public byte toByte(float what) { // nonsensical return (byte) what; } static final public byte[] toByte(String what) { // note: array[] return what.getBytes(); } // static final public byte[] toByte(boolean what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? (byte)1 : 0; } return outgoing; } static final public byte[] toByte(char what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] toByte(int what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] toByte(float what[]) { // nonsensical byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[][] toByte(String what[]) { // note: array[][] byte outgoing[][] = new byte[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].getBytes(); } return outgoing; } // static final public char toChar(boolean what) { // 0/1 or T/F ? return what ? 't' : 'f'; } static final public char toChar(byte what) { return (char) (what & 0xff); } static final public char toChar(int what) { return (char) what; } static final public char toChar(float what) { // nonsensical return (char) what; } static final public char[] toChar(String what) { // note: array[] return what.toCharArray(); } // static final public char[] toChar(boolean what[]) { // 0/1 or T/F ? char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? 't' : 'f'; } return outgoing; } static final public char[] toChar(int what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } static final public char[] toChar(byte what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) (what[i] & 0xff); } return outgoing; } static final public char[] toChar(float what[]) { // nonsensical char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } static final public char[][] toChar(String what[]) { // note: array[][] char outgoing[][] = new char[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].toCharArray(); } return outgoing; } // static final public int toInt(boolean what) { return what ? 1 : 0; } static final public int toInt(byte what) { // note this unsigns return what & 0xff; } static final public int toInt(char what) { return what; } static final public int toInt(float what) { return (int) what; } static final public int toInt(String what) { try { return Integer.parseInt(what); } catch (NumberFormatException e) { } return 0; } static final public int toInt(String what, int otherwise) { try { return Integer.parseInt(what); } catch (NumberFormatException e) { } return otherwise; } // static final public int[] toInt(boolean what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i] ? 1 : 0; } return list; } static final public int[] toInt(byte what[]) { // note this unsigns int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = (what[i] & 0xff); } return list; } static final public int[] toInt(char what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i]; } return list; } static public int[] toInt(float what[]) { int inties[] = new int[what.length]; for (int i = 0; i < what.length; i++) { inties[i] = (int)what[i]; } return inties; } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, it will be set to zero. * * String s[] = { "1", "300", "44" }; * int numbers[] = toInt(s); * * numbers will contain { 1, 300, 44 } */ static public int[] toInt(String what[]) { return toInt(what, 0); } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, its entry in the * array will be set to the value of the "missing" parameter. * * String s[] = { "1", "300", "apple", "44" }; * int numbers[] = toInt(s, 9999); * * numbers will contain { 1, 300, 9999, 44 } */ static public int[] toInt(String what[], int missing) { int output[] = new int[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = Integer.parseInt(what[i]); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // static final public float toFloat(boolean what) { return what ? 1 : 0; } static final public float toFloat(int what) { return (float)what; } static final public float toFloat(String what) { //return new Float(what).floatValue(); return toFloat(what, Float.NaN); } static final public float toFloat(String what, float otherwise) { try { return new Float(what).floatValue(); } catch (NumberFormatException e) { } return otherwise; } // static final public float[] toFloat(boolean what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i] ? 1 : 0; } return floaties; } static final public float[] toFloat(char what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = (char) what[i]; } return floaties; } static final public float[] toFloat(int what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] toFloat(String what[]) { return toFloat(what, 0); } static final public float[] toFloat(String what[], float missing) { float output[] = new float[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = new Float(what[i]).floatValue(); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // static final public String str(boolean x) { return String.valueOf(x); } static final public String str(byte x) { return String.valueOf(x); } static final public String str(char x) { return String.valueOf(x); } static final public String str(short x) { return String.valueOf(x); } static final public String str(int x) { return String.valueOf(x); } static final public String str(float x) { return String.valueOf(x); } static final public String str(long x) { return String.valueOf(x); } static final public String str(double x) { return String.valueOf(x); } // static final public String[] str(boolean x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x); return s; } static final public String[] str(byte x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x); return s; } static final public String[] str(char x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x); return s; } static final public String[] str(short x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x); return s; } static final public String[] str(int x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x); return s; } static final public String[] str(float x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x); return s; } static final public String[] str(long x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x); return s; } static final public String[] str(double x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x); return s; } ////////////////////////////////////////////////////////////// // INT NUMBER FORMATTING /** * Integer number formatter. */ static private NumberFormat int_nf; static private int int_nf_digits; static public String[] nf(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], digits); } return formatted; } static public String nf(int num, int digits) { if ((int_nf != null) && (int_nf_digits == digits)) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(false); // no commas int_nf.setMinimumIntegerDigits(digits); int_nf_digits = digits; return int_nf.format(num); } /** * number format signed (or space) * Formats a number but leaves a blank space in the front * when it's positive so that it can be properly aligned with * numbers that have a negative sign in front of them. */ static public String nfs(int num, int digits) { return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits)); } static public String[] nfs(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], digits); } return formatted; } // /** * number format positive (or plus) * Formats a number, always placing a - or + sign * in the front when it's negative or positive. */ static public String nfp(int num, int digits) { return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits)); } static public String[] nfp(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], digits); } return formatted; } ////////////////////////////////////////////////////////////// // FLOAT NUMBER FORMATTING static private NumberFormat float_nf; static private int float_nf_left, float_nf_right; static public String[] nf(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], left, right); } return formatted; } static public String nf(float num, int left, int right) { if ((float_nf != null) && (float_nf_left == left) && (float_nf_right == right)) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(false); // no commas if (left != 0) float_nf.setMinimumIntegerDigits(left); if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = left; float_nf_right = right; return float_nf.format(num); } /** * Number formatter that takes into account whether the number * has a sign (positive, negative, etc) in front of it. */ static public String[] nfs(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], left, right); } return formatted; } static public String nfs(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right)); } static public String[] nfp(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], left, right); } return formatted; } static public String nfp(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right)); } ////////////////////////////////////////////////////////////// // HEX/BINARY CONVERSION static final public String hex(byte what) { return hex(what, 2); } static final public String hex(char what) { return hex(what, 4); } static final public String hex(int what) { return hex(what, 8); } static final public String hex(int what, int digits) { String stuff = Integer.toHexString(what).toUpperCase(); int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { return "00000000".substring(8 - (digits-length)) + stuff; } return stuff; } static final int unhex(String what) { return Integer.parseInt(what, 16); } // /** * Returns a String that contains the binary value of a byte. * The returned value will always have 8 digits. */ static final public String binary(byte what) { return binary(what, 8); } /** * Returns a String that contains the binary value of a char. * The returned value will always have 16 digits because chars * are two bytes long. */ static final public String binary(char what) { return binary(what, 16); } /** * Returns a String that contains the binary value of an int. * The length depends on the size of the number itself. * An int can be up to 32 binary digits, but that seems like * overkill for almost any situation, so this function just * auto-sizes. If you want a specific number of digits (like all 32) * use binary(int what, int digits) to specify how many digits. */ static final public String binary(int what) { return Integer.toBinaryString(what); //return binary(what, 32); } /** * Returns a String that contains the binary value of an int. * The digits parameter determines how many digits will be used. */ static final public String binary(int what, int digits) { String stuff = Integer.toBinaryString(what); int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { int offset = 32 - (digits-length); return "00000000000000000000000000000000".substring(offset) + stuff; } return stuff; } /** * Unpack a binary String into an int. * i.e. unbinary("00001000") would return 8. */ static final int unbinary(String what) { return Integer.parseInt(what, 2); } ////////////////////////////////////////////////////////////// // COLOR FUNCTIONS // moved here so that they can work without // the graphics actually being instantiated (outside setup) public final int color(int gray) { if (g == null) { if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(gray); } public final int color(float fgray) { if (g == null) { int gray = (int) fgray; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray); } public final int color(int gray, int alpha) { if (g == null) { if (gray > 255) gray = 255; else if (gray < 0) gray = 0; if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; return (alpha << 24) | (gray << 16) | (gray << 8) | gray; } return g.color(gray, alpha); } public final int color(float fgray, float falpha) { if (g == null) { int gray = (int) fgray; int alpha = (int) falpha; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray, falpha); } public final int color(int x, int y, int z) { if (g == null) { if (x > 255) x = 255; else if (x < 0) x = 0; if (y > 255) y = 255; else if (y < 0) y = 0; if (z > 255) z = 255; else if (z < 0) z = 0; return 0xff000000 | (x << 16) | (y << 8) | z; } return g.color(x, y, z); } public final int color(float x, float y, float z) { if (g == null) { if (x > 255) x = 255; else if (x < 0) x = 0; if (y > 255) y = 255; else if (y < 0) y = 0; if (z > 255) z = 255; else if (z < 0) z = 0; return 0xff000000 | ((int)x << 16) | ((int)y << 8) | (int)z; } return g.color(x, y, z); } public final int color(int x, int y, int z, int a) { if (g == null) { if (a > 255) a = 255; else if (a < 0) a = 0; if (x > 255) x = 255; else if (x < 0) x = 0; if (y > 255) y = 255; else if (y < 0) y = 0; if (z > 255) z = 255; else if (z < 0) z = 0; return (a << 24) | (x << 16) | (y << 8) | z; } return g.color(x, y, z, a); } public final int color(float x, float y, float z, float a) { if (g == null) { if (a > 255) a = 255; else if (a < 0) a = 0; if (x > 255) x = 255; else if (x < 0) x = 0; if (y > 255) y = 255; else if (y < 0) y = 0; if (z > 255) z = 255; else if (z < 0) z = 0; return ((int)a << 24) | ((int)x << 16) | ((int)y << 8) | (int)z; } return g.color(x, y, z, a); } ////////////////////////////////////////////////////////////// // MAIN private static class WorkerVar { private Thread thread; WorkerVar(Thread t) { thread = t; } synchronized Thread get() { return thread; } synchronized void clear() { thread = null; } } class Worker { private Object value; private WorkerVar workerVar; protected synchronized Object getValue() { return value; } private synchronized void setValue(Object x) { value = x; } public Object construct() { try { int anything = System.in.read(); if (anything == EXTERNAL_STOP) { // adding this for 0073.. need to stop libraries // when the stop button is hit. PApplet.this.stop(); finished = true; } } catch (IOException e) { finished = true; } try { Thread.sleep(250); //Thread.sleep(100); // kick up latency for 0075? } catch (InterruptedException e) { } return null; } // removing this from SwingWorker //public void finished() { } public void interrupt() { Thread t = workerVar.get(); if (t != null) { t.interrupt(); } workerVar.clear(); } public Object get() { while (true) { Thread t = workerVar.get(); if (t == null) { return getValue(); } try { t.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // propagate return null; } } } public Worker() { // removing this from SwingWorker //final Runnable doFinished = new Runnable() { // public void run() { finished(); } // }; Runnable doConstruct = new Runnable() { public void run() { try { setValue(construct()); } finally { workerVar.clear(); } // removing this from SwingWorker to avoid swing //javax.swing.SwingUtilities.invokeLater(doFinished); } }; Thread t = new Thread(doConstruct); workerVar = new WorkerVar(t); } public void start() { Thread t = workerVar.get(); if (t != null) t.start(); } } public void setupExternal(Frame parentFrame) { //externalRuntime = true; /* javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { //while ((Thread.currentThread() == this) && !finished) { try { // is this what's causing all the trouble? int anything = System.in.read(); if (anything == EXTERNAL_STOP) { //System.out.println("********** STOPPING"); // adding this for 0073.. need to stop libraries // when the stop button is hit. v PApplet.this.stop(); //System.out.println("********** REALLY"); finished = true; } } catch (IOException e) { // not tested (needed?) but seems correct //stop(); finished = true; //thread = null; } try { Thread.sleep(250); //Thread.sleep(100); // kick up latency for 0075? } catch (InterruptedException e) { } } }); */ /* Thread ethread = new Thread() { //new Runnable() { public void run() { // this fixes the "code folder hanging bug" (mostly) setPriority(Thread.MIN_PRIORITY); */ final Worker worker = new Worker(); /* final SwingWorker worker = new SwingWorker() { public Object construct() { //while ((Thread.currentThread() == this) && !finished) { try { // is this what's causing all the trouble? int anything = System.in.read(); if (anything == EXTERNAL_STOP) { //System.out.println("********** STOPPING"); // adding this for 0073.. need to stop libraries // when the stop button is hit. PApplet.this.stop(); //System.out.println("********** REALLY"); finished = true; } } catch (IOException e) { // not tested (needed?) but seems correct //stop(); finished = true; //thread = null; } try { Thread.sleep(250); //Thread.sleep(100); // kick up latency for 0075? } catch (InterruptedException e) { } return null; } }; //ethread.start(); */ parentFrame.addComponentListener(new ComponentAdapter() { public void componentMoved(ComponentEvent e) { //System.out.println(e); Point where = ((Frame) e.getSource()).getLocation(); //System.out.println(e); System.err.println(PApplet.EXTERNAL_MOVE + " " + where.x + " " + where.y); System.err.flush(); } }); parentFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.err.println(PApplet.EXTERNAL_QUIT); System.err.flush(); // important System.exit(0); } }); } static public void main(String args[]) { if (args.length < 1) { System.err.println("error: PApplet <appletname>"); System.exit(1); } try { boolean external = false; int location[] = null; //int locationX, locationY; boolean exactLocation = false; String folder = System.getProperty("user.dir"); //if (args[0].indexOf(EXTERNAL_FLAG) == 0) external = true; String name = null; int initialWidth = PApplet.DEFAULT_WIDTH; int initialHeight = PApplet.DEFAULT_HEIGHT; int argIndex = 0; while (argIndex < args.length) { if (args[argIndex].indexOf(EXT_LOCATION) == 0) { external = true; String locationStr = args[argIndex].substring(EXT_LOCATION.length()); location = toInt(split(locationStr, ',')); //locationX = location[0] - 20; //locationY = location[1]; } else if (args[argIndex].indexOf(EXT_EXACT_LOCATION) == 0) { external = true; String locationStr = args[argIndex].substring(EXT_EXACT_LOCATION.length()); location = toInt(split(locationStr, ',')); exactLocation = true; } else if (args[argIndex].indexOf(EXT_SKETCH_FOLDER) == 0) { folder = args[argIndex].substring(EXT_SKETCH_FOLDER.length()); } else if (args[argIndex].indexOf(EXT_SIZE) == 0) { String sizeStr = args[argIndex].substring(EXT_SIZE.length()); int initial[] = toInt(split(sizeStr, ',')); initialWidth = initial[0]; initialHeight = initial[1]; //System.out.println("initial: " + initialWidth + " " + initialHeight); } else { name = args[argIndex]; break; } argIndex++; } Frame frame = new Frame(); frame.setResizable(false); // remove the grow box frame.pack(); // get insets. get more. //frame.show(); // gl hack Class c = Class.forName(name); PApplet applet = (PApplet) c.newInstance(); applet.frame = frame; applet.INITIAL_WIDTH = initialWidth; applet.INITIAL_HEIGHT = initialHeight; // these are needed before init/start applet.folder = folder; int argc = args.length - (argIndex+1); applet.args = new String[argc]; System.arraycopy(args, argc, applet.args, 0, argc); //System.out.println("calling applet.init"); applet.init(); //applet.start(); //System.out.println("done calling applet.init"); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); if (external) { Insets insets = frame.getInsets(); // does pack() first above //System.out.println(insets); int locationX = location[0] - 20; int locationY = location[1]; // applet.width and .height are zero here /* int minW = 120; int minH = 120; int windowW = Math.max(applet.width, minW) + insets.left + insets.right; int windowH = Math.max(applet.height, minH) + insets.top + insets.bottom; */ //int windowW = 120 + insets.left + insets.right; //int windowH = 120 + insets.top + insets.bottom; int windowW = initialWidth + insets.left + insets.right; int windowH = initialHeight + insets.top + insets.bottom; frame.setSize(windowW, windowH); if (exactLocation) { frame.setLocation(location[0], location[1]); } else { if (locationX - windowW > 10) { // if it fits to the left of the window frame.setLocation(locationX - windowW, locationY); } else { // if it fits inside the editor window, // offset slightly from upper lefthand corner // so that it's plunked inside the text area locationX = location[0] + 66; locationY = location[1] + 66; if ((locationX + windowW > screen.width - 33) || (locationY + windowH > screen.height - 33)) { // otherwise center on screen locationX = (screen.width - windowW) / 2; locationY = (screen.height - windowH) / 2; } frame.setLocation(locationX, locationY); } } //System.out.println("applet izzat: " + applet.width + " " + // applet.height); frame.setLayout(null); frame.add(applet); frame.setBackground(SystemColor.control); /* applet.setBounds((windowW - applet.width)/2, insets.top + ((windowH - insets.top - insets.bottom) - applet.height)/2, windowW, windowH); */ applet.setBounds((windowW - initialWidth) / 2, insets.top + ((windowH - insets.top - insets.bottom) - initialHeight)/2, windowW, windowH); applet.setupExternal(frame); } else { // !external //System.out.println("applet not external"); // remove applet name from args passed in applet.args = new String[args.length - 1]; System.arraycopy(args, 1, applet.args, 0, args.length - 1); frame.setLayout(new BorderLayout()); frame.add(applet, BorderLayout.CENTER); frame.pack(); frame.setLocation((screen.width - applet.g.width) / 2, (screen.height - applet.g.height) / 2); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } //System.out.println("showing frame"); frame.show(); //System.out.println("applet requesting focus"); applet.requestFocus(); // ask for keydowns //System.out.println("exiting main()"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } ////////////////////////////////////////////////////////////// public void recordFrame(PMethods recorder) { this.recorder = recorder; recorder.beginFrame(); } ////////////////////////////////////////////////////////////// // everything below this line is automatically generated. no touch. // public functions for processing.core public void imageMode(int mode) { if (recorder != null) recorder.imageMode(mode); g.imageMode(mode); } public void smooth() { if (recorder != null) recorder.smooth(); g.smooth(); } public void noSmooth() { if (recorder != null) recorder.noSmooth(); g.noSmooth(); } public void loadPixels() { if (recorder != null) recorder.loadPixels(); g.loadPixels(); } public void updatePixels() { if (recorder != null) recorder.updatePixels(); g.updatePixels(); } public void updatePixels(int x1, int y1, int x2, int y2) { if (recorder != null) recorder.updatePixels(x1, y1, x2, y2); g.updatePixels(x1, y1, x2, y2); } public int get(int x, int y) { return g.get(x, y); } public PImage get(int x, int y, int w, int h) { return g.get(x, y, w, h); } public void set(int x, int y, int c) { if (recorder != null) recorder.set(x, y, c); g.set(x, y, c); } public void mask(int alpha[]) { if (recorder != null) recorder.mask(alpha); g.mask(alpha); } static public void mask(PImage image, int alpha[]) { PGraphics.mask(image, alpha); } public void mask(PImage alpha) { if (recorder != null) recorder.mask(alpha); g.mask(alpha); } static public void mask(PImage image, PImage alpha) { PGraphics.mask(image, alpha); } public void filter(int kind) { if (recorder != null) recorder.filter(kind); g.filter(kind); } public void filter(int kind, float param) { if (recorder != null) recorder.filter(kind, param); g.filter(kind, param); } public void copy(PImage src, int dx, int dy) { if (recorder != null) recorder.copy(src, dx, dy); g.copy(src, dx, dy); } public void copy(int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2) { if (recorder != null) recorder.copy(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2); g.copy(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2); } public void copy(PImage src, int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2) { if (recorder != null) recorder.copy(src, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2); g.copy(src, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2); } static public int blend(int c1, int c2, int mode) { return PGraphics.blend(c1, c2, mode); } public void blend(int sx, int sy, int dx, int dy, int mode) { if (recorder != null) recorder.blend(sx, sy, dx, dy, mode); g.blend(sx, sy, dx, dy, mode); } public void blend(PImage src, int sx, int sy, int dx, int dy, int mode) { if (recorder != null) recorder.blend(src, sx, sy, dx, dy, mode); g.blend(src, sx, sy, dx, dy, mode); } public void blend(int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2, int mode) { if (recorder != null) recorder.blend(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2, mode); g.blend(sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2, mode); } public void blend(PImage src, int sx1, int sy1, int sx2, int sy2, int dx1, int dy1, int dx2, int dy2, int mode) { if (recorder != null) recorder.blend(src, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2, mode); g.blend(src, sx1, sy1, sx2, sy2, dx1, dy1, dx2, dy2, mode); } static public boolean saveHeaderTIF(OutputStream output, int width, int height) { return PGraphics.saveHeaderTIF(output, width, height); } static public boolean saveTIF(OutputStream output, int pixels[], int width, int height) { return PGraphics.saveTIF(output, pixels, width, height); } static public boolean saveHeaderTGA(OutputStream output, int width, int height) { return PGraphics.saveHeaderTGA(output, width, height); } static public boolean saveTGA(OutputStream output, int pixels[], int width, int height) { return PGraphics.saveTGA(output, pixels, width, height); } public void save(String filename) { if (recorder != null) recorder.save(filename); g.save(filename); } public void hint(int which) { if (recorder != null) recorder.hint(which); g.hint(which); } public void unhint(int which) { if (recorder != null) recorder.unhint(which); g.unhint(which); } public void beginShape() { if (recorder != null) recorder.beginShape(); g.beginShape(); } public void beginShape(int kind) { if (recorder != null) recorder.beginShape(kind); g.beginShape(kind); } public void normal(float nx, float ny, float nz) { if (recorder != null) recorder.normal(nx, ny, nz); g.normal(nx, ny, nz); } public void textureMode(int mode) { if (recorder != null) recorder.textureMode(mode); g.textureMode(mode); } public void texture(PImage image) { if (recorder != null) recorder.texture(image); g.texture(image); } public void vertex(float x, float y) { if (recorder != null) recorder.vertex(x, y); g.vertex(x, y); } public void vertex(float x, float y, float z) { if (recorder != null) recorder.vertex(x, y, z); g.vertex(x, y, z); } public void vertex(float x, float y, float u, float v) { if (recorder != null) recorder.vertex(x, y, u, v); g.vertex(x, y, u, v); } public void vertex(float x, float y, float z, float u, float v) { if (recorder != null) recorder.vertex(x, y, z, u, v); g.vertex(x, y, z, u, v); } public void bezierVertex(float x, float y) { if (recorder != null) recorder.bezierVertex(x, y); g.bezierVertex(x, y); } public void bezierVertex(float x, float y, float z) { if (recorder != null) recorder.bezierVertex(x, y, z); g.bezierVertex(x, y, z); } public void curveVertex(float x, float y) { if (recorder != null) recorder.curveVertex(x, y); g.curveVertex(x, y); } public void curveVertex(float x, float y, float z) { if (recorder != null) recorder.curveVertex(x, y, z); g.curveVertex(x, y, z); } public void endShape() { if (recorder != null) recorder.endShape(); g.endShape(); } public void point(float x, float y) { if (recorder != null) recorder.point(x, y); g.point(x, y); } public void point(float x, float y, float z) { if (recorder != null) recorder.point(x, y, z); g.point(x, y, z); } public void line(float x1, float y1, float x2, float y2) { if (recorder != null) recorder.line(x1, y1, x2, y2); g.line(x1, y1, x2, y2); } public void line(float x1, float y1, float z1, float x2, float y2, float z2) { if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2); g.line(x1, y1, z1, x2, y2, z2); } public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3); g.triangle(x1, y1, x2, y2, x3, y3); } public void quad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4); g.quad(x1, y1, x2, y2, x3, y3, x4, y4); } public void rectMode(int mode) { if (recorder != null) recorder.rectMode(mode); g.rectMode(mode); } public void rect(float x1, float y1, float x2, float y2) { if (recorder != null) recorder.rect(x1, y1, x2, y2); g.rect(x1, y1, x2, y2); } public void ellipseMode(int mode) { if (recorder != null) recorder.ellipseMode(mode); g.ellipseMode(mode); } public void ellipse(float a, float b, float c, float d) { if (recorder != null) recorder.ellipse(a, b, c, d); g.ellipse(a, b, c, d); } public void arc(float a, float b, float c, float d, float start, float stop) { if (recorder != null) recorder.arc(a, b, c, d, start, stop); g.arc(a, b, c, d, start, stop); } public void box(float size) { if (recorder != null) recorder.box(size); g.box(size); } public void box(float w, float h, float d) { if (recorder != null) recorder.box(w, h, d); g.box(w, h, d); } public void sphereDetail(int res) { if (recorder != null) recorder.sphereDetail(res); g.sphereDetail(res); } public void sphere(float r) { if (recorder != null) recorder.sphere(r); g.sphere(r); } public void sphere(float x, float y, float z, float r) { if (recorder != null) recorder.sphere(x, y, z, r); g.sphere(x, y, z, r); } public float bezierPoint(float a, float b, float c, float d, float t) { return g.bezierPoint(a, b, c, d, t); } public float bezierTangent(float a, float b, float c, float d, float t) { return g.bezierTangent(a, b, c, d, t); } public void bezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4); g.bezier(x1, y1, x2, y2, x3, y3, x4, y4); } public void bezier(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } public void bezierDetail(int detail) { if (recorder != null) recorder.bezierDetail(detail); g.bezierDetail(detail); } public void curveDetail(int detail) { if (recorder != null) recorder.curveDetail(detail); g.curveDetail(detail); } public void curveTightness(float tightness) { if (recorder != null) recorder.curveTightness(tightness); g.curveTightness(tightness); } public float curvePoint(float a, float b, float c, float d, float t) { return g.curvePoint(a, b, c, d, t); } public float curveTangent(float a, float b, float c, float d, float t) { return g.curveTangent(a, b, c, d, t); } public void curve(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4); g.curve(x1, y1, x2, y2, x3, y3, x4, y4); } public void curve(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } public void image(PImage image, float x, float y) { if (recorder != null) recorder.image(image, x, y); g.image(image, x, y); } public void image(PImage image, float x, float y, float c, float d) { if (recorder != null) recorder.image(image, x, y, c, d); g.image(image, x, y, c, d); } public void image(PImage image, float a, float b, float c, float d, int u1, int v1, int u2, int v2) { if (recorder != null) recorder.image(image, a, b, c, d, u1, v1, u2, v2); g.image(image, a, b, c, d, u1, v1, u2, v2); } public void textFont(PFont which, float size) { if (recorder != null) recorder.textFont(which, size); g.textFont(which, size); } public void textFont(PFont which) { if (recorder != null) recorder.textFont(which); g.textFont(which); } public void textSize(float size) { if (recorder != null) recorder.textSize(size); g.textSize(size); } public void textLeading(float leading) { if (recorder != null) recorder.textLeading(leading); g.textLeading(leading); } public void textMode(int mode) { if (recorder != null) recorder.textMode(mode); g.textMode(mode); } public void textSpace(int space) { if (recorder != null) recorder.textSpace(space); g.textSpace(space); } public float textAscent() { return g.textAscent(); } public float textDescent() { return g.textDescent(); } public float textWidth(char c) { return g.textWidth(c); } public float textWidth(String s) { return g.textWidth(s); } public void text(char c, float x, float y) { if (recorder != null) recorder.text(c, x, y); g.text(c, x, y); } public void text(char c, float x, float y, float z) { if (recorder != null) recorder.text(c, x, y, z); g.text(c, x, y, z); } public void text(String s, float x, float y) { if (recorder != null) recorder.text(s, x, y); g.text(s, x, y); } public void text(String s, float x, float y, float z) { if (recorder != null) recorder.text(s, x, y, z); g.text(s, x, y, z); } public void text(String s, float x1, float y1, float x2, float y2) { if (recorder != null) recorder.text(s, x1, y1, x2, y2); g.text(s, x1, y1, x2, y2); } public void text(String s, float x1, float y1, float x2, float y2, float z) { if (recorder != null) recorder.text(s, x1, y1, x2, y2, z); g.text(s, x1, y1, x2, y2, z); } public void text(int num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(int num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } public void text(float num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(float num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } public void translate(float tx, float ty) { if (recorder != null) recorder.translate(tx, ty); g.translate(tx, ty); } public void translate(float tx, float ty, float tz) { if (recorder != null) recorder.translate(tx, ty, tz); g.translate(tx, ty, tz); } public void angleMode(int mode) { if (recorder != null) recorder.angleMode(mode); g.angleMode(mode); } public void rotate(float angle) { if (recorder != null) recorder.rotate(angle); g.rotate(angle); } public void rotateX(float angle) { if (recorder != null) recorder.rotateX(angle); g.rotateX(angle); } public void rotateY(float angle) { if (recorder != null) recorder.rotateY(angle); g.rotateY(angle); } public void rotateZ(float angle) { if (recorder != null) recorder.rotateZ(angle); g.rotateZ(angle); } public void rotate(float angle, float vx, float vy, float vz) { if (recorder != null) recorder.rotate(angle, vx, vy, vz); g.rotate(angle, vx, vy, vz); } public void scale(float s) { if (recorder != null) recorder.scale(s); g.scale(s); } public void scale(float sx, float sy) { if (recorder != null) recorder.scale(sx, sy); g.scale(sx, sy); } public void scale(float x, float y, float z) { if (recorder != null) recorder.scale(x, y, z); g.scale(x, y, z); } public void push() { if (recorder != null) recorder.push(); g.push(); } public void pop() { if (recorder != null) recorder.pop(); g.pop(); } public void resetMatrix() { if (recorder != null) recorder.resetMatrix(); g.resetMatrix(); } public void applyMatrix(float n00, float n01, float n02, float n10, float n11, float n12) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12); g.applyMatrix(n00, n01, n02, n10, n11, n12); } public void applyMatrix(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23, float n30, float n31, float n32, float n33) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); } public void printMatrix() { if (recorder != null) recorder.printMatrix(); g.printMatrix(); } public void cameraMode(int mode) { if (recorder != null) recorder.cameraMode(mode); g.cameraMode(mode); } public void beginCamera() { if (recorder != null) recorder.beginCamera(); g.beginCamera(); } public void endCamera() { if (recorder != null) recorder.endCamera(); g.endCamera(); } public void ortho(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.ortho(left, right, bottom, top, near, far); g.ortho(left, right, bottom, top, near, far); } public void perspective(float fovy, float aspect, float zNear, float zFar) { if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar); g.perspective(fovy, aspect, zNear, zFar); } public void frustum(float left, float right, float bottom, float top, float znear, float zfar) { if (recorder != null) recorder.frustum(left, right, bottom, top, znear, zfar); g.frustum(left, right, bottom, top, znear, zfar); } public void lookat(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { if (recorder != null) recorder.lookat(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); g.lookat(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } public void printCamera() { if (recorder != null) recorder.printCamera(); g.printCamera(); } public float screenX(float x, float y) { return g.screenX(x, y); } public float screenY(float x, float y) { return g.screenY(x, y); } public float screenX(float x, float y, float z) { return g.screenX(x, y, z); } public float screenY(float x, float y, float z) { return g.screenY(x, y, z); } public float screenZ(float x, float y, float z) { return g.screenZ(x, y, z); } public float objectX(float x, float y, float z) { return g.objectX(x, y, z); } public float objectY(float x, float y, float z) { return g.objectY(x, y, z); } public float objectZ(float x, float y, float z) { return g.objectZ(x, y, z); } public void lights() { if (recorder != null) recorder.lights(); g.lights(); } public void noLights() { if (recorder != null) recorder.noLights(); g.noLights(); } public void light(int num, float x, float y, float z, float red, float green, float blue) { if (recorder != null) recorder.light(num, x, y, z, red, green, blue); g.light(num, x, y, z, red, green, blue); } public void lightEnable(int num) { if (recorder != null) recorder.lightEnable(num); g.lightEnable(num); } public void lightDisable(int num) { if (recorder != null) recorder.lightDisable(num); g.lightDisable(num); } public void lightPosition(int num, float x, float y, float z) { if (recorder != null) recorder.lightPosition(num, x, y, z); g.lightPosition(num, x, y, z); } public void lightAmbient(int num, float x, float y, float z) { if (recorder != null) recorder.lightAmbient(num, x, y, z); g.lightAmbient(num, x, y, z); } public void lightDiffuse(int num, float x, float y, float z) { if (recorder != null) recorder.lightDiffuse(num, x, y, z); g.lightDiffuse(num, x, y, z); } public void lightSpecular(int num, float x, float y, float z) { if (recorder != null) recorder.lightSpecular(num, x, y, z); g.lightSpecular(num, x, y, z); } public void colorMode(int mode) { if (recorder != null) recorder.colorMode(mode); g.colorMode(mode); } public void colorMode(int mode, float max) { if (recorder != null) recorder.colorMode(mode, max); g.colorMode(mode, max); } public void colorMode(int mode, float maxX, float maxY, float maxZ) { if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ); g.colorMode(mode, maxX, maxY, maxZ); } public void colorMode(int mode, float maxX, float maxY, float maxZ, float maxA) { if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ, maxA); g.colorMode(mode, maxX, maxY, maxZ, maxA); } public void noTint() { if (recorder != null) recorder.noTint(); g.noTint(); } public void tint(int rgb) { if (recorder != null) recorder.tint(rgb); g.tint(rgb); } public void tint(float gray) { if (recorder != null) recorder.tint(gray); g.tint(gray); } public void tint(float gray, float alpha) { if (recorder != null) recorder.tint(gray, alpha); g.tint(gray, alpha); } public void tint(float x, float y, float z) { if (recorder != null) recorder.tint(x, y, z); g.tint(x, y, z); } public void tint(float x, float y, float z, float a) { if (recorder != null) recorder.tint(x, y, z, a); g.tint(x, y, z, a); } public void noFill() { if (recorder != null) recorder.noFill(); g.noFill(); } public void fill(int rgb) { if (recorder != null) recorder.fill(rgb); g.fill(rgb); } public void fill(float gray) { if (recorder != null) recorder.fill(gray); g.fill(gray); } public void fill(float gray, float alpha) { if (recorder != null) recorder.fill(gray, alpha); g.fill(gray, alpha); } public void fill(float x, float y, float z) { if (recorder != null) recorder.fill(x, y, z); g.fill(x, y, z); } public void fill(float x, float y, float z, float a) { if (recorder != null) recorder.fill(x, y, z, a); g.fill(x, y, z, a); } public void strokeWeight(float weight) { if (recorder != null) recorder.strokeWeight(weight); g.strokeWeight(weight); } public void strokeJoin(int join) { if (recorder != null) recorder.strokeJoin(join); g.strokeJoin(join); } public void strokeCap(int cap) { if (recorder != null) recorder.strokeCap(cap); g.strokeCap(cap); } public void noStroke() { if (recorder != null) recorder.noStroke(); g.noStroke(); } public void stroke(int rgb) { if (recorder != null) recorder.stroke(rgb); g.stroke(rgb); } public void stroke(float gray) { if (recorder != null) recorder.stroke(gray); g.stroke(gray); } public void stroke(float gray, float alpha) { if (recorder != null) recorder.stroke(gray, alpha); g.stroke(gray, alpha); } public void stroke(float x, float y, float z) { if (recorder != null) recorder.stroke(x, y, z); g.stroke(x, y, z); } public void stroke(float x, float y, float z, float a) { if (recorder != null) recorder.stroke(x, y, z, a); g.stroke(x, y, z, a); } public void background(int rgb) { if (recorder != null) recorder.background(rgb); g.background(rgb); } public void background(float gray) { if (recorder != null) recorder.background(gray); g.background(gray); } public void background(float x, float y, float z) { if (recorder != null) recorder.background(x, y, z); g.background(x, y, z); } public void background(PImage image) { if (recorder != null) recorder.background(image); g.background(image); } public void clear() { if (recorder != null) recorder.clear(); g.clear(); } public final float alpha(int what) { return g.alpha(what); } public final float red(int what) { return g.red(what); } public final float green(int what) { return g.green(what); } public final float blue(int what) { return g.blue(what); } public final float hue(int what) { return g.hue(what); } public final float saturation(int what) { return g.saturation(what); } public final float brightness(int what) { return g.brightness(what); } }
false
false
null
null
diff --git a/src/com/seawolfsanctuary/tmt/AddActivity.java b/src/com/seawolfsanctuary/tmt/AddActivity.java index ea104eb..4f857af 100644 --- a/src/com/seawolfsanctuary/tmt/AddActivity.java +++ b/src/com/seawolfsanctuary/tmt/AddActivity.java @@ -1,367 +1,371 @@ package com.seawolfsanctuary.tmt; import java.io.File; import java.io.FileWriter; import java.io.InputStream; import android.app.TabActivity; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.TabHost; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; public class AddActivity extends TabActivity { Bundle template = new Bundle(); TextView txt_FromSearch; DatePicker dp_FromDate; TimePicker tp_FromTime; AutoCompleteTextView actv_FromSearch; CheckBox chk_DetailClass; TextView txt_DetailClass; CheckBox chk_DetailHeadcode; TextView txt_DetailHeadcode; TextView txt_ToSearch; DatePicker dp_ToDate; TimePicker tp_ToTime; AutoCompleteTextView actv_ToSearch; TextView txt_Summary; CheckBox chk_Checkin; @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.list: Intent intent = new Intent(this, ListSavedActivity.class); AddActivity.this.finish(); startActivity(intent); return true; default: return true; } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Link array of completions String[] completions = read_csv("stations.lst"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, completions); setContentView(R.layout.add_activity); TabHost mTabHost = getTabHost(); mTabHost.addTab(mTabHost.newTabSpec("tc_From").setIndicator("From") .setContent(R.id.tc_From)); mTabHost.addTab(mTabHost.newTabSpec("tc_Detail").setIndicator("Detail") .setContent(R.id.tc_Detail)); mTabHost.addTab(mTabHost.newTabSpec("tc_To").setIndicator("To") .setContent(R.id.tc_To)); mTabHost.addTab(mTabHost.newTabSpec("tc_Summary") .setIndicator("Summary").setContent(R.id.tc_Summary)); mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String tabID) { template = Helpers.saveCurrentJourney(AddActivity.this); if (tabID == "tc_Detail") { if (template.containsKey("detail_class")) { txt_DetailClass = (TextView) findViewById(R.id.txt_DetailClass); txt_DetailClass.setText(template .getCharSequence("detail_class")); } } if (tabID == "tc_Summary") { updateText(); txt_Summary = (TextView) findViewById(R.id.txt_Summary); chk_Checkin = (CheckBox) findViewById(R.id.chk_Checkin); actv_FromSearch = (AutoCompleteTextView) findViewById(R.id.actv_FromSearch); actv_ToSearch = (AutoCompleteTextView) findViewById(R.id.actv_ToSearch); if (Helpers.readAccessToken().length() > 0) { chk_Checkin.setEnabled(true); } chk_Checkin.setChecked(false); chk_Checkin.setEnabled(false); if (actv_FromSearch.getText().toString().length() > 0 || actv_ToSearch.getText().toString().length() > 0) { chk_Checkin.setEnabled(true); chk_Checkin.setChecked(true); } } } }); mTabHost.setCurrentTab(0); actv_FromSearch = (AutoCompleteTextView) findViewById(R.id.actv_FromSearch); actv_ToSearch = (AutoCompleteTextView) findViewById(R.id.actv_ToSearch); actv_FromSearch.setAdapter(adapter); actv_FromSearch.setThreshold(2); actv_FromSearch .setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { updateText(); Helpers.hideKeyboard(actv_FromSearch); } }); actv_ToSearch.setAdapter(adapter); actv_ToSearch.setThreshold(2); actv_ToSearch .setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { updateText(); Helpers.hideKeyboard(actv_ToSearch); } }); template = getIntent().getExtras(); Helpers.loadCurrentJourney(template, AddActivity.this); } private String[] read_csv(String filename) { String[] array = {}; try { InputStream input; input = getAssets().open(filename); int size = input.available(); byte[] buffer = new byte[size]; input.read(buffer); input.close(); array = new String(buffer).split("\n"); Toast.makeText(getBaseContext(), "Stations loaded.", Toast.LENGTH_SHORT).show(); } catch (Exception e) { String error_msg = "Error reading station list!"; actv_FromSearch = (AutoCompleteTextView) findViewById(R.id.actv_FromSearch); actv_FromSearch.setText(error_msg); actv_FromSearch.setError(error_msg); actv_FromSearch.setEnabled(false); actv_ToSearch = (AutoCompleteTextView) findViewById(R.id.actv_ToSearch); actv_ToSearch.setText(error_msg); actv_ToSearch.setError(error_msg); actv_ToSearch.setEnabled(false); } return array; } private void updateText() { actv_FromSearch = (AutoCompleteTextView) findViewById(R.id.actv_FromSearch); dp_FromDate = (DatePicker) findViewById(R.id.dp_FromDate); tp_FromTime = (TimePicker) findViewById(R.id.tp_FromTime); txt_DetailClass = (TextView) findViewById(R.id.txt_DetailClass); txt_DetailHeadcode = (TextView) findViewById(R.id.txt_DetailHeadcode); actv_ToSearch = (AutoCompleteTextView) findViewById(R.id.actv_ToSearch); dp_ToDate = (DatePicker) findViewById(R.id.dp_ToDate); tp_ToTime = (TimePicker) findViewById(R.id.tp_ToTime); txt_Summary = (TextView) findViewById(R.id.txt_Summary); txt_Summary.setText("From:\t" + Helpers.trimCodeFromStation(actv_FromSearch.getText() .toString()) + "\nOn:\t\t" + dp_FromDate.getDayOfMonth() + "/" + (dp_FromDate.getMonth() + 1) + "/" + dp_FromDate.getYear() + "\nAt:\t\t" + tp_FromTime.getCurrentHour() + ":" + tp_FromTime.getCurrentMinute() + "\n\nTo:\t\t" + Helpers.trimCodeFromStation(actv_ToSearch.getText() .toString()) + "\nOn:\t\t" + dp_ToDate.getDayOfMonth() + "/" + (dp_ToDate.getMonth() + 1) + "/" + dp_ToDate.getYear() + "\nAt:\t\t" + tp_ToTime.getCurrentHour() + ":" + tp_ToTime.getCurrentMinute() + "\n\nWith:\t" + txt_DetailClass.getText() + "\nAs:\t\t" + txt_DetailHeadcode.getText()); } public void onClassCheckboxClicked(View view) { CheckBox chk_DetailClass = (CheckBox) findViewById(R.id.chk_DetailClass); TextView txt_DetailClass = (TextView) findViewById(R.id.txt_DetailClass); txt_DetailClass.setEnabled(((CheckBox) chk_DetailClass).isChecked()); Helpers.hideKeyboard(view); } public void onHeadcodeCheckboxClicked(View view) { CheckBox chk_DetailHeadcode = (CheckBox) findViewById(R.id.chk_DetailHeadcode); TextView txt_DetailHeadcode = (TextView) findViewById(R.id.txt_DetailHeadcode); txt_DetailHeadcode.setEnabled(((CheckBox) chk_DetailHeadcode) .isChecked()); Helpers.hideKeyboard(view); } public boolean writeEntry(View view) { actv_FromSearch = (AutoCompleteTextView) findViewById(R.id.actv_FromSearch); dp_FromDate = (DatePicker) findViewById(R.id.dp_FromDate); tp_FromTime = (TimePicker) findViewById(R.id.tp_FromTime); txt_DetailClass = (TextView) findViewById(R.id.txt_DetailClass); txt_DetailHeadcode = (TextView) findViewById(R.id.txt_DetailHeadcode); actv_ToSearch = (AutoCompleteTextView) findViewById(R.id.actv_ToSearch); dp_ToDate = (DatePicker) findViewById(R.id.dp_ToDate); tp_ToTime = (TimePicker) findViewById(R.id.tp_ToTime); boolean mExternalStorageWritable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageWritable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageWritable = false; } else { // Something else is wrong. It may be one of many other states, but // all we need to know is we can neither read nor write mExternalStorageWritable = false; } if (mExternalStorageWritable) { try { File f = new File(Helpers.dataDirectoryPath + "/routes.csv"); if (!f.exists()) { f.createNewFile(); } FileWriter writer = new FileWriter(f, true); String msep = "\",\""; String line = ""; line = "\"" + actv_FromSearch.getText().toString() + msep + dp_FromDate.getDayOfMonth() + msep + (dp_FromDate.getMonth() + 1) + msep + dp_FromDate.getYear() + msep + tp_FromTime.getCurrentHour() + msep + tp_FromTime.getCurrentMinute() + msep + actv_ToSearch.getText().toString() + msep + dp_ToDate.getDayOfMonth() + msep + (dp_ToDate.getMonth() + 1) + msep + dp_ToDate.getYear() + msep + tp_ToTime.getCurrentHour() + msep + tp_ToTime.getCurrentMinute() + msep + txt_DetailClass.getText() + msep + txt_DetailHeadcode.getText() + "\""; writer.write(line); writer.write(System.getProperty("line.separator")); writer.close(); Toast.makeText(getBaseContext(), "Entry saved.", Toast.LENGTH_SHORT).show(); chk_Checkin = (CheckBox) findViewById(R.id.chk_Checkin); if (chk_Checkin.isChecked()) { Bundle details = new Bundle(); details.putString("from_stn", Helpers .trimCodeFromStation(actv_FromSearch.getText() .toString())); details.putString("to_stn", Helpers .trimCodeFromStation(actv_ToSearch.getText() .toString())); details.putString("detail_class", txt_DetailClass.getText() .toString()); details.putString("detail_headcode", txt_DetailHeadcode .getText().toString()); AddActivity.this.finish(); Intent intent = new Intent(this, ListSavedActivity.class); startActivity(intent); foursquareCheckin(details); } else { AddActivity.this.finish(); Intent intent = new Intent(this, ListSavedActivity.class); startActivity(intent); } return true; } catch (Exception e) { Toast.makeText(getBaseContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show(); return false; } } else { return false; } } public void startClassInfoActivity(View view) { template = Helpers.saveCurrentJourney(AddActivity.this); if (template == null) { template = new Bundle(); } Intent intent = new Intent(this, ClassInfoActivity.class); intent.putExtras(template); startActivity(intent); + // TODO: can we finish this if a class is selected from new activity, + // but keep it if 'Back' is pushed instead? + AddActivity.this.finish(); } private void foursquareCheckin(Bundle journey) { Intent intent = new Intent(this, FoursquareCheckinActivity.class); intent.putExtras(journey); startActivity(intent); + AddActivity.this.finish(); } } \ No newline at end of file diff --git a/src/com/seawolfsanctuary/tmt/ClassInfoActivity.java b/src/com/seawolfsanctuary/tmt/ClassInfoActivity.java index 75a6bea..f318f2c 100644 --- a/src/com/seawolfsanctuary/tmt/ClassInfoActivity.java +++ b/src/com/seawolfsanctuary/tmt/ClassInfoActivity.java @@ -1,521 +1,522 @@ package com.seawolfsanctuary.tmt; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Iterator; import android.app.ExpandableListActivity; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class ClassInfoActivity extends ExpandableListActivity { public static final int IMAGE_POSITION = 0; private Bundle template; @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.class_info_context_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.download: ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setTitle("Downloading..."); progressDialog.setMessage("Preparing to download..."); progressDialog.setCancelable(false); new DownloadBundleTask(progressDialog).execute(); default: return true; } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.class_info_activity); template = getIntent().getExtras(); if (template == null) { template = new Bundle(); } + final ClassInfoAdapter adaptor = new ClassInfoAdapter(); setListAdapter(adaptor); registerForContextMenu(getExpandableListView()); ExpandableListView lv = getExpandableListView(); lv.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int id, long position) { ArrayList<String[]> data = adaptor.data; String classNo = data.get(id)[0].toString(); if (template == null) { template = new Bundle(); } else { template.remove("detail_class"); } template.putCharSequence("detail_class", classNo); Intent intent = new Intent(view.getContext(), AddActivity.class); intent.putExtras(template); startActivity(intent); ClassInfoActivity.this.finish(); return true; } }); } private class DownloadBundleTask extends AsyncTask<Void, String, Boolean> { private ProgressDialog progressDialog; private String downloadingError = "unknown error :-("; public DownloadBundleTask(ProgressDialog dialogFromActivity) { progressDialog = dialogFromActivity; } public void onPreExecute() { progressDialog.show(); } protected Boolean doInBackground(Void... params) { ClassInfoAdapter adapter = new ClassInfoAdapter(); ArrayList<String> entries = adapter.loadClassInfo(true); ArrayList<String[]> data = adapter.parseEntries(entries); progressDialog.setMax(data.size() * 2); boolean downloadedThumbs = false; boolean downloadedPhotos = false; try { URL bundleDownloadURL = new URL( "http://dl.dropbox.com/u/6413248/class_photos/thumbs/"); File targetDir = new File(Helpers.dataDirectoryPath + "/class_photos/thumbs"); if (targetDir.exists()) { targetDir.delete(); } targetDir.mkdir(); for (int i = 0; i < data.size(); i++) { String[] d = data.get(i); String destination = d[0]; publishProgress("thumbnail", destination); URL photoDownloadURL = new URL(bundleDownloadURL + destination); HttpURLConnection c = (HttpURLConnection) photoDownloadURL .openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); File target = new File(Helpers.dataDirectoryPath + "/class_photos/thumbs/" + destination); if (target.exists()) { target.delete(); } FileOutputStream f = new FileOutputStream( Helpers.dataDirectoryPath + "/class_photos/thumbs/" + destination); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; while ((len1 = in.read(buffer)) > 0) { f.write(buffer, 0, len1); } f.close(); c.disconnect(); progressDialog.incrementProgressBy(1); } downloadedThumbs = true; bundleDownloadURL = new URL( "http://dl.dropbox.com/u/6413248/class_photos/"); targetDir = new File(Helpers.dataDirectoryPath + "/class_photos"); if (targetDir.exists()) { targetDir.delete(); } targetDir.mkdir(); for (int i = 0; i < data.size(); i++) { String[] d = data.get(i); String destination = d[0]; publishProgress("photo", destination); URL photoDownloadURL = new URL(bundleDownloadURL + destination); HttpURLConnection c = (HttpURLConnection) photoDownloadURL .openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); File target = new File(Helpers.dataDirectoryPath + "/class_photos/" + destination); if (target.exists()) { target.delete(); } FileOutputStream f = new FileOutputStream( Helpers.dataDirectoryPath + "/class_photos/" + destination); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; while ((len1 = in.read(buffer)) > 0) { f.write(buffer, 0, len1); } f.close(); c.disconnect(); progressDialog.incrementProgressBy(1); } downloadedPhotos = true; } catch (Exception e) { downloadingError = e.getLocalizedMessage(); e.printStackTrace(); } return (downloadedThumbs && downloadedPhotos); } protected void onProgressUpdate(String... progress) { progressDialog.setMessage(progress[0].substring(0, 1).toUpperCase() + progress[0].substring(1) + " for class " + progress[1]); } protected void onPostExecute(Boolean success) { progressDialog.dismiss(); Intent intent = new Intent(getApplicationContext(), ClassInfoActivity.class); ClassInfoActivity.this.finish(); startActivity(intent); if (success) { Toast.makeText(getApplicationContext(), "Download finished!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Download failed.\n" + downloadingError, Toast.LENGTH_LONG).show(); } } } class ClassInfoAdapter extends BaseExpandableListAdapter { public ArrayList<String> entries = loadClassInfo(true); public ArrayList<String[]> data = parseEntries(entries); ArrayList<String> names = new ArrayList<String>(getNames(data)); private String[] presentedNames = Helpers .arrayListToArray(getNames(data)); private String[][] presentedData = Helpers .multiArrayListToArray(getData(data)); private ArrayList<String> getNames(ArrayList<String[]> data) { ArrayList<String> names = new ArrayList<String>(); for (int i = 0; i < data.size(); i++) { String[] entry = data.get(i); String name = entry[0]; if (entry[1].length() > 0) { name = name + " - " + entry[1]; } names.add(name); } return names; } private ArrayList<ArrayList<String>> getData(ArrayList<String[]> entries) { ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>(); for (int i = 0; i < entries.size(); i++) { String[] entry = entries.get(i); ArrayList<String> split = new ArrayList<String>(); if (entry.length < 7) { String[] new_entry = new String[] { entry[0], entry[1], entry[2], entry[3], entry[4], "", "" }; entry = new_entry; } try { entry[2] = NumberFormat.getIntegerInstance().format( Integer.parseInt(entry[2])) + "mm"; } catch (Exception e) { // meh } if (entry[4] == "0000") { entry[4] = "(none)"; entry[5] = "(none)"; } if (entry[5].length() < 1) { entry[5] = "still in service"; } split.add(null); split.add("Guage: " + entry[2] + "\nEngine: " + entry[3]); split.add("Entered Service: " + entry[4] + "\nRetired: " + entry[5]); ArrayList<String> operatorList = parseOperators(entry[6]); String operators = ""; for (String operator : operatorList) { operators = operators + operator + ", "; } operators = operators.substring(0, operators.length() - 2); split.add("Operators: " + operators); data.add(split); } return data; } public Object getChild(int groupPosition, int childPosition) { return presentedData[groupPosition][childPosition]; } public long getChildId(int groupPosition, int childPosition) { return childPosition; } public int getChildrenCount(int groupPosition) { return presentedData[groupPosition].length; } public TextView getGenericTextView() { // Layout parameters for the ExpandableListView AbsListView.LayoutParams lp = new AbsListView.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, 64); TextView textView = new TextView(ClassInfoActivity.this); textView.setLayoutParams(lp); // Centre the text vertically textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); // Set the text starting position textView.setPadding(36, 0, 0, 0); return textView; } public ImageView getGenericImageView() { // Layout parameters for the ExpandableListView AbsListView.LayoutParams lp = new AbsListView.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, 128); ImageView imageView = new ImageView(ClassInfoActivity.this); imageView.setLayoutParams(lp); // Set the image starting position imageView.setPadding(36, 0, 0, 0); return imageView; } public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if (childPosition == IMAGE_POSITION) { final String classNo = data.get(groupPosition)[0]; ImageView imageView = getGenericImageView(); imageView.setImageDrawable(load_photo(classNo)); imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { show_photo(classNo); } }); return imageView; } else { TextView textView = getGenericTextView(); textView.setText(getChild(groupPosition, childPosition) .toString()); return textView; } } public Object getGroup(int groupPosition) { return presentedNames[groupPosition]; } public int getGroupCount() { return presentedNames.length; } public long getGroupId(int groupPosition) { return groupPosition; } public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { TextView textView = getGenericTextView(); textView.setText(getGroup(groupPosition).toString()); return textView; } public boolean isChildSelectable(int groupPosition, int childPosition) { if (childPosition == IMAGE_POSITION) { return true; } else { return false; } } public boolean hasStableIds() { return true; } private void show_photo(String classNo) { File f = new File(Helpers.dataDirectoryPath + "/class_photos/", classNo); if (f.exists()) { Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType( Uri.parse(Helpers.dataDirectoryURI + "/class_photos/" + classNo), "image/*"); startActivity(i); } else { Toast.makeText(getBaseContext(), "Please download the bundle to view this photo.", Toast.LENGTH_SHORT).show(); } } private Drawable load_photo(String classNo) { Drawable d = null; try { File f = new File(Helpers.dataDirectoryPath + "/class_photos/thumbs/", classNo); if (f.exists()) { Drawable p = Drawable.createFromPath(f.getPath()); d = p; } } catch (Exception e) { System.out.println(e.getMessage()); } return d; } private String[] read_csv(String filename) { String[] array = {}; try { InputStream input; input = getAssets().open(filename); int size = input.available(); byte[] buffer = new byte[size]; input.read(buffer); input.close(); array = new String(buffer).split("\n"); } catch (Exception e) { } return array; } private ArrayList<String> loadClassInfo(boolean showToast) { try { ArrayList<String> array = new ArrayList<String>(); String[] classInfo = read_csv("classes.csv"); for (String infoLine : classInfo) { array.add(infoLine); } return array; } catch (Exception e) { System.out.println(e.getMessage()); return new ArrayList<String>(); } } private ArrayList<String[]> parseEntries(ArrayList<String> entries) { ArrayList<String[]> data = new ArrayList<String[]>(); try { for (Iterator<String> i = entries.iterator(); i.hasNext();) { String str = (String) i.next(); String[] elements = str.split(","); String[] entry = new String[elements.length]; for (int j = 0; j < entry.length; j++) { entry[j] = Helpers.trimCSVSpeech(elements[j]); } data.add(entry); } } catch (Exception e) { System.out.println(e.getMessage()); } return data; } private ArrayList<String> parseOperators(String operatorString) { ArrayList<String> operators = new ArrayList<String>(); if (operatorString.length() > 0) { String[] pipedOperators = operatorString.split("[|]"); for (String operator : pipedOperators) { operators.add(operator); } } else { operators.add("(none)"); } return operators; } } } \ No newline at end of file diff --git a/src/com/seawolfsanctuary/tmt/Helpers.java b/src/com/seawolfsanctuary/tmt/Helpers.java index eec38ff..3300ca3 100644 --- a/src/com/seawolfsanctuary/tmt/Helpers.java +++ b/src/com/seawolfsanctuary/tmt/Helpers.java @@ -1,258 +1,257 @@ package com.seawolfsanctuary.tmt; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.AutoCompleteTextView; import android.widget.DatePicker; import android.widget.TextView; import android.widget.TimePicker; public class Helpers { public static final String dataDirectoryPath = Environment .getExternalStorageDirectory().toString() + "/Android/data/com.seawolfsanctuary.tmt"; public static final String dataDirectoryURI = "file:///sdcard/Android/data/com.seawolfsanctuary.tmt"; public static void hideKeyboard(View view) { InputMethodManager imm = (InputMethodManager) view.getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } public static String trimCSVSpeech(String input) { if (input.startsWith("" + '"') && input.endsWith("" + '"')) { return input.substring(1, input.length() - 1); } else { return input; } } public static String[] arrayListToArray(ArrayList<String> input) { String[] returnedArray = new String[input.size()]; for (int i = 0; i < input.size(); i++) { returnedArray[i] = input.get(i); } return returnedArray; } public static String[][] multiArrayListToArray( ArrayList<ArrayList<String>> input) { String[][] returnedArray = new String[input.size()][]; for (int i = 0; i < input.size(); i++) { returnedArray[i] = arrayListToArray(input.get(i)); } return returnedArray; } public static String leftPad(String s, int width) { return String.format("%" + width + "s", s).replace(' ', '0'); } public static String rightPad(String s, int width) { return String.format("%-" + width + "s", s).replace(' ', '0'); } public static String readAccessToken() { String accessToken = ""; try { String line = null; File f = new File(dataDirectoryPath + "/access_token.txt"); BufferedReader reader = new BufferedReader(new FileReader(f)); while ((line = reader.readLine()) != null) { accessToken = line; } reader.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return accessToken; } public static boolean writeAccessToken(String accessToken) { boolean success = false; try { File f = new File(dataDirectoryPath + "/access_token.txt"); if (f.exists()) { f.delete(); } if (!f.exists()) { f.createNewFile(); } FileWriter writer = new FileWriter(f, true); writer.write(accessToken); writer.close(); success = true; } catch (Exception e) { System.out.println(e.getMessage()); } return success; } public static boolean removeAccessToken() { boolean success = false; try { File f = new File(dataDirectoryPath + "/access_token.txt"); success = f.delete(); } catch (Exception e) { System.out.println(e.getMessage()); } return success; } public static String trimCodeFromStation(String station) { if (station.length() > 4) { station = station.substring(4); } return station; } public static Bundle saveCurrentJourney(Activity src) { Bundle journey = new Bundle(); AutoCompleteTextView actv_FromSearch = (AutoCompleteTextView) src .findViewById(R.id.actv_FromSearch); DatePicker dp_FromDate = (DatePicker) src .findViewById(R.id.dp_FromDate); TimePicker tp_FromTime = (TimePicker) src .findViewById(R.id.tp_FromTime); journey.putString("from_stn", actv_FromSearch.getText().toString()); journey.putInt("from_date_day", dp_FromDate.getDayOfMonth()); journey.putInt("from_date_month", dp_FromDate.getMonth()); journey.putInt("from_date_year", dp_FromDate.getYear()); journey.putInt("from_time_hour", tp_FromTime.getCurrentHour()); journey.putInt("from_time_minute", tp_FromTime.getCurrentMinute()); TextView txt_DetailClass = (TextView) src .findViewById(R.id.txt_DetailClass); TextView txt_DetailHeadcode = (TextView) src .findViewById(R.id.txt_DetailHeadcode); journey.putString("detail_class", txt_DetailClass.getText().toString()); journey.putString("detail_headcode", txt_DetailHeadcode.getText() .toString()); AutoCompleteTextView actv_ToSearch = (AutoCompleteTextView) src .findViewById(R.id.actv_ToSearch); DatePicker dp_ToDate = (DatePicker) src.findViewById(R.id.dp_ToDate); TimePicker tp_ToTime = (TimePicker) src.findViewById(R.id.tp_ToTime); journey.putString("to_stn", actv_ToSearch.getText().toString()); journey.putInt("to_date_day", dp_ToDate.getDayOfMonth()); journey.putInt("to_date_month", dp_ToDate.getMonth()); journey.putInt("to_date_year", dp_ToDate.getYear()); journey.putInt("to_time_hour", tp_ToTime.getCurrentHour()); journey.putInt("to_time_minute", tp_ToTime.getCurrentMinute()); return journey; } public static void loadCurrentJourney(Bundle journey, Activity dest) { if (journey != null) { - System.out.println("Loading journey..."); if (journey.containsKey("from_stn")) { if (journey.getString("from_stn").length() > 0) { AutoCompleteTextView actv_FromSearch = (AutoCompleteTextView) dest .findViewById(R.id.actv_FromSearch); actv_FromSearch.setText(journey.getString("from_stn")); } } if (journey.containsKey("from_date_year")) { if (journey.getInt("from_date_year") + journey.getInt("from_date_month") + journey.getInt("from_date_day") > 0) { DatePicker dp_FromDate = (DatePicker) dest .findViewById(R.id.dp_FromDate); dp_FromDate.init(journey.getInt("from_date_year"), journey.getInt("from_date_month"), journey.getInt("from_date_day"), null); } } if (journey.containsKey("from_time_hour")) { if (journey.getInt("from_time_hour") + journey.getInt("from_time_minute") > 0) { TimePicker tp_FromTime = (TimePicker) dest .findViewById(R.id.tp_FromTime); tp_FromTime .setCurrentHour(journey.getInt("from_time_hour")); tp_FromTime.setCurrentMinute(journey .getInt("from_time_minute")); } } if (journey.containsKey("detail_class")) { if (journey.getString("detail_class").length() > 0) { TextView txt_DetailClass = (TextView) dest .findViewById(R.id.txt_DetailClass); txt_DetailClass.setText(journey.getString("detail_class")); } } if (journey.containsKey("detail_headcode")) { if (journey.getString("detail_headcode").length() > 0) { TextView txt_DetailHeadcode = (TextView) dest .findViewById(R.id.txt_DetailHeadcode); txt_DetailHeadcode.setText(journey .getString("detail_headcode")); } } if (journey.containsKey("to_stn")) { if (journey.getString("to_stn").length() > 0) { AutoCompleteTextView actv_ToSearch = (AutoCompleteTextView) dest .findViewById(R.id.actv_ToSearch); actv_ToSearch.setText(journey.getString("to_stn")); } } if (journey.containsKey("to_date_year")) { if (journey.getInt("to_date_year") + journey.getInt("to_date_month") + journey.getInt("to_date_day") > 0) { DatePicker dp_ToDate = (DatePicker) dest .findViewById(R.id.dp_ToDate); dp_ToDate.init(journey.getInt("to_date_year"), journey.getInt("to_date_month"), journey.getInt("to_date_day"), null); } } if (journey.containsKey("to_time_hour")) { if (journey.getInt("to_time_hour") + journey.getInt("to_time_minute") > 0) { TimePicker tp_ToTime = (TimePicker) dest .findViewById(R.id.tp_ToTime); tp_ToTime.setCurrentHour(journey.getInt("to_time_hour")); tp_ToTime .setCurrentMinute(journey.getInt("to_time_minute")); } } } } }
false
false
null
null
diff --git a/server/src/main/java/org/openqa/selenium/server/SeleniumServer.java b/server/src/main/java/org/openqa/selenium/server/SeleniumServer.java index 815fa4ad..686a09b1 100644 --- a/server/src/main/java/org/openqa/selenium/server/SeleniumServer.java +++ b/server/src/main/java/org/openqa/selenium/server/SeleniumServer.java @@ -1,676 +1,677 @@ /* * Copyright 2006 ThoughtWorks, 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.openqa.selenium.server; import org.mortbay.http.HttpContext; import org.mortbay.http.SocketListener; import org.mortbay.jetty.Server; import org.openqa.selenium.server.browserlaunchers.AsyncExecute; import org.openqa.selenium.server.htmlrunner.HTMLLauncher; import org.openqa.selenium.server.htmlrunner.HTMLResultsListener; import org.openqa.selenium.server.htmlrunner.SeleniumHTMLRunnerResultsHandler; import org.openqa.selenium.server.htmlrunner.SingleTestSuiteResourceHandler; import java.io.*; import java.net.URL; import java.net.URLConnection; /** * Provides a server that can launch/terminate browsers and can receive Selenese commands * over HTTP and send them on to the browser. * <p/> * <p>To run Selenium Server, run: * <p/> * <blockquote><code>java -jar selenium-server-1.0-SNAPSHOT.jar [-port 4444] [-interactive] [-timeout 1800]</code></blockquote> * <p/> * <p>Where <code>-port</code> specifies the port you wish to run the Server on (default is 4444). * <p/> * <p>Where <code>-timeout</code> specifies the number of seconds that you allow data to wait all in the * communications queues before an exception is thrown. * <p/> * <p>Using the <code>-interactive</code> flag will start the server in Interactive mode. * In this mode you can type Selenese commands on the command line (e.g. cmd=open&1=http://www.yahoo.com). * You may also interactively specify commands to run on a particular "browser session" (see below) like this: * <blockquote><code>cmd=open&1=http://www.yahoo.com&sessionId=1234</code></blockquote></p> * <p/> * <p>The server accepts three types of HTTP requests on its port: * <p/> * <ol> * <li><b>Client-Configured Proxy Requests</b>: By configuring your browser to use the * Selenium Server as an HTTP proxy, you can use the Selenium Server as a web proxy. This allows * the server to create a virtual "/selenium-server" directory on every website that you visit using * the proxy. * <li><b>Browser Selenese</b>: If the browser goes to "/selenium-server/SeleneseRunner.html?sessionId=1234" on any website * via the Client-Configured Proxy, it will ask the Selenium Server for work to do, like this: * <blockquote><code>http://www.yahoo.com/selenium-server/driver/?seleniumStart=true&sessionId=1234</code></blockquote> * The driver will then reply with a command to run in the body of the HTTP response, e.g. "|open|http://www.yahoo.com||". Once * the browser is done with this request, the browser will issue a new request for more work, this * time reporting the results of the previous command:<blockquote><code>http://www.yahoo.com/selenium-server/driver/?commandResult=OK&sessionId=1234</code></blockquote> * The action list is listed in selenium-api.js. Normal actions like "doClick" will return "OK" if * clicking was successful, or some other error string if there was an error. Assertions like * assertTextPresent or verifyTextPresent will return "PASSED" if the assertion was true, or * some other error string if the assertion was false. Getters like "getEval" will return the * result of the get command. "getAllLinks" will return a comma-delimited list of links.</li> * <li><b>Driver Commands</b>: Clients may send commands to the Selenium Server over HTTP. * Command requests should look like this:<blockquote><code>http://localhost:4444/selenium-server/driver/?commandRequest=|open|http://www.yahoo.com||&sessionId=1234</code></blockquote> * The Selenium Server will not respond to the HTTP request until the browser has finished performing the requested * command; when it does, it will reply with the result of the command (e.g. "OK" or "PASSED") in the * body of the HTTP response. (Note that <code>-interactive</code> mode also works by sending these * HTTP requests, so tests using <code>-interactive</code> mode will behave exactly like an external client driver.) * </ol> * <p>There are some special commands that only work in the Selenium Server. These commands are: * <ul><li><p><strong>getNewBrowserSession</strong>( <em>browserString</em>, <em>startURL</em> )</p> * <p>Creates a new "sessionId" number (based on the current time in milliseconds) and launches the browser specified in * <i>browserString</i>. We will then browse directly to <i>startURL</i> + "/selenium-server/SeleneseRunner.html?sessionId=###" * where "###" is the sessionId number. Only commands that are associated with the specified sessionId will be run by this browser.</p> * <p/> * <p><i>browserString</i> may be any one of the following: * <ul> * <li><code>*firefox [absolute path]</code> - Automatically launch a new Firefox process using a custom Firefox profile. * This profile will be automatically configured to use the Selenium Server as a proxy and to have all annoying prompts * ("save your password?" "forms are insecure" "make Firefox your default browser?" disabled. You may optionally specify * an absolute path to your firefox executable, or just say "*firefox". If no absolute path is specified, we'll look for * firefox.exe in a default location (normally c:\program files\mozilla firefox\firefox.exe), which you can override by * setting the Java system property <code>firefoxDefaultPath</code> to the correct path to Firefox.</li> * <li><code>*iexplore [absolute path]</code> - Automatically launch a new Internet Explorer process using custom Windows registry settings. * This process will be automatically configured to use the Selenium Server as a proxy and to have all annoying prompts * ("save your password?" "forms are insecure" "make Firefox your default browser?" disabled. You may optionally specify * an absolute path to your iexplore executable, or just say "*iexplore". If no absolute path is specified, we'll look for * iexplore.exe in a default location (normally c:\program files\internet explorer\iexplore.exe), which you can override by * setting the Java system property <code>iexploreDefaultPath</code> to the correct path to Internet Explorer.</li> * <li><code>/path/to/my/browser [other arguments]</code> - You may also simply specify the absolute path to your browser * executable, or use a relative path to your executable (which we'll try to find on your path). <b>Warning:</b> If you * specify your own custom browser, it's up to you to configure it correctly. At a minimum, you'll need to configure your * browser to use the Selenium Server as a proxy, and disable all browser-specific prompting. * </ul> * </li> * <li><p><strong>testComplete</strong>( )</p> * <p>Kills the currently running browser and erases the old browser session. If the current browser session was not * launched using <code>getNewBrowserSession</code>, or if that session number doesn't exist in the server, this * command will return an error.</p> * </li> * <li><p><strong>shutDown</strong>( )</p> * <p>Causes the server to shut itself down, killing itself and all running browsers along with it.</p> * </li> * </ul> * <p>Example:<blockquote><code>cmd=getNewBrowserSession&1=*firefox&2=http://www.google.com * <br/>Got result: 1140738083345 * <br/>cmd=open&1=http://www.google.com&sessionId=1140738083345 * <br/>Got result: OK * <br/>cmd=type&1=q&2=hello world&sessionId=1140738083345 * <br/>Got result: OK * <br/>cmd=testComplete&sessionId=1140738083345 * <br/>Got result: OK * </code></blockquote></p> * <p/> * <h4>The "null" session</h4> * <p/> * <p>If you open a browser manually and do not specify a session ID, it will look for * commands using the "null" session. You may then similarly send commands to this * browser by not specifying a sessionId when issuing commands.</p> * * @author plightbo */ public class SeleniumServer { private Server server; private SeleniumDriverResourceHandler driver; private SeleniumHTMLRunnerResultsHandler postResultsHandler; private StaticContentHandler staticContentHandler; private int port; private boolean multiWindow = false; private static String debugURL = ""; // add special tracing for debug when this URL is requested private static boolean debugMode = false; private static boolean proxyInjectionMode = false; public static final int DEFAULT_PORT = 4444; // The following port is the one which drivers and browsers should use when they contact the selenium server. // Under normal circumstances, this port will be the same as the port which the selenium server listens on. // But if a developer wants to monitor traffic into and out of the selenium server, he can set this port from // the command line to be a different value and then use a tool like tcptrace to link this port with the // server listening port, thereby opening a window into the raw HTTP traffic. // // For example, if the selenium server is invoked with -portDriversShouldContact 4445, then traffic going // into the selenium server will be routed to port 4445, although the selenium server will still be listening // to the default port 4444. At this point, you would open tcptrace to bridge the gap and be able to watch // all the data coming in and out: private static int portDriversShouldContact = DEFAULT_PORT; private static PrintStream logOut = null; private static String defaultBrowserString = null; public static final int DEFAULT_TIMEOUT = (30 * 60); public static int timeout = DEFAULT_TIMEOUT; private static Boolean reusingBrowserSessions = null; /** * Starts up the server on the specified port (or default if no port was specified) * and then starts interactive mode if specified. * * @param args - either "-port" followed by a number, or "-interactive" * @throws Exception - you know, just in case. */ public static void main(String[] args) throws Exception { int port = DEFAULT_PORT; boolean interactive = false; boolean htmlSuite = false; boolean multiWindow = false; String browserString = null; String startURL = null; String suiteFilePath = null; String resultFilePath = null; File userExtensions = null; boolean proxyInjectionModeArg = false; int portDriversShouldContactArg = 0; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-help".equals(arg)) { usage(null); System.exit(1); } else if ("-defaultBrowserString".equals(arg)) { for (i++; i < args.length; i++) { if (SeleniumServer.defaultBrowserString == null) SeleniumServer.defaultBrowserString = ""; else SeleniumServer.defaultBrowserString += " "; SeleniumServer.defaultBrowserString += args[i]; } SeleniumServer.log("\"" + defaultBrowserString + "\" will be used as the browser " + "mode for all sessions, no matter what is passed to getNewBrowserSession."); } else if ("-log".equals(arg)) { logOut = new PrintStream(getArg(args, ++i)); } else if ("-port".equals(arg)) { port = Integer.parseInt(getArg(args, ++i)); } else if ("-multiWindow".equals(arg)) { multiWindow = true; } else if ("-proxyInjectionMode".equals(arg)) { proxyInjectionModeArg = true; } else if ("-portDriversShouldContact".equals(arg)) { // to facilitate tcptrace interception of interaction between // injected js and the selenium server portDriversShouldContactArg = Integer.parseInt(getArg(args, ++i)); } else if ("-noBrowserSessionReuse".equals(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.FALSE; } else if ("-browserSessionReuse".equals(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.TRUE; } else if ("-debug".equals(arg)) { SeleniumServer.setDebugMode(true); } else if ("-debugURL".equals(arg)) { debugURL = getArg(args, ++i); } else if ("-timeout".equals(arg)) { timeout = Integer.parseInt(getArg(args, ++i)); } else if ("-userJsInjection".equals(arg)) { if (!InjectionHelper.addUserJsInjectionFile(getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userContentTransformation".equals(arg)) { if (!InjectionHelper.addUserContentTransformation(getArg(args, ++i), getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userExtensions".equals(arg)) { userExtensions = new File(getArg(args, ++i)); if (!userExtensions.exists()) { System.err.println("User Extensions file doesn't exist: " + userExtensions.getAbsolutePath()); System.exit(1); } if (!"user-extensions.js".equals(userExtensions.getName())) { System.err.println("User extensions file MUST be called \"user-extensions.js\": " + userExtensions.getAbsolutePath()); System.exit(1); } } else if ("-htmlSuite".equals(arg)) { try { browserString = args[++i]; startURL = args[++i]; suiteFilePath = args[++i]; resultFilePath = args[++i]; } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Not enough command line arguments for -htmlSuite"); System.err.println("-htmlSuite requires you to specify:"); System.err.println("* browserString (e.g. \"*firefox\")"); System.err.println("* startURL (e.g. \"http://www.google.com\")"); System.err.println("* suiteFile (e.g. \"c:\\absolute\\path\\to\\my\\HTMLSuite.html\")"); System.err.println("* resultFile (e.g. \"c:\\absolute\\path\\to\\my\\results.html\")"); System.exit(1); } htmlSuite = true; } else if ("-interactive".equals(arg)) { timeout = Integer.MAX_VALUE; interactive = true; } else if (arg.startsWith("-D")) { setSystemProperty(arg); } else { usage("unrecognized argument " + arg); System.exit(1); } } if (portDriversShouldContactArg == 0) { portDriversShouldContactArg = port; } System.setProperty("org.mortbay.http.HttpRequest.maxFormContentSize", "0"); // default max is 200k; zero is infinite final SeleniumServer seleniumProxy = new SeleniumServer(port); + seleniumProxy.multiWindow = multiWindow; checkArgsSanity(port, interactive, htmlSuite, proxyInjectionModeArg, portDriversShouldContactArg, seleniumProxy); Thread jetty = new Thread(new Runnable() { public void run() { try { seleniumProxy.start(); } catch (Exception e) { System.err.println("jetty run exception seen:"); e.printStackTrace(); } } }); if (interactive) { jetty.setDaemon(true); } jetty.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { System.out.println("Shutting down..."); seleniumProxy.stop(); } catch (InterruptedException e) { System.err.println("run exception seen:"); e.printStackTrace(); } } })); if (userExtensions != null) { seleniumProxy.addNewStaticContent(userExtensions.getParentFile()); } if (htmlSuite) { String result = null; try { File suiteFile = new File(suiteFilePath); seleniumProxy.addNewStaticContent(suiteFile.getParentFile()); String suiteURL = startURL + "/selenium-server/" + suiteFile.getName(); HTMLLauncher launcher = new HTMLLauncher(seleniumProxy); result = launcher.runHTMLSuite(browserString, startURL, suiteURL, new File(resultFilePath), timeout, multiWindow); } catch (Exception e) { System.err.println("HTML suite exception seen:"); e.printStackTrace(); System.exit(1); } if (!"PASSED".equals(result)) { System.err.println("Tests failed"); System.exit(1); } else { System.exit(0); } } if (interactive) { AsyncExecute.sleepTight(500); System.out.println("Entering interactive mode... type Selenium commands here (e.g: cmd=open&1=http://www.yahoo.com)"); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; final String[] lastSessionId = new String[]{""}; while ((userInput = stdIn.readLine()) != null) { if ("quit".equals(userInput)) { System.out.println("Stopping..."); seleniumProxy.stop(); System.exit(0); } if ("".equals(userInput)) continue; if (!userInput.startsWith("cmd=") && !userInput.startsWith("commandResult=")) { System.err.println("ERROR - Invalid command: \"" + userInput + "\""); continue; } final boolean newBrowserSession = userInput.indexOf("getNewBrowserSession") != -1; if (userInput.indexOf("sessionId") == -1 && !newBrowserSession) { userInput = userInput + "&sessionId=" + lastSessionId[0]; } final URL url = new URL("http://localhost:" + port + "/selenium-server/driver?" + userInput); Thread t = new Thread(new Runnable() { public void run() { try { SeleniumServer.log("---> Requesting " + url.toString()); URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int length = -1; while ((length = is.read(buffer)) != -1) { out.write(buffer, 0, length); } is.close(); String output = out.toString(); if (newBrowserSession) { if (output.startsWith("OK,")) { lastSessionId[0] = output.substring(3); } } } catch (IOException e) { System.err.println(e.getMessage()); if (SeleniumServer.isDebugMode()) { e.printStackTrace(); } } } }); t.start(); } } } private static void checkArgsSanity(int port, boolean interactive, boolean htmlSuite, boolean proxyInjectionModeArg, int portDriversShouldContactArg, SeleniumServer seleniumProxy) throws Exception { if (interactive && htmlSuite) { System.err.println("You can't use -interactive and -htmlSuite on the same line!"); System.exit(1); } SingleEntryAsyncQueue.setDefaultTimeout(timeout); seleniumProxy.setProxyInjectionMode(proxyInjectionModeArg); SeleniumServer.setPortDriversShouldContact(portDriversShouldContactArg); if (!isProxyInjectionMode() && (InjectionHelper.userContentTransformationsExist() || InjectionHelper.userJsInjectionsExist())) { usage("-userJsInjection and -userContentTransformation are only " + "valid in combination with -proxyInjectionMode"); System.exit(1); } if (!isProxyInjectionMode() && reusingBrowserSessions()) { usage("-reusingBrowserSessions only valid in combination with -proxyInjectionMode" + " (because of the need for multiple domain support, which only -proxyInjectionMode" + " provides)."); System.exit(1); } if (reusingBrowserSessions()) { SeleniumServer.log("Will recycle browser sessions when possible."); } } private static String getArg(String[] args, int i) { if (i >= args.length) { usage("expected at least one more argument"); System.exit(-1); } return args[i]; } private static void proxyInjectionSpeech() { SeleniumServer.log("The selenium server will execute in proxyInjection mode."); } private static void setSystemProperty(String arg) { if (arg.indexOf('=') == -1) { usage("poorly formatted Java property setting (I expect to see '=') " + arg); System.exit(1); } String property = arg.replaceFirst("-D", "").replaceFirst("=.*", ""); String value = arg.replaceFirst("[^=]*=", ""); System.err.println("Setting system property " + property + " to " + value); System.setProperty(property, value); } private static void usage(String msg) { if (msg != null) { System.err.println(msg + ":"); } System.err.println("Usage: java -jar selenium-server.jar -debug [-port nnnn] [-timeout nnnn] [-interactive]" + " [-defaultBrowserString browserString] [-log logfile] [-proxyInjectionMode [-browserSessionReuse|-noBrowserSessionReuse][-userContentTransformation your-before-regexp-string your-after-string] [-userJsInjection your-js-filename]] [-htmlSuite browserString (e.g. \"*firefox\") startURL (e.g. \"http://www.google.com\") " + "suiteFile (e.g. \"c:\\absolute\\path\\to\\my\\HTMLSuite.html\") resultFile (e.g. \"c:\\absolute\\path\\to\\my\\results.html\"]\n" + "where:\n" + "the argument for timeout is an integer number of seconds before we should give up\n" + "the argument for port is the port number the selenium server should use (default 4444)" + "\n\t-interactive puts you into interactive mode. See the tutorial for more details" + "\n\t-defaultBrowserString (e.g., *iexplore) sets the browser mode for all sessions, no matter what is passed to getNewBrowserSession" + "\n\t-browserSessionReuse stops re-initialization and spawning of the browser between tests" + "\n\t-debug puts you into debug mode, with more trace information and diagnostics" + "\n\t-proxyInjectionMode puts you into proxy injection mode, a mode where the selenium server acts as a proxy server " + "\n\t\tfor all content going to the test application. Under this mode, multiple domains can be visited, and the " + "\n\t\tfollowing additional flags are supported:" + "\n\t\t\tThe -userJsInjection flag allows you to point at a JavaScript file which will then be injected into all pages. " + "\n\t\t\tThe -userContentTransformation flag takes two arguments: the first is a regular expression which is matched " + "\n\t\t\t\tagainst all test HTML content; the second is a string which will replace matches. These flags can be used any " + "\n\t\t\t\tnumber of times. A simple example of how this could be useful: if you add" + "\n" + "\n\t\t\t\t -userContentTransformation https http" + "\n" + "\n\t\t\t\tthen all \"https\" strings in the HTML of the test application will be changed to be \"http\".\n" + "\n\t-debug puts you into debug mode, with more trace information and diagnostics" + "\n\t-proxyInjectionMode puts you into proxy injection mode, a mode where the selenium server acts as a proxy server " + "\n\t\tfor all content going to the test application. Under this mode, multiple domains can be visited, and the " + "\n\t\tfollowing additional flags are supported:" + "\n\t\t\tThe -userJsInjection flag allows you to point at a JavaScript file which will then be injected into all pages. " + "\n\t\t\tThe -userContentTransformation flag takes two arguments: the first is a regular expression which is matched " + "\n\t\t\t\tagainst all AUT content; the second is a string which will replace matches. These flags can be used any " + "\n\t\t\t\tnumber of times. A simple example of how this could be useful: if you add" + "\n\n" + " -userContentTransformation https http\r\n" + "\n\n" + "\n\t\t\t\tthen all \"https\" strings in the HTML of the test application will be changed to be \"http\".\n"); } /** * Prepares a Jetty server with its HTTP handlers. * * @param port the port to start on * @param slowResources should the webserver return static resources more slowly? (Note that this will not slow down ordinary RC test runs; this setting is used to debug Selenese HTML tests.) * @param multiWindow run the tests in the "multi-Window" layout, without using the embedded iframe * @throws Exception you know, just in case */ public SeleniumServer(int port, boolean slowResources, boolean multiWindow) throws Exception { this.port = port; this.multiWindow = multiWindow; server = new Server(); SocketListener socketListener = new SocketListener(); socketListener.setMaxIdleTimeMs(60000); socketListener.setPort(port); server.addListener(socketListener); configServer(); assembleHandlers(slowResources); } public SeleniumServer(int port, boolean slowResources) throws Exception { this(port, slowResources, false); } private void assembleHandlers(boolean slowResources) { HttpContext root = new HttpContext(); root.setContextPath("/"); ProxyHandler rootProxy = new ProxyHandler(); root.addHandler(rootProxy); server.addContext(root); HttpContext context = new HttpContext(); context.setContextPath("/selenium-server"); staticContentHandler = new StaticContentHandler(slowResources); String overrideJavascriptDir = System.getProperty("selenium.javascript.dir"); if (overrideJavascriptDir != null) { staticContentHandler.addStaticContent(new FsResourceLocator(new File(overrideJavascriptDir))); } staticContentHandler.addStaticContent(new ClasspathResourceLocator()); context.addHandler(staticContentHandler); context.addHandler(new SingleTestSuiteResourceHandler()); postResultsHandler = new SeleniumHTMLRunnerResultsHandler(); context.addHandler(postResultsHandler); // Associate the SeleniumDriverResourceHandler with the /selenium-server/driver context HttpContext driverContext = new HttpContext(); driverContext.setContextPath("/selenium-server/driver"); driver = new SeleniumDriverResourceHandler(this); context.addHandler(driver); server.addContext(context); server.addContext(driverContext); } private void configServer() { if (getDefaultBrowser() == null) { SeleniumServer.setDefaultBrowser(System.getProperty("selenium.defaultBrowserString")); } if (!isProxyInjectionMode() && System.getProperty("selenium.proxyInjectionMode") != null) { setProxyInjectionMode("true".equals(System.getProperty("selenium.proxyInjectionMode"))); } if (!isDebugMode() && System.getProperty("selenium.debugMode") != null) { setDebugMode("true".equals(System.getProperty("selenium.debugMode"))); } } public SeleniumServer(int port) throws Exception { this(port, slowResourceProperty()); } public SeleniumServer() throws Exception { this(SeleniumServer.DEFAULT_PORT, slowResourceProperty()); } private static boolean slowResourceProperty() { return ("true".equals(System.getProperty("slowResources"))); } public void addNewStaticContent(File directory) { staticContentHandler.addStaticContent(new FsResourceLocator(directory)); } public void handleHTMLRunnerResults(HTMLResultsListener listener) { postResultsHandler.addListener(listener); } /** * Starts the Jetty server */ public void start() throws Exception { server.start(); } /** * Stops the Jetty server */ public void stop() throws InterruptedException { server.stop(); driver.stopAllBrowsers(); } public int getPort() { return port; } public boolean isMultiWindow() { return multiWindow; } /** * Exposes the internal Jetty server used by Selenium. * This lets users add their own webapp to the Selenium Server jetty instance. * It is also a minor violation of encapsulation principles (what if we stop * using Jetty?) but life is too short to worry about such things. * * @return the internal Jetty server, pre-configured with the /selenium-server context as well as * the proxy server on / */ public Server getServer() { return server; } public static boolean isDebugMode() { return SeleniumServer.debugMode; } static public void setDebugMode(boolean debugMode) { SeleniumServer.debugMode = debugMode; if (debugMode) { SeleniumServer.log("Selenium server running in debug mode."); System.err.println("Standard error test."); } } public static boolean isProxyInjectionMode() { return proxyInjectionMode; } public static int getPortDriversShouldContact() { return portDriversShouldContact; } private static void setPortDriversShouldContact(int port) { SeleniumServer.portDriversShouldContact = port; } public void setProxyInjectionMode(boolean proxyInjectionMode) { if (proxyInjectionMode) { proxyInjectionSpeech(); } SeleniumServer.proxyInjectionMode = proxyInjectionMode; } public static String getDefaultBrowser() { return defaultBrowserString; } public static int getTimeoutInSeconds() { return timeout; } public static void setDefaultBrowser(String defaultBrowserString) { SeleniumServer.defaultBrowserString = defaultBrowserString; } public static boolean reusingBrowserSessions() { if (reusingBrowserSessions == null) { // if (isProxyInjectionMode()) { turn off this default until we are stable. Too many variables spoils the soup. // reusingBrowserSessions = Boolean.TRUE; // default in pi mode // } // else { reusingBrowserSessions = Boolean.FALSE; // default in non-pi mode // } } return reusingBrowserSessions; } public static String getDebugURL() { return debugURL; } public static void log(String logMessages) { PrintStream out = (logOut != null) ? logOut : System.out; if (logMessages.endsWith("\n")) { out.print(logMessages); } else { out.println(logMessages); } } }
true
true
public static void main(String[] args) throws Exception { int port = DEFAULT_PORT; boolean interactive = false; boolean htmlSuite = false; boolean multiWindow = false; String browserString = null; String startURL = null; String suiteFilePath = null; String resultFilePath = null; File userExtensions = null; boolean proxyInjectionModeArg = false; int portDriversShouldContactArg = 0; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-help".equals(arg)) { usage(null); System.exit(1); } else if ("-defaultBrowserString".equals(arg)) { for (i++; i < args.length; i++) { if (SeleniumServer.defaultBrowserString == null) SeleniumServer.defaultBrowserString = ""; else SeleniumServer.defaultBrowserString += " "; SeleniumServer.defaultBrowserString += args[i]; } SeleniumServer.log("\"" + defaultBrowserString + "\" will be used as the browser " + "mode for all sessions, no matter what is passed to getNewBrowserSession."); } else if ("-log".equals(arg)) { logOut = new PrintStream(getArg(args, ++i)); } else if ("-port".equals(arg)) { port = Integer.parseInt(getArg(args, ++i)); } else if ("-multiWindow".equals(arg)) { multiWindow = true; } else if ("-proxyInjectionMode".equals(arg)) { proxyInjectionModeArg = true; } else if ("-portDriversShouldContact".equals(arg)) { // to facilitate tcptrace interception of interaction between // injected js and the selenium server portDriversShouldContactArg = Integer.parseInt(getArg(args, ++i)); } else if ("-noBrowserSessionReuse".equals(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.FALSE; } else if ("-browserSessionReuse".equals(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.TRUE; } else if ("-debug".equals(arg)) { SeleniumServer.setDebugMode(true); } else if ("-debugURL".equals(arg)) { debugURL = getArg(args, ++i); } else if ("-timeout".equals(arg)) { timeout = Integer.parseInt(getArg(args, ++i)); } else if ("-userJsInjection".equals(arg)) { if (!InjectionHelper.addUserJsInjectionFile(getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userContentTransformation".equals(arg)) { if (!InjectionHelper.addUserContentTransformation(getArg(args, ++i), getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userExtensions".equals(arg)) { userExtensions = new File(getArg(args, ++i)); if (!userExtensions.exists()) { System.err.println("User Extensions file doesn't exist: " + userExtensions.getAbsolutePath()); System.exit(1); } if (!"user-extensions.js".equals(userExtensions.getName())) { System.err.println("User extensions file MUST be called \"user-extensions.js\": " + userExtensions.getAbsolutePath()); System.exit(1); } } else if ("-htmlSuite".equals(arg)) { try { browserString = args[++i]; startURL = args[++i]; suiteFilePath = args[++i]; resultFilePath = args[++i]; } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Not enough command line arguments for -htmlSuite"); System.err.println("-htmlSuite requires you to specify:"); System.err.println("* browserString (e.g. \"*firefox\")"); System.err.println("* startURL (e.g. \"http://www.google.com\")"); System.err.println("* suiteFile (e.g. \"c:\\absolute\\path\\to\\my\\HTMLSuite.html\")"); System.err.println("* resultFile (e.g. \"c:\\absolute\\path\\to\\my\\results.html\")"); System.exit(1); } htmlSuite = true; } else if ("-interactive".equals(arg)) { timeout = Integer.MAX_VALUE; interactive = true; } else if (arg.startsWith("-D")) { setSystemProperty(arg); } else { usage("unrecognized argument " + arg); System.exit(1); } } if (portDriversShouldContactArg == 0) { portDriversShouldContactArg = port; } System.setProperty("org.mortbay.http.HttpRequest.maxFormContentSize", "0"); // default max is 200k; zero is infinite final SeleniumServer seleniumProxy = new SeleniumServer(port); checkArgsSanity(port, interactive, htmlSuite, proxyInjectionModeArg, portDriversShouldContactArg, seleniumProxy); Thread jetty = new Thread(new Runnable() { public void run() { try { seleniumProxy.start(); } catch (Exception e) { System.err.println("jetty run exception seen:"); e.printStackTrace(); } } }); if (interactive) { jetty.setDaemon(true); } jetty.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { System.out.println("Shutting down..."); seleniumProxy.stop(); } catch (InterruptedException e) { System.err.println("run exception seen:"); e.printStackTrace(); } } })); if (userExtensions != null) { seleniumProxy.addNewStaticContent(userExtensions.getParentFile()); } if (htmlSuite) { String result = null; try { File suiteFile = new File(suiteFilePath); seleniumProxy.addNewStaticContent(suiteFile.getParentFile()); String suiteURL = startURL + "/selenium-server/" + suiteFile.getName(); HTMLLauncher launcher = new HTMLLauncher(seleniumProxy); result = launcher.runHTMLSuite(browserString, startURL, suiteURL, new File(resultFilePath), timeout, multiWindow); } catch (Exception e) { System.err.println("HTML suite exception seen:"); e.printStackTrace(); System.exit(1); } if (!"PASSED".equals(result)) { System.err.println("Tests failed"); System.exit(1); } else { System.exit(0); } } if (interactive) { AsyncExecute.sleepTight(500); System.out.println("Entering interactive mode... type Selenium commands here (e.g: cmd=open&1=http://www.yahoo.com)"); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; final String[] lastSessionId = new String[]{""}; while ((userInput = stdIn.readLine()) != null) { if ("quit".equals(userInput)) { System.out.println("Stopping..."); seleniumProxy.stop(); System.exit(0); } if ("".equals(userInput)) continue; if (!userInput.startsWith("cmd=") && !userInput.startsWith("commandResult=")) { System.err.println("ERROR - Invalid command: \"" + userInput + "\""); continue; } final boolean newBrowserSession = userInput.indexOf("getNewBrowserSession") != -1; if (userInput.indexOf("sessionId") == -1 && !newBrowserSession) { userInput = userInput + "&sessionId=" + lastSessionId[0]; } final URL url = new URL("http://localhost:" + port + "/selenium-server/driver?" + userInput); Thread t = new Thread(new Runnable() { public void run() { try { SeleniumServer.log("---> Requesting " + url.toString()); URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int length = -1; while ((length = is.read(buffer)) != -1) { out.write(buffer, 0, length); } is.close(); String output = out.toString(); if (newBrowserSession) { if (output.startsWith("OK,")) { lastSessionId[0] = output.substring(3); } } } catch (IOException e) { System.err.println(e.getMessage()); if (SeleniumServer.isDebugMode()) { e.printStackTrace(); } } } }); t.start(); } } }
public static void main(String[] args) throws Exception { int port = DEFAULT_PORT; boolean interactive = false; boolean htmlSuite = false; boolean multiWindow = false; String browserString = null; String startURL = null; String suiteFilePath = null; String resultFilePath = null; File userExtensions = null; boolean proxyInjectionModeArg = false; int portDriversShouldContactArg = 0; for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-help".equals(arg)) { usage(null); System.exit(1); } else if ("-defaultBrowserString".equals(arg)) { for (i++; i < args.length; i++) { if (SeleniumServer.defaultBrowserString == null) SeleniumServer.defaultBrowserString = ""; else SeleniumServer.defaultBrowserString += " "; SeleniumServer.defaultBrowserString += args[i]; } SeleniumServer.log("\"" + defaultBrowserString + "\" will be used as the browser " + "mode for all sessions, no matter what is passed to getNewBrowserSession."); } else if ("-log".equals(arg)) { logOut = new PrintStream(getArg(args, ++i)); } else if ("-port".equals(arg)) { port = Integer.parseInt(getArg(args, ++i)); } else if ("-multiWindow".equals(arg)) { multiWindow = true; } else if ("-proxyInjectionMode".equals(arg)) { proxyInjectionModeArg = true; } else if ("-portDriversShouldContact".equals(arg)) { // to facilitate tcptrace interception of interaction between // injected js and the selenium server portDriversShouldContactArg = Integer.parseInt(getArg(args, ++i)); } else if ("-noBrowserSessionReuse".equals(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.FALSE; } else if ("-browserSessionReuse".equals(arg)) { SeleniumServer.reusingBrowserSessions = Boolean.TRUE; } else if ("-debug".equals(arg)) { SeleniumServer.setDebugMode(true); } else if ("-debugURL".equals(arg)) { debugURL = getArg(args, ++i); } else if ("-timeout".equals(arg)) { timeout = Integer.parseInt(getArg(args, ++i)); } else if ("-userJsInjection".equals(arg)) { if (!InjectionHelper.addUserJsInjectionFile(getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userContentTransformation".equals(arg)) { if (!InjectionHelper.addUserContentTransformation(getArg(args, ++i), getArg(args, ++i))) { usage(null); System.exit(1); } } else if ("-userExtensions".equals(arg)) { userExtensions = new File(getArg(args, ++i)); if (!userExtensions.exists()) { System.err.println("User Extensions file doesn't exist: " + userExtensions.getAbsolutePath()); System.exit(1); } if (!"user-extensions.js".equals(userExtensions.getName())) { System.err.println("User extensions file MUST be called \"user-extensions.js\": " + userExtensions.getAbsolutePath()); System.exit(1); } } else if ("-htmlSuite".equals(arg)) { try { browserString = args[++i]; startURL = args[++i]; suiteFilePath = args[++i]; resultFilePath = args[++i]; } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Not enough command line arguments for -htmlSuite"); System.err.println("-htmlSuite requires you to specify:"); System.err.println("* browserString (e.g. \"*firefox\")"); System.err.println("* startURL (e.g. \"http://www.google.com\")"); System.err.println("* suiteFile (e.g. \"c:\\absolute\\path\\to\\my\\HTMLSuite.html\")"); System.err.println("* resultFile (e.g. \"c:\\absolute\\path\\to\\my\\results.html\")"); System.exit(1); } htmlSuite = true; } else if ("-interactive".equals(arg)) { timeout = Integer.MAX_VALUE; interactive = true; } else if (arg.startsWith("-D")) { setSystemProperty(arg); } else { usage("unrecognized argument " + arg); System.exit(1); } } if (portDriversShouldContactArg == 0) { portDriversShouldContactArg = port; } System.setProperty("org.mortbay.http.HttpRequest.maxFormContentSize", "0"); // default max is 200k; zero is infinite final SeleniumServer seleniumProxy = new SeleniumServer(port); seleniumProxy.multiWindow = multiWindow; checkArgsSanity(port, interactive, htmlSuite, proxyInjectionModeArg, portDriversShouldContactArg, seleniumProxy); Thread jetty = new Thread(new Runnable() { public void run() { try { seleniumProxy.start(); } catch (Exception e) { System.err.println("jetty run exception seen:"); e.printStackTrace(); } } }); if (interactive) { jetty.setDaemon(true); } jetty.start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { try { System.out.println("Shutting down..."); seleniumProxy.stop(); } catch (InterruptedException e) { System.err.println("run exception seen:"); e.printStackTrace(); } } })); if (userExtensions != null) { seleniumProxy.addNewStaticContent(userExtensions.getParentFile()); } if (htmlSuite) { String result = null; try { File suiteFile = new File(suiteFilePath); seleniumProxy.addNewStaticContent(suiteFile.getParentFile()); String suiteURL = startURL + "/selenium-server/" + suiteFile.getName(); HTMLLauncher launcher = new HTMLLauncher(seleniumProxy); result = launcher.runHTMLSuite(browserString, startURL, suiteURL, new File(resultFilePath), timeout, multiWindow); } catch (Exception e) { System.err.println("HTML suite exception seen:"); e.printStackTrace(); System.exit(1); } if (!"PASSED".equals(result)) { System.err.println("Tests failed"); System.exit(1); } else { System.exit(0); } } if (interactive) { AsyncExecute.sleepTight(500); System.out.println("Entering interactive mode... type Selenium commands here (e.g: cmd=open&1=http://www.yahoo.com)"); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; final String[] lastSessionId = new String[]{""}; while ((userInput = stdIn.readLine()) != null) { if ("quit".equals(userInput)) { System.out.println("Stopping..."); seleniumProxy.stop(); System.exit(0); } if ("".equals(userInput)) continue; if (!userInput.startsWith("cmd=") && !userInput.startsWith("commandResult=")) { System.err.println("ERROR - Invalid command: \"" + userInput + "\""); continue; } final boolean newBrowserSession = userInput.indexOf("getNewBrowserSession") != -1; if (userInput.indexOf("sessionId") == -1 && !newBrowserSession) { userInput = userInput + "&sessionId=" + lastSessionId[0]; } final URL url = new URL("http://localhost:" + port + "/selenium-server/driver?" + userInput); Thread t = new Thread(new Runnable() { public void run() { try { SeleniumServer.log("---> Requesting " + url.toString()); URLConnection conn = url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int length = -1; while ((length = is.read(buffer)) != -1) { out.write(buffer, 0, length); } is.close(); String output = out.toString(); if (newBrowserSession) { if (output.startsWith("OK,")) { lastSessionId[0] = output.substring(3); } } } catch (IOException e) { System.err.println(e.getMessage()); if (SeleniumServer.isDebugMode()) { e.printStackTrace(); } } } }); t.start(); } } }
diff --git a/src/com/valfom/skydiving/altimeter/AltimeterActivity.java b/src/com/valfom/skydiving/altimeter/AltimeterActivity.java index 0c4fed8..82866da 100644 --- a/src/com/valfom/skydiving/altimeter/AltimeterActivity.java +++ b/src/com/valfom/skydiving/altimeter/AltimeterActivity.java @@ -1,372 +1,374 @@ package com.valfom.skydiving.altimeter; import java.text.DateFormat; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.ContentValues; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.valfom.skydiving.altimeter.AltimeterCalibrationFragment.OnZeroAltitudeChangedListener; public class AltimeterActivity extends Activity implements SensorEventListener, OnZeroAltitudeChangedListener { private static final String TAG = "AltimeterActivity"; public static final String PREF_FILE_NAME = "SAPrefs"; public static final byte STEP = 10; private SensorManager sensorManager; private Sensor sensorPressure; // private Vibrator vibrator; // private PowerManager.WakeLock wakeLock; private long lastBackPressTime = 0; private Toast toastOnExit; private TextView tvAltitude; private TextView tvAltitudeUnit; private boolean convert = false; private Timer timerSavePoints; private Integer trackId = null; // Altitude private int altitude; private int zeroAltitude; // Vertical speed private Integer firstAltitude = null; private Integer secondAltitude = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); sensorPressure = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); if (sensorPressure != null) { Log.d(TAG, "Barometer: min delay " + sensorPressure.getMinDelay() + ", power " + sensorPressure.getPower() + ", resolution" + sensorPressure.getResolution() + ", max range " + sensorPressure.getMaximumRange()); tvAltitude = (TextView) findViewById(R.id.tvAltitude); tvAltitudeUnit = (TextView) findViewById(R.id.tvAltitudeUnit); ToggleButton tbShowData = (ToggleButton) findViewById(R.id.tbLog); tbShowData.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { SharedPreferences sharedPreferences = getSharedPreferences(PREF_FILE_NAME, Activity.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); if (isChecked) { DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT); String startDate = dateFormat.format(new Date()); dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM); String startTime = dateFormat.format(new Date()); ContentValues values = new ContentValues(); values.put(AltimeterDB.KEY_TRACKS_DATE, startDate); values.put(AltimeterDB.KEY_TRACKS_TIME, startTime); values.put(AltimeterDB.KEY_TRACKS_TYPE, 1); Uri uri = Uri.parse(AltimeterContentProvider.CONTENT_URI_TRACKS + "/insert"); Uri url = getContentResolver().insert(uri, values); String[] arr = url.toString().split("/"); trackId = Integer.valueOf(arr[1]); timerSavePoints = new Timer(); timerSavePoints.schedule(new savePointsTask(), 0, 1000); editor.putBoolean("logging", true); editor.putInt("trackId", trackId); } else { trackId = null; if (timerSavePoints != null) { timerSavePoints.cancel(); timerSavePoints = null; } firstAltitude = null; secondAltitude = null; editor.putBoolean("logging", false); editor.remove("trackId"); } editor.apply(); } }); restoreSharedPreferences(); // vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // PowerManager powerManager = (PowerManager) // getSystemService(Context.POWER_SERVICE); // wakeLock = // powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); // wakeLock.acquire(); // vibrator.vibrate(1000); // wakeLock.release(); // SENSOR_DELAY_NORMAL (200,000 microsecond delay) 200 // SENSOR_DELAY_GAME (20,000 microsecond delay) 200 // SENSOR_DELAY_UI (60,000 microsecond delay) <100 ms // SENSOR_DELAY_FASTEST (0 microsecond delay) 200 ms // As of Android 3.0 (API Level 11) you can also specify the delay // as an absolute value (in microseconds). sensorManager.registerListener(this, sensorPressure, SensorManager.SENSOR_DELAY_FASTEST); } } private void restoreSharedPreferences() { SharedPreferences sharedPreferences = getSharedPreferences(PREF_FILE_NAME, Activity.MODE_PRIVATE); if (sharedPreferences.getBoolean("logging", false)) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean("logging", false); editor.remove("trackId"); editor.apply(); } } private class savePointsTask extends TimerTask { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { int customAltitude; int verticalSpeed = 0; customAltitude = altitude - zeroAltitude; if (firstAltitude != null) { int diffAltitude; secondAltitude = customAltitude; diffAltitude = Math.abs(secondAltitude - firstAltitude); verticalSpeed = diffAltitude; + firstAltitude = secondAltitude; + } else firstAltitude = customAltitude; DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM); String date = dateFormat.format(new Date()); ContentValues values = new ContentValues(); values.put(AltimeterDB.KEY_POINTS_DATE, date); values.put(AltimeterDB.KEY_POINTS_ALTITUDE, customAltitude); values.put(AltimeterDB.KEY_POINTS_SPEED, verticalSpeed); values.put(AltimeterDB.KEY_POINTS_TRACK_ID, trackId); Uri uri = Uri.parse(AltimeterContentProvider.CONTENT_URI_POINTS.toString()); getContentResolver().insert(uri, values); } }); } }; @Override protected void onDestroy() { super.onDestroy(); if (timerSavePoints != null) { timerSavePoints.cancel(); timerSavePoints = null; } restoreSharedPreferences(); sensorManager.unregisterListener(this); } @Override protected void onResume() { super.onResume(); String altitudeUnit; SharedPreferences sharedPreferences; sharedPreferences = getSharedPreferences(PREF_FILE_NAME, Activity.MODE_PRIVATE); zeroAltitude = sharedPreferences.getInt("zeroAltitude", 0); AltimeterSettings settings = new AltimeterSettings(this); altitudeUnit = settings.getAltitudeUnit(); if (altitudeUnit.equals(getString(R.string.ft))) convert = true; else convert = false; tvAltitudeUnit.setText(altitudeUnit); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: Intent settings = new Intent(this, AltimeterPreferenceActivity.class); startActivity(settings); break; case R.id.action_list: Intent list = new Intent(this, AltimeterListActivity.class); startActivity(list); break; case R.id.action_calibrate: FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out); AltimeterCalibrationFragment calibrationFragment = (AltimeterCalibrationFragment) fragmentManager.findFragmentById(R.id.calibration_container); if (calibrationFragment == null) { fragmentTransaction.add(R.id.calibration_container, new AltimeterCalibrationFragment()); // fragmentTransaction.addToBackStack(null); } else { fragmentTransaction.remove(calibrationFragment); } fragmentTransaction.commit(); break; default: break; } return true; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { Log.d(TAG, "Accuracy " + accuracy); } @Override public void onSensorChanged(SensorEvent event) { float atmosphericPressure; int customAltitude; atmosphericPressure = event.values[0]; altitude = (int) SensorManager.getAltitude(SensorManager.PRESSURE_STANDARD_ATMOSPHERE, atmosphericPressure); customAltitude = altitude - zeroAltitude; if (convert) customAltitude = AltimeterSettings.convertAltitudeToFt(customAltitude); tvAltitude.setText(String.valueOf(customAltitude)); } @Override public void onZeroAltitudeChanged(int code) { switch (code) { case AltimeterCalibrationFragment.CODE_DECREASE: zeroAltitude += STEP; break; case AltimeterCalibrationFragment.CODE_SET_TO_ZERO: zeroAltitude = altitude; break; case AltimeterCalibrationFragment.CODE_INCREASE: zeroAltitude -= STEP; break; } SharedPreferences sharedPreferences = getSharedPreferences(PREF_FILE_NAME, Activity.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("zeroAltitude", zeroAltitude); editor.apply(); } @Override public void onBackPressed() { if (lastBackPressTime < (System.currentTimeMillis() - 2000)) { toastOnExit = Toast.makeText(this, getString(R.string.message_on_exit), Toast.LENGTH_SHORT); toastOnExit.show(); lastBackPressTime = System.currentTimeMillis(); } else { if (toastOnExit != null) toastOnExit.cancel(); super.onBackPressed(); } } }
true
false
null
null
diff --git a/src/org/clarent/ivyidea/intellij/facet/IvyIdeaFacetType.java b/src/org/clarent/ivyidea/intellij/facet/IvyIdeaFacetType.java index 1a856c8..f23b9b1 100644 --- a/src/org/clarent/ivyidea/intellij/facet/IvyIdeaFacetType.java +++ b/src/org/clarent/ivyidea/intellij/facet/IvyIdeaFacetType.java @@ -1,86 +1,86 @@ package org.clarent.ivyidea.intellij.facet; import com.intellij.facet.Facet; import com.intellij.facet.FacetType; import com.intellij.facet.FacetTypeId; import com.intellij.facet.autodetecting.FacetDetector; import com.intellij.facet.autodetecting.FacetDetectorRegistry; import com.intellij.openapi.module.Module; import com.intellij.openapi.util.Condition; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileFilter; import com.intellij.psi.PsiFile; import org.clarent.ivyidea.intellij.IvyFileType; import org.clarent.ivyidea.intellij.ui.IvyIdeaIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; /** * @author Guy Mahieu */ public class IvyIdeaFacetType extends FacetType<IvyIdeaFacet, IvyIdeaFacetConfiguration> { public static final FacetTypeId<IvyIdeaFacet> ID = new FacetTypeId<IvyIdeaFacet>("IvyIDEA"); public IvyIdeaFacetType() { super(ID, "IvyIDEA", "IvyIDEA"); } public IvyIdeaFacetConfiguration createDefaultConfiguration() { return new IvyIdeaFacetConfiguration(); } public IvyIdeaFacet createFacet(@NotNull Module module, String name, @NotNull IvyIdeaFacetConfiguration configuration, @Nullable Facet underlyingFacet) { return new IvyIdeaFacet(this, module, name, configuration, underlyingFacet); } public javax.swing.Icon getIcon() { return IvyIdeaIcons.MAIN_ICON_SMALL; } public void registerDetectors(FacetDetectorRegistry<IvyIdeaFacetConfiguration> ivyIdeaDetectorRegistry) { VirtualFileFilter virtualFileFilter = new VirtualFileFilter() { public boolean accept(VirtualFile file) { return "ivy.xml".equals(file.getName()); } }; ivyIdeaDetectorRegistry.registerUniversalDetector(IvyFileType.IVY_FILE_TYPE, virtualFileFilter, new FacetDetector<VirtualFile, IvyIdeaFacetConfiguration>() { public IvyIdeaFacetConfiguration detectFacet(VirtualFile source, Collection<IvyIdeaFacetConfiguration> existentFacetConfigurations) { return configureDetectedFacet(source, existentFacetConfigurations); } }); ivyIdeaDetectorRegistry.registerOnTheFlyDetector(IvyFileType.IVY_FILE_TYPE, virtualFileFilter, new Condition<PsiFile>() { public boolean value(PsiFile psiFile) { return true; } }, new FacetDetector<PsiFile, IvyIdeaFacetConfiguration>() { public IvyIdeaFacetConfiguration detectFacet(PsiFile source, Collection<IvyIdeaFacetConfiguration> existentFacetConfigurations) { return configureDetectedFacet(source.getVirtualFile(), existentFacetConfigurations); } }); ivyIdeaDetectorRegistry.registerDetectorForWizard(IvyFileType.IVY_FILE_TYPE, virtualFileFilter, new FacetDetector<VirtualFile, IvyIdeaFacetConfiguration>() { public IvyIdeaFacetConfiguration detectFacet(VirtualFile source, Collection<IvyIdeaFacetConfiguration> existentFacetConfigurations) { return configureDetectedFacet(source, existentFacetConfigurations); } }); } protected IvyIdeaFacetConfiguration configureDetectedFacet(VirtualFile ivyFile, Collection<IvyIdeaFacetConfiguration> existingFacetConfigurations) { if (existingFacetConfigurations.isEmpty()) { final IvyIdeaFacetConfiguration defaultConfiguration = createDefaultConfiguration(); - defaultConfiguration.setIvyFile(ivyFile.getUrl()); + defaultConfiguration.setIvyFile(ivyFile.getPath()); return defaultConfiguration; } else { // TODO: only use file that is the closest to the iml file! // http://code.google.com/p/ivyidea/issues/detail?id=1 return existingFacetConfigurations.iterator().next(); } } }
true
false
null
null
diff --git a/src/java/org/apache/hadoop/mapred/DefaultJobHistoryParser.java b/src/java/org/apache/hadoop/mapred/DefaultJobHistoryParser.java index c9ded3861..7e9961323 100644 --- a/src/java/org/apache/hadoop/mapred/DefaultJobHistoryParser.java +++ b/src/java/org/apache/hadoop/mapred/DefaultJobHistoryParser.java @@ -1,188 +1,201 @@ package org.apache.hadoop.mapred; import java.util.*; import java.io.*; import org.apache.hadoop.mapred.JobHistory.Keys; -import org.apache.hadoop.mapred.JobHistory.Values;; +import org.apache.hadoop.mapred.JobHistory.Values; /** * Default parser for job history files. It creates object model from * job history file. * */ public class DefaultJobHistoryParser { + // This class is required to work around the Java compiler's lack of + // run-time information on generic classes. In particular, we need to be able + // to cast to this type without generating compiler warnings, which is only + // possible if it is a non-generic class. + + /** + * Contents of a job history file. Maps: + * <xmp>jobTrackerId -> <jobId, JobHistory.JobInfo>*</xmp> + */ + public static class MasterIndex + extends TreeMap<String, Map<String, JobHistory.JobInfo>> { + + } + /** - * Parses a master index file and returns a Map of - * (jobTrakerId - Map (job Id - JobHistory.JobInfo)). + * Parses a master index file and returns a {@link MasterIndex}. * @param historyFile master index history file. - * @return a map of values, as described as described earlier. + * @return a {@link MasterIndex}. * @throws IOException */ - public static Map<String, Map<String, JobHistory.JobInfo>> parseMasterIndex(File historyFile) + public static MasterIndex parseMasterIndex(File historyFile) throws IOException { MasterIndexParseListener parser = new MasterIndexParseListener(); JobHistory.parseHistory(historyFile, parser); return parser.getValues(); } /** * Populates a JobInfo object from the job's history log file. * @param jobHistoryFile history file for this job. * @param job a precreated JobInfo object, should be non-null. * @throws IOException */ public static void parseJobTasks(File jobHistoryFile, JobHistory.JobInfo job) throws IOException { JobHistory.parseHistory(jobHistoryFile, new JobTasksParseListener(job)); } /** * Listener for Job's history log file, it populates JobHistory.JobInfo * object with data from log file. */ static class JobTasksParseListener implements JobHistory.Listener { JobHistory.JobInfo job; JobTasksParseListener(JobHistory.JobInfo job) { this.job = job; } private JobHistory.Task getTask(String taskId) { JobHistory.Task task = job.getAllTasks().get(taskId); if (null == task) { task = new JobHistory.Task(); task.set(Keys.TASKID, taskId); job.getAllTasks().put(taskId, task); } return task; } private JobHistory.MapAttempt getMapAttempt( String jobid, String jobTrackerId, String taskId, String taskAttemptId) { JobHistory.Task task = getTask(taskId); JobHistory.MapAttempt mapAttempt = (JobHistory.MapAttempt) task.getTaskAttempts().get(taskAttemptId); if (null == mapAttempt) { mapAttempt = new JobHistory.MapAttempt(); mapAttempt.set(Keys.TASK_ATTEMPT_ID, taskAttemptId); task.getTaskAttempts().put(taskAttemptId, mapAttempt); } return mapAttempt; } private JobHistory.ReduceAttempt getReduceAttempt( String jobid, String jobTrackerId, String taskId, String taskAttemptId) { JobHistory.Task task = getTask(taskId); JobHistory.ReduceAttempt reduceAttempt = (JobHistory.ReduceAttempt) task.getTaskAttempts().get(taskAttemptId); if (null == reduceAttempt) { reduceAttempt = new JobHistory.ReduceAttempt(); reduceAttempt.set(Keys.TASK_ATTEMPT_ID, taskAttemptId); task.getTaskAttempts().put(taskAttemptId, reduceAttempt); } return reduceAttempt; } // JobHistory.Listener implementation public void handle(JobHistory.RecordTypes recType, Map<Keys, String> values) throws IOException { String jobTrackerId = values.get(JobHistory.Keys.JOBTRACKERID); String jobid = values.get(Keys.JOBID); if (recType == JobHistory.RecordTypes.Job) { job.handle(values); }if (recType.equals(JobHistory.RecordTypes.Task)) { String taskid = values.get(JobHistory.Keys.TASKID); getTask(taskid).handle(values); } else if (recType.equals(JobHistory.RecordTypes.MapAttempt)) { String taskid = values.get(Keys.TASKID); String mapAttemptId = values.get(Keys.TASK_ATTEMPT_ID); getMapAttempt(jobid, jobTrackerId, taskid, mapAttemptId).handle(values); } else if (recType.equals(JobHistory.RecordTypes.ReduceAttempt)) { String taskid = values.get(Keys.TASKID); String reduceAttemptId = values.get(Keys.TASK_ATTEMPT_ID); getReduceAttempt(jobid, jobTrackerId, taskid, reduceAttemptId).handle(values); } } } /** * Parses and returns a map of values in master index. * @author sanjaydahiya * */ static class MasterIndexParseListener implements JobHistory.Listener { - Map<String, Map<String, JobHistory.JobInfo>> jobTrackerToJobs = new TreeMap<String, Map<String, JobHistory.JobInfo>>(); + MasterIndex jobTrackerToJobs = new MasterIndex(); Map<String, JobHistory.JobInfo> activeJobs = null; String currentTracker; // Implement JobHistory.Listener public void handle(JobHistory.RecordTypes recType, Map<Keys, String> values) throws IOException { if (recType.equals(JobHistory.RecordTypes.Jobtracker)) { activeJobs = new TreeMap<String, JobHistory.JobInfo>(); currentTracker = values.get(Keys.START_TIME); jobTrackerToJobs.put(currentTracker, activeJobs); } else if (recType.equals(JobHistory.RecordTypes.Job)) { String jobId = (String) values.get(Keys.JOBID); JobHistory.JobInfo job = activeJobs.get(jobId); if (null == job) { job = new JobHistory.JobInfo(jobId); job.set(Keys.JOBTRACKERID, currentTracker); activeJobs.put(jobId, job); } job.handle(values); } } /** * Return map of parsed values. * @return */ - Map<String, Map<String, JobHistory.JobInfo>> getValues() { + MasterIndex getValues() { return jobTrackerToJobs; } } // call this only for jobs that succeeded for better results. static class BadNodesFilter implements JobHistory.Listener { private Map<String, Set<String>> badNodesToNumFailedTasks = new HashMap<String, Set<String>>(); Map<String, Set<String>> getValues(){ return badNodesToNumFailedTasks; } public void handle(JobHistory.RecordTypes recType, Map<Keys, String> values) throws IOException { if (recType.equals(JobHistory.RecordTypes.MapAttempt) || recType.equals(JobHistory.RecordTypes.ReduceAttempt)) { if (Values.FAILED.name().equals(values.get(Keys.TASK_STATUS)) ){ String hostName = values.get(Keys.HOSTNAME); String taskid = values.get(Keys.TASKID); Set<String> tasks = badNodesToNumFailedTasks.get(hostName); if (null == tasks ){ tasks = new TreeSet<String>(); tasks.add(taskid); badNodesToNumFailedTasks.put(hostName, tasks); }else{ tasks.add(taskid); } } } } } }
false
false
null
null
diff --git a/src/egit/ClaseC.java b/src/egit/ClaseC.java index 4232d40..c42c793 100644 --- a/src/egit/ClaseC.java +++ b/src/egit/ClaseC.java @@ -1,13 +1,13 @@ package egit; public class ClaseC { private int a; private int b; public void m1(){} public void m2(){} - public void m3(){} + }
true
false
null
null
diff --git a/src/net/sf/freecol/server/generator/River.java b/src/net/sf/freecol/server/generator/River.java index 1e89516a5..09384554b 100644 --- a/src/net/sf/freecol/server/generator/River.java +++ b/src/net/sf/freecol/server/generator/River.java @@ -1,378 +1,382 @@ /** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.server.generator; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.logging.Logger; import net.sf.freecol.FreeCol; import net.sf.freecol.common.PseudoRandom; import net.sf.freecol.common.model.Map; import net.sf.freecol.common.model.Map.Direction; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.TileImprovement; import net.sf.freecol.common.model.TileType; import net.sf.freecol.common.model.Map.Position; /** * A river for the map generator. */ public class River { private static final Logger logger = Logger.getLogger(MapGenerator.class.getName()); - private static final TileType river = FreeCol.getSpecification().getTileType("model.tile.greatRiver"); + private static final TileType greatRiver = FreeCol.getSpecification().getTileType("model.tile.greatRiver"); /** * Directions a river may flow in. * @see net.sf.freecol.common.model.Map */ private static final Direction[] directions = { Direction.NE, Direction.SE, Direction.SW, Direction.NW}; /** * Possible direction changes for a river. * @see net.sf.freecol.common.model.Map */ private static enum DirectionChange { STRAIGHT_AHEAD, RIGHT_TURN, LEFT_TURN; public Direction getNewDirection(Direction oldDirection) { switch(this) { case STRAIGHT_AHEAD: return oldDirection; case RIGHT_TURN: switch(oldDirection) { case NE: return Direction.SE; case SE: return Direction.SW; case SW: return Direction.NW; case NW: return Direction.NE; default: return oldDirection; } case LEFT_TURN: switch(oldDirection) { case NE: return Direction.NW; case SE: return Direction.NE; case SW: return Direction.SE; case NW: return Direction.SW; default: return oldDirection; } } return oldDirection; } } /** * Current direction the river is flowing in. */ private Direction direction; /** * The map on which the river flows. */ private Map map; /** * A list of river sections. */ private ArrayList<RiverSection> sections = new ArrayList<RiverSection>(); /** * The next river. */ private River nextRiver = null; /** * A hashtable of position-river pairs. */ private Hashtable<Position, River> riverMap; /** * Constructor. * * @param map The map on which the river flows. * @param riverMap A hashtable of position-river pairs. */ public River(Map map, Hashtable<Position, River> riverMap) { this.map = map; this.riverMap = riverMap; int length = directions.length; int index = map.getGame().getModelController().getPseudoRandom().nextInt(length); direction = directions[index]; logger.fine("Starting new river flowing " + direction.toString()); } /** * Returns the length of this river. * * @return the length of this river. */ public int getLength() { return this.sections.size(); } public RiverSection getLastSection() { return this.sections.get(sections.size() - 1); } /** * Adds a new section to this river. * * @param position Where this section is located. * @param direction The direction the river is flowing in. */ public void add(Map.Position position, Direction direction) { this.sections.add(new RiverSection(position, direction)); } /** * Increases the size of this river. * * @param lastSection The last section of the river flowing into this one. * @param position The position of the confluence. */ public void grow(RiverSection lastSection, Map.Position position) { boolean found = false; RiverSection section = null; Iterator<RiverSection> sectionIterator = sections.iterator(); while (sectionIterator.hasNext()) { section = sectionIterator.next(); if (found) { section.grow(); } else if (section.getPosition().equals(position)) { section.setBranch(lastSection.direction.getReverseDirection(), lastSection.getSize()); section.grow(); found = true; } } drawToMap(); if (nextRiver != null) { Position neighbor = Map.getAdjacent(section.getPosition(), section.direction); nextRiver.grow(section, neighbor); } } /** * Returns true if the given position is next to this river. * * @param p A map position. * @return true if the given position is next to this river. */ public boolean isNextToSelf(Map.Position p) { for (Direction direction : directions) { Map.Position px = Map.getAdjacent(p, direction); if (this.contains(px)) { return true; } } return false; } /** * Returns true if the given position is next to a river, lake or sea. * * @param p A map position. * @return true if the given position is next to a river, lake or sea. */ public boolean isNextToWater(Map.Position p) { for (Direction direction : directions) { Map.Position px = Map.getAdjacent(p, direction); final Tile tile = map.getTile(px); if (tile == null) { continue; } if (!tile.isLand() || tile.hasRiver()) { return true; } } return false; } /** * Returns true if this river already contains the given position. * * @param p A map position. * @return true if this river already contains the given position. */ public boolean contains(Map.Position p) { Iterator<RiverSection> sectionIterator = sections.iterator(); while (sectionIterator.hasNext()) { Map.Position q = sectionIterator.next().getPosition(); if (p.equals(q)) { return true; } } return false; } /** * Creates a river flowing from the given position if possible. * * @param position A map position. * @return true if a river was created, false otherwise. */ public boolean flowFromSource(Map.Position position) { Tile tile = map.getTile(position); if (!tile.getType().canHaveRiver()) { // Mountains, ocean cannot have rivers logger.fine("Tile (" + tile.getType().getName() + ") at " + position + " cannot have rivers."); return false; } else if (isNextToWater(position)) { logger.fine("Tile at " + position + " is next to water."); return false; } else { logger.fine("Tile at " + position + " is suitable source."); return flow(position); } } /** * Lets the river flow from the given position. * * @param source A map position. * @return true if a river was created, false otherwise. */ private boolean flow(Map.Position source) { //Tile t = map.getTile(source); if (sections.size() % 2 == 0) { // get random new direction int length = DirectionChange.values().length; int index = map.getGame().getModelController().getPseudoRandom().nextInt(length); DirectionChange change = DirectionChange.values()[index]; this.direction = change.getNewDirection(this.direction); logger.fine("Direction is now " + direction); } for (DirectionChange change : DirectionChange.values()) { Direction dir = change.getNewDirection(direction); Map.Position newPosition = Map.getAdjacent(source, dir); Tile nextTile = map.getTile(newPosition); if (nextTile == null) { continue; } // is the tile suitable for this river? if (!nextTile.getType().canHaveRiver()) { // Mountains, ocean cannot have rivers logger.fine("Tile (" + nextTile.getType().getName() + ") at " + newPosition + " cannot have rivers."); continue; } else if (this.contains(newPosition)) { logger.fine("Tile at " + newPosition + " is already in river."); continue; } else if (isNextToSelf(newPosition)) { logger.fine("Tile at " + newPosition + " is next to the river."); continue; } else { // find out if an adjacent tile is next to water for (DirectionChange change2 : DirectionChange.values()) { Direction lastDir = change2.getNewDirection(dir); Map.Position px = Map.getAdjacent(newPosition, lastDir); Tile tile = map.getTile(px); if (tile != null && (!tile.isLand() || tile.hasRiver())) { sections.add(new RiverSection(source, dir)); RiverSection lastSection = new RiverSection(newPosition, lastDir); sections.add(lastSection); if (tile.hasRiver() && tile.isLand()) { logger.fine("Point " + newPosition + " is next to another river."); drawToMap(); // increase the size of another river nextRiver = riverMap.get(px); nextRiver.grow(lastSection, px); } else { // flow into the sea (or a lake) logger.fine("Point " + newPosition + " is next to water."); River someRiver = riverMap.get(px); if (someRiver == null) { sections.add(new RiverSection(px, lastDir.getReverseDirection())); } else { RiverSection waterSection = someRiver.getLastSection(); waterSection.setBranch(lastDir.getReverseDirection(), TileImprovement.SMALL_RIVER); } drawToMap(); } return true; } } // this is not the case logger.fine("Tile at " + newPosition + " is suitable."); sections.add(new RiverSection(source, dir)); return flow(newPosition); } } sections = new ArrayList<RiverSection>(); return false; } /** * Draws the completed river to the map. */ private void drawToMap() { RiverSection oldSection = null; Iterator<RiverSection> sectionIterator = sections.iterator(); while (sectionIterator.hasNext()) { RiverSection section = sectionIterator.next(); riverMap.put(section.getPosition(), this); if (oldSection != null) { section.setBranch(oldSection.direction.getReverseDirection(), oldSection.getSize()); } Tile tile = map.getTile(section.getPosition()); if (section.getSize() == TileImprovement.SMALL_RIVER || section.getSize() == TileImprovement.LARGE_RIVER) { // tile.addRiver(Tile.ADD_RIVER_MAJOR, section.getBranches()); // Depreciated // tile.addRiver will process the neighbouring branches as well tile.addRiver(section.getSize()); logger.fine("Added river (magnitude: " + section.getSize() + ") to tile at " + section.getPosition()); } else if (section.getSize() >= TileImprovement.FJORD_RIVER) { - tile.setType(river); + TileImprovement oldRiver = tile.getRiver(); // save the previous river + tile.setType(greatRiver); // changing the type resets the improvements + tile.addRiver(section.getSize()); + TileImprovement newRiver = tile.getRiver(); + newRiver.setStyle(oldRiver.getStyle()); logger.fine("Created fjord at " + section.getPosition()); } oldSection = section; } } }
false
false
null
null
diff --git a/activiti-cycle/src/main/java/org/activiti/cycle/impl/transform/signavio/RemedyTemporarySignavioIncompatibilityTransformation.java b/activiti-cycle/src/main/java/org/activiti/cycle/impl/transform/signavio/RemedyTemporarySignavioIncompatibilityTransformation.java index 31e12170e..70d5e3bf2 100644 --- a/activiti-cycle/src/main/java/org/activiti/cycle/impl/transform/signavio/RemedyTemporarySignavioIncompatibilityTransformation.java +++ b/activiti-cycle/src/main/java/org/activiti/cycle/impl/transform/signavio/RemedyTemporarySignavioIncompatibilityTransformation.java @@ -1,135 +1,148 @@ package org.activiti.cycle.impl.transform.signavio; /** * Temporary transformation to adjust BPMN 2.0 XML to the version Activiti * understands (there are some minor incompatibilities due to changes in the * final BPMN 2.0 spec. Should be temporary, that's why we did it very very * hacky. * * @author ruecker */ public class RemedyTemporarySignavioIncompatibilityTransformation { public String transformBpmn20Xml(String xml, String processName) { // set process id and name processName = ExchangeSignavioUuidWithNameTransformation.adjustNamesForEngine(processName); xml = setAttributeText(xml, "process", "id", processName); - xml = addAttribute(xml, "process", "name", processName); + if (!existAttribute(xml, "process", "name")) { + xml = addAttribute(xml, "process", "name", processName); + } return transformBpmn20Xml(xml); } public String transformBpmn20Xml(String xml) { // Change upper/lower case problem <exclusiveGateway gatewayDirection="Diverging" xml = exchangeAttributeText(xml, "gatewayDirection", "diverging", "Diverging"); xml = exchangeAttributeText(xml, "gatewayDirection", "converging", "Converging"); xml = exchangeAttributeText(xml, "gatewayDirection", "mixed", "Mixed"); xml = removeAttribute(xml, "processType"); // add namespace (yeah, pretty hacky, I know) xml = addAttribute(xml, "definitions", "xmlns:activiti", "http://activiti.org/bpmn"); // remove BPMN-DI xml = removeElement(xml, "bpmndi:BPMNDiagram"); // remove Signavio extensions xml = removeElement(xml, "signavio:signavioMetaData"); // removed currently unused elements xml = removeElement(xml, "laneSet"); xml = removeElement(xml, "messageEventDefinition"); // removed unused default attributes xml = removeAttribute(xml, "resourceRef"); xml = removeAttribute(xml, "completionQuantity"); xml = removeAttribute(xml, "startQuantity"); xml = removeAttribute(xml, "implementation"); xml = removeAttribute(xml, "completionQuantity"); xml = removeAttribute(xml, "startQuantity"); xml = removeAttribute(xml, "isForCompensation"); xml = removeAttribute(xml, "isInterrupting"); xml = removeAttribute(xml, "isClosed"); xml = removeAttribute(xml, "typeLanguage"); xml = removeAttribute(xml, "expressionLanguage"); xml = removeAttribute(xml, "xmlns:bpmndi"); return xml; } // public static void main(String[] args) { // System.out.println(new // RemedyTemporarySignavioIncompatibilityTransformation().removeAttribute("<process test=\"hallo\" />", // "process", "test")); // System.out.println(new // RemedyTemporarySignavioIncompatibilityTransformation().setAttributeText("<process test=\"hallo\" />", // "process", "test", "bernd")); // System.out // .println(new // RemedyTemporarySignavioIncompatibilityTransformation().exchangeAttributeText("<process test=\"hallo\" />", // "test", "hallo", "bernd")); // System.out.println(new // RemedyTemporarySignavioIncompatibilityTransformation().addAttribute("<process test=\"hallo\" />", // "process", "new", "bernd")); // System.out.println(new // RemedyTemporarySignavioIncompatibilityTransformation().removeElement("<process><test /></process>", // "test")); // System.out.println(new // RemedyTemporarySignavioIncompatibilityTransformation().removeElement("<process><test><hallo /></test>></process>", // "test")); // } private String removeAttribute(String xml, String attributeName) { int startIndex = xml.indexOf(" " + attributeName + "=\""); while (startIndex != -1) { int endIndex = xml.indexOf("\"", startIndex + attributeName.length() + 3); xml = xml.substring(0, startIndex) + xml.substring(endIndex + 1); startIndex = xml.indexOf(" " + attributeName + "=\""); } return xml; } private String setAttributeText(String xml, String element, String attributeName, String newValue) { int elementStartIndex = xml.indexOf("<" + element); if (elementStartIndex == -1) return xml; int startIndex = xml.indexOf(attributeName + "=\"", elementStartIndex) + attributeName.length() + 2; - if (startIndex == -1) + if (startIndex == -1) { return xml; + } int endIndex = xml.indexOf("\"", startIndex); return xml.substring(0, startIndex) + newValue + xml.substring(endIndex); } + private boolean existAttribute(String xml, String elementName, String attributeName) { + int elementStartIndex = xml.indexOf("<" + elementName); + if (elementStartIndex == -1) + return false; + int elementEndIndex = xml.indexOf(">", elementStartIndex); + xml = xml.substring(0, elementEndIndex); + int startIndex = xml.indexOf(attributeName + "=\"", elementStartIndex); + return (startIndex > -1); + } + private String exchangeAttributeText(String xml, String attributeName, String oldValue, String newValue) { return xml.replaceAll(attributeName + "=\"" + oldValue + "\"", attributeName + "=\"" + newValue + "\""); } private String addAttribute(String xml, String elementName, String attributeName, String value) { int index = xml.indexOf("<" + elementName + " ") + elementName.length() + 2; if (index == 0) return xml; return xml.substring(0, index) + attributeName + "=\"" + value + "\" " + xml.substring(index); } private String removeElement(String xml, String elementName) { int startIndex = xml.indexOf("<" + elementName); while (startIndex != -1) { int endIndex = xml.indexOf("</" + elementName + ">"); if (endIndex != -1) { endIndex = endIndex + elementName.length() + 3; } else { endIndex = xml.indexOf("/>", startIndex) + 2; } String lastPartOfString = xml.substring(endIndex); xml = xml.substring(0, startIndex) + lastPartOfString; startIndex = xml.indexOf("<" + elementName); } return xml; } }
false
false
null
null
diff --git a/src/org/dancres/paxos/Leader.java b/src/org/dancres/paxos/Leader.java index 5caf9ef..ea17600 100644 --- a/src/org/dancres/paxos/Leader.java +++ b/src/org/dancres/paxos/Leader.java @@ -1,614 +1,632 @@ package org.dancres.paxos; import org.dancres.paxos.messages.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; /** * Implements the leader state machine. * * @author dan */ public class Leader implements MembershipListener { private static final Logger _logger = LoggerFactory.getLogger(Leader.class); /* * Used to compute the timeout period for watchdog tasks. In order to behave sanely we want the failure * detector to be given the best possible chance of detecting problems with the members. Thus the timeout for the * watchdog is computed as the unresponsiveness threshold of the failure detector plus a grace period. */ private static final long FAILURE_DETECTOR_GRACE_PERIOD = 2000; /* * Internal states */ private static final int COLLECT = 0; private static final int BEGIN = 1; private static final int SUCCESS = 2; private static final int EXIT = 3; private static final int ABORT = 4; private static final int RECOVER = 5; private static final int COMMITTED = 6; private static final int SUBMITTED = 7; /** * Indicates the Leader is not ready to process the passed message and the caller should retry. */ public static final int BUSY = 256; /** * Indicates the Leader has accepted the message and is waiting for further messages. */ public static final int ACCEPTED = 257; private final Timer _watchdog = new Timer("Leader watchdog"); private final long _watchdogTimeout; private final FailureDetector _detector; private final NodeId _nodeId; private final Transport _transport; private final AcceptorLearner _al; private long _seqNum = LogStorage.EMPTY_LOG; /** * Tracks the round number this leader used last. This cannot be stored in the acceptor/learner's version without * risking breaking the collect protocol (the al could suddenly believe it's seen a collect it hasn't and become * noisy when it should be silent). This field can be updated as the result of OldRound messages. */ private long _rndNumber = 0; /** * The current value the leader is using for a proposal. Might be sourced from _clientOp but can also come from * Last messages as part of recovery. */ private byte[] _value; /* private boolean _checkLeader = true; */ /** * Note that being the leader is merely an optimisation and saves on sending COLLECTs. Thus if one thread * establishes we're leader and a prior thread decides otherwise with the latter being last to update this variable * we'll simply do an unnecessary COLLECT. The protocol execution will still be correct. */ private boolean _isLeader = false; /** * When in recovery mode we perform collect for each sequence number in the recovery range */ private boolean _isRecovery = false; private long _lowWatermark; private long _highWatermark; /** * Maintains the current client request. The actual sequence number and value the state machine operates on are * held in <code>_seqNum</code> and <code>_value</code> and during recovery will not be the same as the client * request. Thus we cache the client request and move it into the operating variables once recovery is complete. */ private Operation _clientOp; private TimerTask _activeAlarm; private Membership _membership; private int _stage = EXIT; /** * In cases of ABORT, indicates the reason */ private Completion _completion; private List<PaxosMessage> _messages = new ArrayList<PaxosMessage>(); public Leader(FailureDetector aDetector, NodeId aNodeId, Transport aTransport, AcceptorLearner anAcceptorLearner) { _nodeId = aNodeId; _detector = aDetector; _transport = aTransport; _watchdogTimeout = _detector.getUnresponsivenessThreshold() + FAILURE_DETECTOR_GRACE_PERIOD; _al = anAcceptorLearner; } /* public void setLeaderCheck(boolean aCheck) { _logger.warn("Setting leader check: " + aCheck); synchronized(this) { _checkLeader = aCheck; } } */ private long getRndNumber() { return _rndNumber; } private long newRndNumber() { return ++_rndNumber; } + /** + * @param anOldRound is the instance to update from + */ private void updateRndNumber(OldRound anOldRound) { - _rndNumber = anOldRound.getLastRound() + 1; + updateRndNumber(anOldRound.getLastRound()); + } + + /** + * Updates the leader's view of what the current round number is. We don't increment it here, that's done when + * we attempt to become leader. We're only concerned here with having as up-to-date view as possible of what + * the current view is. + * + * @param aNumber the round number we wish to update to + */ + private void updateRndNumber(long aNumber) { + _rndNumber = aNumber; } private boolean isRecovery() { return _isRecovery; } private void amRecovery() { _isRecovery = true; } private void notRecovery() { _isRecovery = false; } private boolean isLeader() { return _isLeader; } private void amLeader() { _isLeader = true; } private void notLeader() { _isLeader = false; } public NodeId getNodeId() { return _nodeId; } /** * Do actions for the state we are now in. Essentially, we're always one state ahead of the participants thus we * process the result of a Collect in the BEGIN state which means we expect Last or OldRound and in SUCCESS state * we expect ACCEPT or OLDROUND */ private void process() { switch(_stage) { case ABORT : case EXIT : { _logger.info("Leader reached " + _completion); if (_membership != null) _membership.dispose(); // Acceptor/learner generates events for successful negotiation itself, we generate failures // if (_stage != EXIT) { _al.signal(_completion); } return; } case SUBMITTED : { /* if (_checkLeader && !_detector.amLeader(_nodeId)) { failed(); error(Reasons.OTHER_LEADER, _detector.getLeader()); return ; } */ _membership = _detector.getMembers(this); _logger.info("Got membership for leader: " + Long.toHexString(_seqNum) + ", (" + _membership.getSize() + ")"); // Collect will decide if it can skip straight to a begin // _stage = COLLECT; process(); break; } case COLLECT : { if ((! isLeader()) && (! isRecovery())) { /* * If the Acceptor/Learner thinks there's a valid leader and the failure detector confirms * liveness, reject the request */ Collect myLastCollect = _al.getLastCollect(); // Collect is INITIAL means no leader known so try to become leader // if (! myLastCollect.isInitial()) { NodeId myOtherLeader = NodeId.from(myLastCollect.getNodeId()); if (_detector.isLive(myOtherLeader)) { error(Reasons.OTHER_LEADER, myOtherLeader); } } + // Best guess for a round number is the acceptor/learner + // + updateRndNumber(myLastCollect.getRndNumber()); + // Best guess for starting sequence number is the acceptor/learner // _seqNum = _al.getLowWatermark(); // Possibility we're starting from scratch // if (_seqNum == LogStorage.EMPTY_LOG) _seqNum = 0; _stage = RECOVER; emitCollect(); } else if (isRecovery()) { ++_seqNum; if (_seqNum > _highWatermark) { // Recovery is complete // notRecovery(); amLeader(); _logger.info("Recovery complete - we're leader doing begin with client value"); _value = _clientOp.getValue(); _stage = BEGIN; process(); } else { _value = LogStorage.NO_VALUE; _stage = BEGIN; emitCollect(); } } else if (isLeader()) { _logger.info("Skipping collect phase - we're leader already"); _value = _clientOp.getValue(); ++_seqNum; _stage = BEGIN; process(); } break; } case RECOVER : { // Compute low and high watermarks // long myMinSeq = -1; long myMaxSeq = -1; Iterator<PaxosMessage> myMessages = _messages.iterator(); while (myMessages.hasNext()) { PaxosMessage myMessage = myMessages.next(); if (myMessage.getType() == Operations.OLDROUND) { /* * An OldRound here indicates some other leader is present and we're only computing the * range for recovery thus we just give up and exit */ oldRound(myMessage); return; } else { Last myLast = (Last) myMessage; long myLow = myLast.getLowWatermark(); long myHigh = myLast.getHighWatermark(); if (myLow != LogStorage.EMPTY_LOG) { if (myLow < myMinSeq) myMinSeq = myLow; } if (myHigh != LogStorage.EMPTY_LOG) { if (myHigh > myMaxSeq) { myMaxSeq = myHigh; } } } } amRecovery(); _lowWatermark = myMinSeq; _highWatermark = myMaxSeq; /* * Collect always increments the sequence number so we must allow for that when figuring out where to * start from low watermark */ if (_lowWatermark == -1) _seqNum = -1; else _seqNum = _lowWatermark - 1; _logger.info("Recovery started: " + _lowWatermark + " ->" + _highWatermark + " (" + _seqNum + ") "); _stage = COLLECT; process(); break; } case BEGIN : { byte[] myValue = _value; /* * If we're not currently the leader, we'll have issued a collect and must process the responses. * We'll be in recovery so we're interested in resolving any outstanding sequence numbers thus our * proposal must be constrained by whatever values the acceptor/learners already know about */ if (! isLeader()) { // Process _messages to assess what we do next - might be to launch a new round or to give up // long myMaxRound = 0; Iterator<PaxosMessage> myMessages = _messages.iterator(); while (myMessages.hasNext()) { PaxosMessage myMessage = myMessages.next(); if (myMessage.getType() == Operations.OLDROUND) { oldRound(myMessage); return; } else { Last myLast = (Last) myMessage; if (myLast.getRndNumber() > myMaxRound) { myMaxRound = myLast.getRndNumber(); myValue = myLast.getValue(); } } } } _value = myValue; emitBegin(); _stage = SUCCESS; break; } case SUCCESS : { /* * Old round message, causes start at collect or quit. If Accept messages total more than majority * we're happy, send Success wait for all acks or redo collect. Note that if we receive OldRound * here we haven't proposed a value (we do that when we emit success) thus if we die after this point * the worst case would be an empty entry in the log with no filled in value. If we succeed here * we've essentially reserved a slot in the log for the specified sequence number and it's up to us * to fill it with the value we want. */ int myAcceptCount = 0; Iterator<PaxosMessage> myMessages = _messages.iterator(); while (myMessages.hasNext()) { PaxosMessage myMessage = myMessages.next(); if (myMessage.getType() == Operations.OLDROUND) { oldRound(myMessage); return; } else { myAcceptCount++; } } if (myAcceptCount >= _membership.getMajority()) { // Send success, wait for acks // emitSuccess(); _stage = COMMITTED; } else { // Need another try, didn't get enough accepts but didn't get leader conflict // emitBegin(); _stage = SUCCESS; } break; } case COMMITTED : { /* * If ACK messages total more than majority we're happy otherwise try again. */ if (_messages.size() >= _membership.getMajority()) { successful(Reasons.OK, null); } else { // Need another try, didn't get enough accepts but didn't get leader conflict // emitSuccess(); _stage = COMMITTED; } break; } default : throw new RuntimeException("Invalid state: " + _stage); } } /** * @param aMessage is an OldRound message received from some other node */ private void oldRound(PaxosMessage aMessage) { failed(); OldRound myOldRound = (OldRound) aMessage; NodeId myCompetingNodeId = NodeId.from(myOldRound.getNodeId()); + updateRndNumber(myOldRound); + /* * Some other node is active, we should abort if they are the leader by virtue of a larger nodeId */ if (myCompetingNodeId.leads(_nodeId)) { _logger.info("Superior leader is active, backing down: " + myCompetingNodeId + ", " + _nodeId); error(Reasons.OTHER_LEADER, myCompetingNodeId); return; } - updateRndNumber(myOldRound); - /* * Some other leader is active but we are superior, restart negotiations with COLLECT, note we must mark * ourselves as not the leader (as has been done above) because having re-established leadership we must * perform recovery and then attempt to submit the client's value (if any) again. */ _stage = COLLECT; process(); } private void successful(int aReason, Object aContext) { _stage = EXIT; _completion = new Completion(aReason, _seqNum, _value, aContext); process(); } private void error(int aReason, Object aContext) { _stage = ABORT; _completion = new Completion(aReason, _seqNum, _value, aContext); process(); } /** * If we timed out or lost membership, we're potentially no longer leader and need to run recovery to get back to * the right sequence number. */ private void failed() { notLeader(); notRecovery(); } private void emitCollect() { _messages.clear(); PaxosMessage myMessage = new Collect(_seqNum, newRndNumber(), _nodeId.asLong()); startInteraction(); _logger.info("Leader sending collect: " + Long.toHexString(_seqNum)); _transport.send(myMessage, NodeId.BROADCAST); } private void emitBegin() { _messages.clear(); PaxosMessage myMessage = new Begin(_seqNum, getRndNumber(), _nodeId.asLong()); startInteraction(); _logger.info("Leader sending begin: " + Long.toHexString(_seqNum)); _transport.send(myMessage, NodeId.BROADCAST); } private void emitSuccess() { _messages.clear(); PaxosMessage myMessage = new Success(_seqNum, _value); startInteraction(); _logger.info("Leader sending success: " + Long.toHexString(_seqNum)); _transport.send(myMessage, NodeId.BROADCAST); } private void startInteraction() { _activeAlarm = new Alarm(); _watchdog.schedule(_activeAlarm, _watchdogTimeout); _membership.startInteraction(); } /** * @todo If we get ABORT, we could try a new round from scratch or make the client re-submit or ..... */ public void abort() { _logger.info("Membership requested abort: " + Long.toHexString(_seqNum)); _activeAlarm.cancel(); synchronized(this) { failed(); error(Reasons.BAD_MEMBERSHIP, null); } } private void expired() { _logger.info("Watchdog requested abort: " + Long.toHexString(_seqNum)); synchronized(this) { failed(); error(Reasons.VOTE_TIMEOUT, null); } } public void allReceived() { _activeAlarm.cancel(); synchronized(this) { process(); } } /** * Request a vote on a value. * * @param anOp is the value to attempt to agree upon * @return BUSY if the state machine is already attempting to get a decision on some vote other ACCEPTED. */ public int submit(Operation anOp) { synchronized (this) { if ((_stage != ABORT) && (_stage != EXIT)) { return BUSY; } _clientOp = anOp; _logger.info("Initialising leader: " + Long.toHexString(_seqNum)); _stage = SUBMITTED; process(); } return ACCEPTED; } /** * Used to process all core paxos protocol messages. * * @param aMessage is a message from some acceptor/learner * @param aNodeId is the address from which the message was sent */ public void messageReceived(PaxosMessage aMessage, NodeId aNodeId) { _logger.info("Leader received message: " + aMessage); synchronized (this) { if (aMessage.getSeqNum() == _seqNum) { _messages.add(aMessage); _membership.receivedResponse(aNodeId); } else { _logger.warn("Unexpected message received: " + aMessage.getSeqNum() + " (" + Long.toHexString(_seqNum) + ")"); } } _logger.info("Leader processed message: " + aMessage); } private class Alarm extends TimerTask { public void run() { expired(); } } }
false
false
null
null
diff --git a/benchmark/src/com/sun/sgs/benchmark/scripts/DirectSend.java b/benchmark/src/com/sun/sgs/benchmark/scripts/DirectSend.java index a143af596..144ec5f19 100644 --- a/benchmark/src/com/sun/sgs/benchmark/scripts/DirectSend.java +++ b/benchmark/src/com/sun/sgs/benchmark/scripts/DirectSend.java @@ -1,105 +1,105 @@ package com.sun.sgs.benchmark.scripts; import com.sun.sgs.benchmark.client.*; import java.text.ParseException; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class DirectSend { static final int DEFAULT_CLIENTS = 60; static final long DEFAULT_DELAY = 500; static final int DEFAULT_BYTES = 500;//1 << 12; private final int clients; private final long delay; private final int bytes; public DirectSend(int clients, long delay, int bytes) { this.clients = clients; this.delay = delay; this.bytes = bytes; System.out.println("Starting up with #client=" + clients + ", delay=" + delay + "ms, bytes=" + bytes + "."); } public DirectSend() { this(DEFAULT_CLIENTS, DEFAULT_DELAY, DEFAULT_BYTES); } public void run() { List<Thread> threads = new LinkedList<Thread>(); StringBuffer sb = new StringBuffer(); for (int i=0; i < clients; i++) sb.append("A"); final String cmdArg = sb.toString(); for (int i = 0; i < clients; ++i) { final int j = i; threads.add(new Thread() { public void run() { try { BenchmarkClient c = new BenchmarkClient(); c.printCommands(false); c.printNotices(true); c.processInput("config dstar2"); c.processInput("login sender-" + j + " pswd"); c.processInput("wait_for login"); Thread.sleep(1000); while (true) { sleep(delay); c.processInput("noop " + cmdArg); } } catch (Throwable t) { t.printStackTrace(); } } }); } try { Thread.sleep(1000); } catch (Throwable t) { } for (Thread t : threads) { t.start(); try { //Thread.sleep(50 + (int)(100 * Math.random())); Thread.sleep(1000); } catch (InterruptedException ie) { } // silent } } private static void usage() { System.out.println("Usage: java DirectSend " + "<#clients> <delay (ms)> <message size (bytes)>"); } public static void main(String[] args) { if (args.length > 0) { - if (args.length != 4) { + if (args.length != 3) { usage(); } else { int clients = 0, delay = 0, bytes = 0; try { clients = Integer.parseInt(args[0]); - delay = Integer.parseInt(args[2]); - bytes = Integer.parseInt(args[3]); + delay = Integer.parseInt(args[1]); + bytes = Integer.parseInt(args[2]); new DirectSend(clients,delay,bytes).run(); } catch (Throwable t) { usage(); } } } else { new DirectSend().run(); } } }
false
false
null
null
diff --git a/src/net/timendum/denis/message/Message.java b/src/net/timendum/denis/message/Message.java index dd52f46..710d2d5 100644 --- a/src/net/timendum/denis/message/Message.java +++ b/src/net/timendum/denis/message/Message.java @@ -1,156 +1,153 @@ package net.timendum.denis.message; import java.io.IOException; import java.util.Collections; import java.util.LinkedList; import java.util.List; import net.timendum.denis.DomainNameCompressor; import net.timendum.denis.io.ArrayDataInputStream; import net.timendum.denis.io.ArrayDataOutputStream; import net.timendum.denis.message.resources.Resource; import net.timendum.denis.rfc.Flags; import net.timendum.denis.rfc.Opcode; public class Message implements Cloneable { private Header header; /** *Questions */ private List<Question> qd = new LinkedList<Question>(); /** * Answer */ private List<Resource> an = new LinkedList<Resource>(); /** * Authority records. */ private List<Resource> ns = new LinkedList<Resource>(); /** * Additional records. */ private List<Resource> ar = new LinkedList<Resource>(); public Message() { header = Header.newHeader(); } public Message(Header header) { header = this.header; } public void addQuestion(String qName, int type, int dClass) { addQuestion(Question.newQuestion(qName, type, dClass)); } public void addQuestion(Question q) { qd.add(q); header.incrementQdCount(); } public static Message newQuery(String qName, int type, int dClass) { Message m = newQuery(); m.addQuestion(qName, type, dClass); return m; } public static Message newQuery() { Message m = new Message(); m.setQuery(); return m; } public void setQuery() { header.setOpcode(Opcode.QUERY); header.setFlag(Flags.RD); } public static Message read(ArrayDataInputStream dis, DomainNameCompressor dnc) throws IOException { Message message = new Message(); message.header = Header.read(dis, dnc); int count = message.header.getQdCount(); for (int i = 0; i < count; i++) { message.qd.add(Question.read(dis, dnc)); } count = message.header.getAnCount(); for (int i = 0; i < count; i++) { message.an.add(Resource.read(dis, dnc)); } count = message.header.getNsCount(); for (int i = 0; i < count; i++) { message.ns.add(Resource.read(dis, dnc)); } count = message.header.getArCount(); for (int i = 0; i < count; i++) { message.ar.add(Resource.read(dis, dnc)); } return message; } public void write(ArrayDataOutputStream dos) { header.write(dos); - for (Question q : qd) { - q.write(dos); - } int count = header.getQdCount(); for (int i = 0; i < count; i++) { qd.get(i).write(dos); } count = header.getAnCount(); for (int i = 0; i < count; i++) { an.get(i).write(dos); } count = header.getNsCount(); for (int i = 0; i < count; i++) { ns.get(i).write(dos); } count = header.getArCount(); for (int i = 0; i < count; i++) { ar.get(i).write(dos); } } public List<Question> getQd() { return Collections.unmodifiableList(qd); } @Override public Message clone() { Message m = new Message(); m.header = header.clone(); for (Question q : qd) { m.qd.add(q.clone()); } for (Resource r : an) { m.an.add(r.clone()); } for (Resource r : ns) { m.ns.add(r.clone()); } for (Resource r : ar) { m.ar.add(r.clone()); } return m; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Message [header="); builder.append(header); builder.append(", qd="); builder.append(qd); builder.append(", an="); builder.append(an); builder.append(", ns="); builder.append(ns); builder.append(", ar="); builder.append(ar); builder.append("]"); return builder.toString(); } }
true
false
null
null
diff --git a/src/com/bergerkiller/bukkit/nolagg/tnt/TNTHandler.java b/src/com/bergerkiller/bukkit/nolagg/tnt/TNTHandler.java index f59b50f..1e53ab2 100644 --- a/src/com/bergerkiller/bukkit/nolagg/tnt/TNTHandler.java +++ b/src/com/bergerkiller/bukkit/nolagg/tnt/TNTHandler.java @@ -1,203 +1,216 @@ package com.bergerkiller.bukkit.nolagg.tnt; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.logging.Level; import net.minecraft.server.Chunk; import net.minecraft.server.Packet60Explosion; import net.minecraft.server.WorldServer; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.entity.TNTPrimed; import org.bukkit.event.entity.EntityExplodeEvent; import com.bergerkiller.bukkit.common.BlockLocation; import com.bergerkiller.bukkit.common.BlockSet; import com.bergerkiller.bukkit.common.Task; import com.bergerkiller.bukkit.common.utils.PacketUtil; import com.bergerkiller.bukkit.common.utils.WorldUtil; import com.bergerkiller.bukkit.nolagg.NoLagg; public class TNTHandler { private static Queue<Block> todo = new LinkedList<Block>(); private static BlockSet added = new BlockSet(); private static Task task; public static int interval; public static int rate; public static int explosionRate; private static long sentExplosions = 0; private static long intervalCounter = 0; public static boolean changeBlocks = true; public static int getBufferCount() { return todo.size(); } public static void init() { // start the task if (interval > 0) { task = new Task(NoLagg.plugin) { public void run() { if (added == null) return; if (todo == null) return; if (denyExplosionsCounter > 0) { --denyExplosionsCounter; } sentExplosions = 0; if (intervalCounter == interval) { intervalCounter = 1; CustomExplosion.useQuickDamageMode = todo.size() > 500; - if (todo.isEmpty()) + if (todo.isEmpty()) { return; + } for (int i = 0; i < rate; i++) { Block next = todo.poll(); if (next == null) break; added.remove(next); int x = next.getX(); int y = next.getY(); int z = next.getZ(); - if (next.getWorld().isChunkLoaded(x >> 4, z >> 4)) { + int cx = x >> 4; + int cz = z >> 4; + int dcx, dcz; + boolean isLoaded = true; + for (dcx = -2; dcx <= 5 && isLoaded; dcx++) { + for (dcz = -2; dcz <= 5 && isLoaded; dcz++) { + if (!WorldUtil.isLoaded(next.getWorld(), cx + dcx, cz+ dcz)) { + isLoaded = false; + } + } + } + if (isLoaded) { Chunk chunk = WorldUtil.getNative(next.getChunk()); if (chunk.getTypeId(x & 15, y, z & 15) == Material.TNT.getId()) { chunk.world.setTypeId(x, y, z, 0); TNTPrimed tnt = next.getWorld().spawn(next.getLocation().add(0.5, 0.5, 0.5), TNTPrimed.class); int fuse = tnt.getFuseTicks(); fuse = nextRandom(tnt.getWorld(), fuse >> 2) + fuse >> 3; tnt.setFuseTicks(fuse); } } } } else { intervalCounter++; } } }.start(1, 1); } } public static void deinit() { Task.stop(task); added = null; todo = null; } private static int nextRandom(World w, int n) { net.minecraft.server.World world = ((CraftWorld) w).getHandle(); return world.random.nextInt(n); } - private static int denyExplosionsCounter = 0; // tick countdown to deny explosions + private static int denyExplosionsCounter = 0; // tick countdown to deny + // explosions public static void clear(World world) { Iterator<BlockLocation> iter = added.iterator(); while (iter.hasNext()) { if (iter.next().world.equals(world.getName())) { iter.remove(); } } Iterator<Block> iter2 = todo.iterator(); while (iter2.hasNext()) { if (iter2.next().getWorld() == world) { iter.remove(); } } denyExplosionsCounter = 5; } public static void clear() { todo.clear(); added.clear(); denyExplosionsCounter = 5; } public static boolean isScheduledForDetonation(Block block) { return added.contains(block); } /* * Detonates TNT and creates explosions Returns false if it was not possible * to do in any way (Including if the feature is disabled) */ public static boolean detonate(Block tntBlock) { if (added == null) return false; if (todo == null) return false; if (interval <= 0) return false; if (tntBlock != null) { // && tntBlock.getType() == Material.TNT) { if (added.add(tntBlock)) { todo.offer(tntBlock); return true; } } return false; } private static boolean allowdrops = true; public static boolean createExplosion(EntityExplodeEvent event) { return createExplosion(event.getLocation(), event.blockList(), event.getYield()); } public static boolean createExplosion(Location at, List<Block> affectedBlocks, float yield) { if (interval > 0) { if (denyExplosionsCounter == 0) { try { WorldServer world = ((CraftWorld) at.getWorld()).getHandle(); int id; int x, y, z; for (Block b : affectedBlocks) { id = b.getTypeId(); x = b.getX(); y = b.getY(); z = b.getZ(); if (id == Material.TNT.getId()) { detonate(b); } else { if (id != Material.FIRE.getId()) { net.minecraft.server.Block bb = net.minecraft.server.Block.byId[id]; if (bb != null && allowdrops) { try { bb.dropNaturally(world, x, y, z, b.getData(), yield, 0); } catch (Throwable t) { NoLaggTNT.plugin.log(Level.SEVERE, "Failed to spawn block drops during explosions!"); t.printStackTrace(); allowdrops = false; } } b.setTypeId(0); } } } if (sentExplosions < explosionRate) { ++sentExplosions; Packet60Explosion packet = new Packet60Explosion(at.getX(), at.getY(), at.getZ(), yield, Collections.EMPTY_LIST, null); PacketUtil.broadcastPacketNearby(at, 64.0, packet); world.makeSound(at.getX(), at.getY(), at.getZ(), "random.explode", 4.0f, (1.0f + (world.random.nextFloat() - world.random.nextFloat()) * 0.2f) * 0.7f); } } catch (Throwable t) { NoLaggTNT.plugin.log(Level.WARNING, "Explosion did not go as planned!"); t.printStackTrace(); } } return true; } else { return false; } } }
false
false
null
null
diff --git a/RoverPanel.java b/RoverPanel.java index 033dc87..136ec59 100644 --- a/RoverPanel.java +++ b/RoverPanel.java @@ -1,323 +1,331 @@ //******************************************************************** // RoverPanel.java // //******************************************************************** import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.geom.*; import java.lang.*; public class RoverPanel extends JPanel implements ActionListener, KeyListener { private static Font sanSerifFont = new Font("SanSerif", Font.PLAIN, 12); private int width = 800, height = 800; public int delay=5; private final int IMAGE_SIZE = 35; private ImageIcon image; private JButton faster,slower,pause; private JButton modeButton; private Timer timer; private double x, y, moveX, moveY; private double roverRotation, wheelRotation, rotationSpeed, roverRotationSpeed; private boolean mode; //mode = false -> Ackermann, mode = true -> Crab //----------------------------------------------------------------- // Sets up the panel, including the timer for the animation. //----------------------------------------------------------------- public RoverPanel() { timer = new Timer(delay, this); x = 200; y = 700; moveX = 0; moveY =0; roverRotation = wheelRotation = 0; rotationSpeed=0; roverRotationSpeed=0; mode = false; setFocusable(false); addKeyListener(this); setFocusable(true); setFocusTraversalKeysEnabled(false); setPreferredSize (new Dimension(width, height)); setBackground (Color.lightGray); timer.start(); } //----------------------------------------------------------------- // Draws the image in the current location. //----------------------------------------------------------------- @Override public void paintComponent (Graphics page) { this.height=getHeight(); this.width=getWidth(); super.paintComponent (page); Graphics2D g2d = (Graphics2D) page; g2d.setFont(sanSerifFont); FontMetrics fm = g2d.getFontMetrics(); //Add in obstacles g2d.setColor(Color.orange); Ellipse2D.Double obs1 = new Ellipse2D.Double(50, 600, 60, 60); g2d.fill(obs1); Ellipse2D.Double obs2 = new Ellipse2D.Double(200, 400, 20, 20); g2d.fill(obs2); Ellipse2D.Double obs3 = new Ellipse2D.Double(300, 300, 20, 20); g2d.fill(obs3); Ellipse2D.Double obs4 = new Ellipse2D.Double(400, 400, 20, 20); g2d.fill(obs4); Ellipse2D.Double obs5 = new Ellipse2D.Double(200, 200, 25, 25); g2d.fill(obs5); Ellipse2D.Double obs6 = new Ellipse2D.Double(300, 100, 20, 20); g2d.fill(obs6); Ellipse2D.Double obs7 = new Ellipse2D.Double(500, 600, 40, 40); g2d.fill(obs7); Ellipse2D.Double obs8 = new Ellipse2D.Double(600, 415, 60, 60); g2d.fill(obs8); Ellipse2D.Double obs9 = new Ellipse2D.Double(500, 275, 40, 40); g2d.fill(obs9); Ellipse2D.Double obs10 = new Ellipse2D.Double(550, 150, 40, 40); g2d.fill(obs10); g2d.setColor(Color.black); if(rotationSpeed>2.5){ rotationSpeed=2.5; } if(rotationSpeed<-2.5){ rotationSpeed= -2.5; } int w = fm.stringWidth("Enter: Change modes Up/Down: Move Left/Right: Steer"); int h = fm.getAscent(); g2d.drawString("Enter: Change modes Up/Down: Move Left/Right: Steer", 400 - (w / 2), 10 + (h / 4)); if(mode) {//Crab w = fm.stringWidth("Crab Steering"); h = fm.getAscent(); g2d.drawString("Crab Steering", 100 - (w / 2), 10 + (h / 4)); wheelRotation+=rotationSpeed; if(roverRotationSpeed==0){ x-=moveY*Math.sin(Math.toRadians(wheelRotation)); y+=moveY*Math.cos(Math.toRadians(wheelRotation)); g2d.setColor(Color.GRAY); Rectangle2D.Double body = new Rectangle2D.Double(-25+x,-50+y, 50, 100); g2d.fill(body); g2d.setColor(Color.BLACK); Rectangle2D.Double frontLeftWheel = new Rectangle2D.Double(-35+x,-40+y, 10, 25); g2d.translate(-35+5+x, -40+12.5+y); //translate coordinates to center of wheel for rotation g2d.rotate(Math.toRadians(wheelRotation)); g2d.translate(35-5-x, 40-12.5-y); g2d.fill(frontLeftWheel); g2d.translate(-35+5+x, -40+12.5+y); //translate coordinates back to origin g2d.rotate(Math.toRadians(-wheelRotation)); g2d.translate(35-5-x, 40-12.5-y); g2d.setColor(Color.BLACK); Rectangle2D.Double frontRightWheel = new Rectangle2D.Double(25+x,-40+y, 10, 25); g2d.translate(25+5+x, -40+12.5+y); //translate coordinates to center of wheel for rotation g2d.rotate(Math.toRadians(wheelRotation)); g2d.translate(-25-5-x, 40-12.5-y); g2d.fill(frontRightWheel); g2d.translate(25+5+x, -40+12.5+y); //translate coordinates back to origin g2d.rotate(Math.toRadians(-wheelRotation)); g2d.translate(-25-5-x, 40-12.5-y); g2d.setColor(Color.BLACK); Rectangle2D.Double backRightWheel = new Rectangle2D.Double(25+x, 20+y, 10, 25); g2d.translate(25+5+x, 20+12.5+y); //translate coordinates to center of wheel for rotation g2d.rotate(Math.toRadians(wheelRotation)); g2d.translate(-25-5-x, -20-12.5-y); g2d.fill(backRightWheel); g2d.translate(25+5+x, 20+12.5+y); //translate coordinates back to origin g2d.rotate(Math.toRadians(-wheelRotation)); g2d.translate(-25-5-x, -20-12.5-y); g2d.setColor(Color.BLACK); Rectangle2D.Double backLeftWheel = new Rectangle2D.Double(-35+x, 20+y, 10, 25); g2d.translate(-35+5+x, 20+12.5+y); //translate coordinates to center of wheel for rotation g2d.rotate(Math.toRadians(wheelRotation)); g2d.translate(35-5-x, -20-12.5-y); g2d.fill(backLeftWheel); g2d.translate(-35+5+x, 20+12.5+y); //translate coordinates back to origin g2d.rotate(Math.toRadians(-wheelRotation)); g2d.translate(35-5-x, -20-12.5-y); } else{ - + g2d.setColor(Color.GRAY); + Rectangle2D.Double body = new Rectangle2D.Double(-25+x,-50+y, 50, 100); + g2d.fill(body); //this is where the thing rotates about its center } } //end if (Crab) else {//Ackermann w = fm.stringWidth("Ackermann Steering"); h = fm.getAscent(); g2d.drawString("Ackermann Steering", 100 - (w / 2), 10 + (h / 4)); wheelRotation+=rotationSpeed; if((wheelRotation-roverRotation)>60){ //prevent over-rotating wheels wheelRotation=roverRotation+60; } else if((wheelRotation-roverRotation)<-60){ wheelRotation=roverRotation-60; } if(wheelRotation>360) { //keep angles within -360 to 360 range wheelRotation-=360; roverRotation-=360; } else if(wheelRotation<-360) { wheelRotation+=360; roverRotation+=360; } x-=moveY*Math.sin(Math.toRadians(wheelRotation)); y+=moveY*Math.cos(Math.toRadians(wheelRotation)); g2d.setColor(Color.BLACK); Rectangle2D.Double frontLeftWheel = new Rectangle2D.Double(-35+x,-40+y, 10, 25); g2d.translate(x, y); //translate coordinates to center of wheel for rotation g2d.rotate(Math.toRadians(wheelRotation)); g2d.translate(-x, -y); g2d.fill(frontLeftWheel); /* g2d.translate(-35+5+x, -40+12.5+y); //translate coordinates back to origin g2d.rotate(Math.toRadians(-wheelRotation)); g2d.translate(35-5-x, 40-12.5-y);*/ g2d.setColor(Color.BLACK); Rectangle2D.Double frontRightWheel = new Rectangle2D.Double(25+x,-40+y, 10, 25); /*g2d.translate(25+5+x, -40+12.5+y); //translate coordinates to center of wheel for rotation g2d.rotate(Math.toRadians(wheelRotation)); g2d.translate(-25-5-x, 40-12.5-y);*/ g2d.fill(frontRightWheel); /*g2d.translate(25+5+x, -40+12.5+y); //translate coordinates back to origin g2d.rotate(Math.toRadians(-wheelRotation)); g2d.translate(-25-5-x, 40-12.5-y);*/ g2d.setColor(Color.GRAY); Rectangle2D.Double body = new Rectangle2D.Double(-25+x,-50+y, 50, 100); g2d.translate(x, y); g2d.rotate(Math.toRadians(-wheelRotation)); g2d.rotate(Math.toRadians(roverRotation)); g2d.translate(-x, -y); g2d.fill(body); g2d.setColor(Color.BLACK); Rectangle2D.Double backRightWheel = new Rectangle2D.Double(25+x, 20+y, 10, 25); //g2d.rotate(Math.toRadians(-roverRotation)); //g2d.rotate(Math.toRadians(roverRotation/2)); g2d.fill(backRightWheel); g2d.setColor(Color.BLACK); Rectangle2D.Double backLeftWheel = new Rectangle2D.Double(-35+x, 20+y, 10, 25); //g2d.rotate(Math.toRadians(-roverRotation)); //g2d.rotate(Math.toRadians(roverRotation/2)); g2d.fill(backLeftWheel); } //end else (Ackermann) } //end paintComponent /** this method changes delay of the repaint method thought timer. * @param delta determines what the change in the timer will be on click */ @Override public void actionPerformed(ActionEvent e) { repaint(); } //end actionPerformed public void up(){ moveY-=.2; double tempRot = wheelRotation; - wheelRotation += (wheelRotation-roverRotation)/5; //the 5 is arbitrary - roverRotation += wheelRotation-tempRot; //constant rotation difference b/w rover & wheels + if(!mode){ + wheelRotation += (wheelRotation-roverRotation)/5; + //the 5 is arbitrary + roverRotation += wheelRotation-tempRot; //constant rotation difference b/w rover & wheels + } if(moveY<-2.5){ moveY=-2.5; } } //end up public void down(){ moveY+=.2; double tempRot = wheelRotation; - wheelRotation -= (wheelRotation-roverRotation)/5; + if(!mode){ + wheelRotation -= (wheelRotation-roverRotation)/5; + roverRotation += wheelRotation-tempRot; + } if(moveY>2.5){ moveY=2.5; } } //end down public void left(){ rotationSpeed-=.2; } //end left public void right(){ rotationSpeed+=.2; } //end right public void rotateRoverLeft(){ roverRotationSpeed +=.2; if(roverRotationSpeed>2){ roverRotationSpeed=2; } } public void rotateRoverRight(){ roverRotationSpeed -=.2; if(roverRotationSpeed<-2){ roverRotationSpeed= -2; } } @Override public void keyPressed(KeyEvent e){ int code = e.getKeyCode(); if(code ==KeyEvent.VK_A){ rotateRoverLeft(); } if(code ==KeyEvent.VK_S){ rotateRoverRight(); } if(code==KeyEvent.VK_UP){ up(); } if(code==KeyEvent.VK_DOWN){ down(); } if(code==KeyEvent.VK_LEFT){ left(); } if(code==KeyEvent.VK_RIGHT){ right(); } if(code==KeyEvent.VK_ENTER){ if(mode == false){ //switch steering mode on key input of enter mode = true; } else{ mode = false; } } } //end keyPressed @Override public void keyTyped(KeyEvent e){} @Override public void keyReleased(KeyEvent e){ int code = e.getKeyCode(); if(code ==KeyEvent.VK_A){ roverRotationSpeed=0; } if(code ==KeyEvent.VK_S){ roverRotationSpeed=0; } if(code==KeyEvent.VK_UP){ moveY=0; } //end if if(code==KeyEvent.VK_DOWN){ moveY=0; } //end if if(code==KeyEvent.VK_LEFT){ rotationSpeed=0; //moveX=0; } //end if if(code==KeyEvent.VK_RIGHT){ rotationSpeed=0; //moveX=0; } //end if } //end keyReleased }
false
false
null
null
diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryValueFactory.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryValueFactory.java index 84df8f7469..f54ef09c86 100644 --- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryValueFactory.java +++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/memory/MemoryValueFactory.java @@ -1,102 +1,102 @@ /* * 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.jackrabbit.oak.plugins.memory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import javax.jcr.PropertyType; import org.apache.jackrabbit.oak.api.CoreValue; import org.apache.jackrabbit.oak.api.CoreValueFactory; public class MemoryValueFactory implements CoreValueFactory { public static final CoreValueFactory INSTANCE = new MemoryValueFactory(); @Override public CoreValue createValue(String value) { return new StringValue(value); } @Override public CoreValue createValue(double value) { return new DoubleValue(value); } @Override public CoreValue createValue(long value) { return new LongValue(value); } @Override public CoreValue createValue(boolean value) { if (value) { return BooleanValue.TRUE; } else { return BooleanValue.FALSE; } } @Override public CoreValue createValue(BigDecimal value) { return new DecimalValue(value); } @Override public CoreValue createValue(InputStream value) throws IOException { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] b = new byte[4096]; int n = value.read(b); while (n != -1) { buffer.write(b, 0, n); n = value.read(b); } return new BinaryValue(buffer.toByteArray()); } finally { value.close(); } } @Override public CoreValue createValue(String value, final int type) { if (type == PropertyType.BINARY) { try { return new BinaryValue(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 is not supported", e); } - } else if (type == PropertyType.DECIMAL) { - return createValue(createValue(value).getDecimal()); + } else if (type == PropertyType.BOOLEAN) { + return createValue(createValue(value).getBoolean()); } else if (type == PropertyType.DECIMAL) { return createValue(createValue(value).getDecimal()); } else if (type == PropertyType.DOUBLE) { return createValue(createValue(value).getDouble()); } else if (type == PropertyType.LONG) { return createValue(createValue(value).getLong()); } else if (type == PropertyType.STRING) { return createValue(value); } else { return new GenericValue(type, value); } } }
true
true
public CoreValue createValue(String value, final int type) { if (type == PropertyType.BINARY) { try { return new BinaryValue(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 is not supported", e); } } else if (type == PropertyType.DECIMAL) { return createValue(createValue(value).getDecimal()); } else if (type == PropertyType.DECIMAL) { return createValue(createValue(value).getDecimal()); } else if (type == PropertyType.DOUBLE) { return createValue(createValue(value).getDouble()); } else if (type == PropertyType.LONG) { return createValue(createValue(value).getLong()); } else if (type == PropertyType.STRING) { return createValue(value); } else { return new GenericValue(type, value); } }
public CoreValue createValue(String value, final int type) { if (type == PropertyType.BINARY) { try { return new BinaryValue(value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 is not supported", e); } } else if (type == PropertyType.BOOLEAN) { return createValue(createValue(value).getBoolean()); } else if (type == PropertyType.DECIMAL) { return createValue(createValue(value).getDecimal()); } else if (type == PropertyType.DOUBLE) { return createValue(createValue(value).getDouble()); } else if (type == PropertyType.LONG) { return createValue(createValue(value).getLong()); } else if (type == PropertyType.STRING) { return createValue(value); } else { return new GenericValue(type, value); } }
diff --git a/src/org/mozilla/javascript/FunctionObject.java b/src/org/mozilla/javascript/FunctionObject.java index 20c1549f..2fc45464 100644 --- a/src/org/mozilla/javascript/FunctionObject.java +++ b/src/org/mozilla/javascript/FunctionObject.java @@ -1,717 +1,725 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/NPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1997-2000 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * David C. Navas * Ted Neward * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (the "GPL"), in which case the * provisions of the GPL are applicable instead of those above. * If you wish to allow use of your version of this file only * under the terms of the GPL and not to allow others to use your * version of this file under the NPL, indicate your decision by * deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete * the provisions above, a recipient may use your version of this * file under either the NPL or the GPL. */ // API class package org.mozilla.javascript; import java.lang.reflect.Constructor; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.InvocationTargetException; import java.io.Serializable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class FunctionObject extends BaseFunction { static final long serialVersionUID = -4074285335521944312L; /** * Create a JavaScript function object from a Java method. * * <p>The <code>member</code> argument must be either a java.lang.reflect.Method * or a java.lang.reflect.Constructor and must match one of two forms.<p> * * The first form is a member with zero or more parameters * of the following types: Object, String, boolean, Scriptable, * byte, short, int, float, or double. The Long type is not supported * because the double representation of a long (which is the * EMCA-mandated storage type for Numbers) may lose precision. * If the member is a Method, the return value must be void or one * of the types allowed for parameters.<p> * * The runtime will perform appropriate conversions based * upon the type of the parameter. A parameter type of * Object specifies that no conversions are to be done. A parameter * of type String will use Context.toString to convert arguments. * Similarly, parameters of type double, boolean, and Scriptable * will cause Context.toNumber, Context.toBoolean, and * Context.toObject, respectively, to be called.<p> * * If the method is not static, the Java 'this' value will * correspond to the JavaScript 'this' value. Any attempt * to call the function with a 'this' value that is not * of the right Java type will result in an error.<p> * * The second form is the variable arguments (or "varargs") * form. If the FunctionObject will be used as a constructor, * the member must have the following parameters * <pre> * (Context cx, Object[] args, Function ctorObj, * boolean inNewExpr)</pre> * and if it is a Method, be static and return an Object result.<p> * * Otherwise, if the FunctionObject will <i>not</i> be used to define a * constructor, the member must be a static Method with parameters * (Context cx, Scriptable thisObj, Object[] args, * Function funObj) </pre> * <pre> * and an Object result.<p> * * When the function varargs form is called as part of a function call, * the <code>args</code> parameter contains the * arguments, with <code>thisObj</code> * set to the JavaScript 'this' value. <code>funObj</code> * is the function object for the invoked function.<p> * * When the constructor varargs form is called or invoked while evaluating * a <code>new</code> expression, <code>args</code> contains the * arguments, <code>ctorObj</code> refers to this FunctionObject, and * <code>inNewExpr</code> is true if and only if a <code>new</code> * expression caused the call. This supports defining a function that * has different behavior when called as a constructor than when * invoked as a normal function call. (For example, the Boolean * constructor, when called as a function, * will convert to boolean rather than creating a new object.)<p> * * @param name the name of the function * @param methodOrConstructor a java.lang.reflect.Method or a java.lang.reflect.Constructor * that defines the object * @param scope enclosing scope of function * @see org.mozilla.javascript.Scriptable */ public FunctionObject(String name, Member methodOrConstructor, Scriptable scope) { String methodName; if (methodOrConstructor instanceof Constructor) { ctor = (Constructor) methodOrConstructor; isStatic = true; // well, doesn't take a 'this' types = ctor.getParameterTypes(); methodName = ctor.getName(); } else { method = (Method) methodOrConstructor; isStatic = Modifier.isStatic(method.getModifiers()); types = method.getParameterTypes(); methodName = method.getName(); } this.functionName = name; if (types.length == 4 && (types[1].isArray() || types[2].isArray())) { // Either variable args or an error. if (types[1].isArray()) { if (!isStatic || types[0] != Context.class || types[1].getComponentType() != ScriptRuntime.ObjectClass || types[2] != ScriptRuntime.FunctionClass || types[3] != Boolean.TYPE) { throw Context.reportRuntimeError1( "msg.varargs.ctor", methodName); } parmsLength = VARARGS_CTOR; } else { if (!isStatic || types[0] != Context.class || types[1] != ScriptRuntime.ScriptableClass || types[2].getComponentType() != ScriptRuntime.ObjectClass || types[3] != ScriptRuntime.FunctionClass) { throw Context.reportRuntimeError1( "msg.varargs.fun", methodName); } parmsLength = VARARGS_METHOD; } // XXX check return type } else { parmsLength = types.length; for (int i=0; i < parmsLength; i++) { Class type = types[i]; if (type != ScriptRuntime.ObjectClass && type != ScriptRuntime.StringClass && type != ScriptRuntime.BooleanClass && !ScriptRuntime.NumberClass.isAssignableFrom(type) && !Scriptable.class.isAssignableFrom(type) && type != Boolean.TYPE && type != Byte.TYPE && type != Short.TYPE && type != Integer.TYPE && type != Float.TYPE && type != Double.TYPE) { // Note that long is not supported. throw Context.reportRuntimeError1("msg.bad.parms", methodName); } } } hasVoidReturn = method != null && method.getReturnType() == Void.TYPE; ScriptRuntime.setFunctionProtoAndParent(scope, this); - Context cx = Context.getCurrentContext(); - useDynamicScope = cx != null && - cx.hasCompileFunctionsWithDynamicScope(); + Context cx = Context.getContext(); + useDynamicScope = cx.hasCompileFunctionsWithDynamicScope(); + + if (method != null) { + Invoker master = invokerMaster; + if (master != null) { + try { + invoker = master.createInvoker(cx, method, types); + } catch (SecurityException ex) { + // Ignore invoker optimization in case of SecurityException + // which can be the case if class loader creation is + // disabled. + } + } + } } /** * Return the value defined by the method used to construct the object * (number of parameters of the method, or 1 if the method is a "varargs" * form). */ public int getArity() { return parmsLength < 0 ? 1 : parmsLength; } /** * Return the same value as {@link #getArity()}. */ public int getLength() { return getArity(); } // TODO: Make not public /** * Finds methods of a given name in a given class. * * <p>Searches <code>clazz</code> for methods with name * <code>name</code>. Maintains a cache so that multiple * lookups on the same class are cheap. * * @param clazz the class to search * @param name the name of the methods to find * @return an array of the found methods, or null if no methods * by that name were found. * @see java.lang.Class#getMethods */ public static Method[] findMethods(Class clazz, String name) { return findMethods(getMethodList(clazz), name); } static Method[] findMethods(Method[] methods, String name) { // Usually we're just looking for a single method, so optimize // for that case. ObjArray v = null; Method first = null; for (int i=0; i < methods.length; i++) { if (methods[i] == null) continue; if (methods[i].getName().equals(name)) { if (first == null) { first = methods[i]; } else { if (v == null) { v = new ObjArray(5); v.add(first); } v.add(methods[i]); } } } if (v == null) { if (first == null) return null; Method[] single = { first }; return single; } Method[] result = new Method[v.size()]; v.toArray(result); return result; } static Method[] getMethodList(Class clazz) { Method[] cached = methodsCache; // get once to avoid synchronization if (cached != null && cached[0].getDeclaringClass() == clazz) return cached; Method[] methods = null; try { // getDeclaredMethods may be rejected by the security manager // but getMethods is more expensive if (!sawSecurityException) methods = clazz.getDeclaredMethods(); } catch (SecurityException e) { // If we get an exception once, give up on getDeclaredMethods sawSecurityException = true; } if (methods == null) { methods = clazz.getMethods(); } int count = 0; for (int i=0; i < methods.length; i++) { if (sawSecurityException ? methods[i].getDeclaringClass() != clazz : !Modifier.isPublic(methods[i].getModifiers())) { methods[i] = null; } else { count++; } } Method[] result = new Method[count]; int j=0; for (int i=0; i < methods.length; i++) { if (methods[i] != null) result[j++] = methods[i]; } if (result.length > 0 && Context.isCachingEnabled) methodsCache = result; return result; } /** * Define this function as a JavaScript constructor. * <p> * Sets up the "prototype" and "constructor" properties. Also * calls setParent and setPrototype with appropriate values. * Then adds the function object as a property of the given scope, using * <code>prototype.getClassName()</code> * as the name of the property. * * @param scope the scope in which to define the constructor (typically * the global object) * @param prototype the prototype object * @see org.mozilla.javascript.Scriptable#setParentScope * @see org.mozilla.javascript.Scriptable#setPrototype * @see org.mozilla.javascript.Scriptable#getClassName */ public void addAsConstructor(Scriptable scope, Scriptable prototype) { ScriptRuntime.setFunctionProtoAndParent(scope, this); setImmunePrototypeProperty(prototype); prototype.setParentScope(this); final int attr = ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY; defineProperty(prototype, "constructor", this, attr); String name = prototype.getClassName(); defineProperty(scope, name, this, ScriptableObject.DONTENUM); setParentScope(scope); } static public Object convertArg(Context cx, Scriptable scope, Object arg, Class desired) { if (desired == ScriptRuntime.StringClass) return ScriptRuntime.toString(arg); if (desired == ScriptRuntime.IntegerClass || desired == Integer.TYPE) { return new Integer(ScriptRuntime.toInt32(arg)); } if (desired == ScriptRuntime.BooleanClass || desired == Boolean.TYPE) { return ScriptRuntime.toBoolean(arg) ? Boolean.TRUE : Boolean.FALSE; } if (desired == ScriptRuntime.DoubleClass || desired == Double.TYPE) { return new Double(ScriptRuntime.toNumber(arg)); } if (desired == ScriptRuntime.ScriptableClass) return ScriptRuntime.toObject(cx, scope, arg); if (desired == ScriptRuntime.ObjectClass) return arg; // Note that the long type is not supported; see the javadoc for // the constructor for this class throw Context.reportRuntimeError1 ("msg.cant.convert", desired.getName()); } /** * Performs conversions on argument types if needed and * invokes the underlying Java method or constructor. * <p> * Implements Function.call. * * @see org.mozilla.javascript.Function#call * @exception JavaScriptException if the underlying Java method or * constructor threw an exception */ public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) throws JavaScriptException { if (parmsLength < 0) { return callVarargs(cx, thisObj, args, false); } if (!isStatic) { // OPT: cache "clazz"? Class clazz = method != null ? method.getDeclaringClass() : ctor.getDeclaringClass(); while (!clazz.isInstance(thisObj)) { thisObj = thisObj.getPrototype(); if (thisObj == null || !useDynamicScope) { // Couldn't find an object to call this on. throw NativeGlobal.typeError1 ("msg.incompat.call", functionName, scope); } } } Object[] invokeArgs; int i; if (parmsLength == args.length) { invokeArgs = args; // avoid copy loop if no conversions needed i = (types == null) ? parmsLength : 0; } else { invokeArgs = new Object[parmsLength]; i = 0; } for (; i < parmsLength; i++) { Object arg = (i < args.length) ? args[i] : Undefined.instance; if (types != null) { arg = convertArg(cx, this, arg, types[i]); } invokeArgs[i] = arg; } try { Object result = method == null ? ctor.newInstance(invokeArgs) : doInvoke(cx, thisObj, invokeArgs); return hasVoidReturn ? Undefined.instance : result; } catch (InvocationTargetException e) { throw JavaScriptException.wrapException(cx, scope, e); } catch (IllegalAccessException e) { throw WrappedException.wrapException(e); } catch (InstantiationException e) { throw WrappedException.wrapException(e); } } /** * Performs conversions on argument types if needed and * invokes the underlying Java method or constructor * to create a new Scriptable object. * <p> * Implements Function.construct. * * @param cx the current Context for this thread * @param scope the scope to execute the function relative to. This * set to the value returned by getParentScope() except * when the function is called from a closure. * @param args arguments to the constructor * @see org.mozilla.javascript.Function#construct * @exception JavaScriptException if the underlying Java method or constructor * threw an exception */ public Scriptable construct(Context cx, Scriptable scope, Object[] args) throws JavaScriptException { if (method == null || parmsLength == VARARGS_CTOR) { Scriptable result; if (method != null) { result = (Scriptable) callVarargs(cx, null, args, true); } else { result = (Scriptable) call(cx, scope, null, args); } if (result.getPrototype() == null) result.setPrototype(getClassPrototype()); if (result.getParentScope() == null) { Scriptable parent = getParentScope(); if (result != parent) result.setParentScope(parent); } return result; } else if (method != null && !isStatic) { Scriptable result; try { result = (Scriptable) method.getDeclaringClass().newInstance(); } catch (IllegalAccessException e) { throw WrappedException.wrapException(e); } catch (InstantiationException e) { throw WrappedException.wrapException(e); } result.setPrototype(getClassPrototype()); result.setParentScope(getParentScope()); Object val = call(cx, scope, result, args); if (val != null && val != Undefined.instance && val instanceof Scriptable) { return (Scriptable) val; } return result; } return super.construct(cx, scope, args); } private final Object doInvoke(Context cx, Object thisObj, Object[] args) throws IllegalAccessException, InvocationTargetException { - Invoker master = invokerMaster; - if (master != null) { - if (invoker == null) { - invoker = master.createInvoker(cx, method, types); - } + if (invoker != null) { try { return invoker.invoke(thisObj, args); } catch (Exception e) { throw new InvocationTargetException(e); } } return method.invoke(thisObj, args); } private Object callVarargs(Context cx, Scriptable thisObj, Object[] args, boolean inNewExpr) throws JavaScriptException { try { if (parmsLength == VARARGS_METHOD) { Object[] invokeArgs = { cx, thisObj, args, this }; Object result = doInvoke(cx, null, invokeArgs); return hasVoidReturn ? Undefined.instance : result; } else { Boolean b = inNewExpr ? Boolean.TRUE : Boolean.FALSE; Object[] invokeArgs = { cx, args, this, b }; return (method == null) ? ctor.newInstance(invokeArgs) : doInvoke(cx, null, invokeArgs); } } catch (InvocationTargetException e) { Throwable target = e.getTargetException(); if (target instanceof EvaluatorException) throw (EvaluatorException) target; if (target instanceof EcmaError) throw (EcmaError) target; Scriptable scope = thisObj == null ? this : thisObj; throw JavaScriptException.wrapException(cx, scope, target); } catch (IllegalAccessException e) { throw WrappedException.wrapException(e); } catch (InstantiationException e) { throw WrappedException.wrapException(e); } } boolean isVarArgsMethod() { return parmsLength == VARARGS_METHOD; } boolean isVarArgsConstructor() { return parmsLength == VARARGS_CTOR; } static void setCachingEnabled(boolean enabled) { if (!enabled) { methodsCache = null; invokerMaster = null; } else if (invokerMaster == null) { invokerMaster = newInvokerMaster(); } } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); boolean hasConstructor = ctor != null; Member member = hasConstructor ? (Member)ctor : (Member)method; writeMember(out, member); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); Member member = readMember(in); if (member instanceof Method) { method = (Method) member; types = method.getParameterTypes(); } else { ctor = (Constructor) member; types = ctor.getParameterTypes(); } } /** * Writes a Constructor or Method object. * * Methods and Constructors are not serializable, so we must serialize * information about the class, the name, and the parameters and * recreate upon deserialization. */ static void writeMember(ObjectOutputStream out, Member member) throws IOException { if (member == null) { out.writeBoolean(false); return; } out.writeBoolean(true); if (!(member instanceof Method || member instanceof Constructor)) throw new IllegalArgumentException("not Method or Constructor"); out.writeBoolean(member instanceof Method); out.writeObject(member.getName()); out.writeObject(member.getDeclaringClass()); if (member instanceof Method) { writeParameters(out, ((Method) member).getParameterTypes()); } else { writeParameters(out, ((Constructor) member).getParameterTypes()); } } /** * Reads a Method or a Constructor from the stream. */ static Member readMember(ObjectInputStream in) throws IOException, ClassNotFoundException { if (!in.readBoolean()) return null; boolean isMethod = in.readBoolean(); String name = (String) in.readObject(); Class declaring = (Class) in.readObject(); Class[] parms = readParameters(in); try { if (isMethod) { return declaring.getMethod(name, parms); } else { return declaring.getConstructor(parms); } } catch (NoSuchMethodException e) { throw new IOException("Cannot find member: " + e); } } private static final Class[] primitives = { Boolean.TYPE, Byte.TYPE, Character.TYPE, Double.TYPE, Float.TYPE, Integer.TYPE, Long.TYPE, Short.TYPE, Void.TYPE }; /** * Writes an array of parameter types to the stream. * * Requires special handling because primitive types cannot be * found upon deserialization by the default Java implementation. */ static void writeParameters(ObjectOutputStream out, Class[] parms) throws IOException { out.writeShort(parms.length); outer: for (int i=0; i < parms.length; i++) { Class parm = parms[i]; out.writeBoolean(parm.isPrimitive()); if (!parm.isPrimitive()) { out.writeObject(parm); continue; } for (int j=0; j < primitives.length; j++) { if (parm.equals(primitives[j])) { out.writeByte(j); continue outer; } } throw new IllegalArgumentException("Primitive " + parm + " not found"); } } /** * Reads an array of parameter types from the stream. */ static Class[] readParameters(ObjectInputStream in) throws IOException, ClassNotFoundException { Class[] result = new Class[in.readShort()]; for (int i=0; i < result.length; i++) { if (!in.readBoolean()) { result[i] = (Class) in.readObject(); continue; } result[i] = primitives[in.readByte()]; } return result; } /** Get default master implementation or null if not available */ private static Invoker newInvokerMaster() { Class cl = ScriptRuntime.getClassOrNull(INVOKER_MASTER_CLASS); if (cl != null) { return (Invoker)ScriptRuntime.newInstanceOrNull(cl); } return null; } private static final String INVOKER_MASTER_CLASS = "org.mozilla.javascript.optimizer.InvokerImpl"; static Invoker invokerMaster = newInvokerMaster(); private static final short VARARGS_METHOD = -1; private static final short VARARGS_CTOR = -2; private static boolean sawSecurityException; static Method[] methodsCache; transient Method method; transient Constructor ctor; transient Invoker invoker; transient private Class[] types; private int parmsLength; private boolean hasVoidReturn; private boolean isStatic; private boolean useDynamicScope; } diff --git a/src/org/mozilla/javascript/optimizer/InvokerImpl.java b/src/org/mozilla/javascript/optimizer/InvokerImpl.java index 59829df2..83dc3c3d 100644 --- a/src/org/mozilla/javascript/optimizer/InvokerImpl.java +++ b/src/org/mozilla/javascript/optimizer/InvokerImpl.java @@ -1,314 +1,318 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/NPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1997-2000 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * Norris Boyd * David C. Navas * * Alternatively, the contents of this file may be used under the * terms of the GNU Public License (the "GPL"), in which case the * provisions of the GPL are applicable instead of those above. * If you wish to allow use of your version of this file only * under the terms of the GPL and not to allow others to use your * version of this file under the NPL, indicate your decision by * deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete * the provisions above, a recipient may use your version of this * file under either the NPL or the GPL. */ package org.mozilla.javascript.optimizer; import java.util.Hashtable; import java.lang.reflect.Method; import org.mozilla.javascript.Invoker; import org.mozilla.javascript.Context; import org.mozilla.javascript.GeneratedClassLoader; import org.mozilla.classfile.ByteCode; import org.mozilla.classfile.ClassFileWriter; /** * Avoid cost of java.lang.reflect.Method.invoke() by compiling a class to * perform the method call directly. */ public class InvokerImpl extends Invoker { public Invoker createInvoker(Context cx, Method method, Class[] types) { Invoker result; int classNum; synchronized (this) { if (invokersCache == null) { - invokersCache = new Hashtable(); ClassLoader parentLoader = cx.getClass().getClassLoader(); classLoader = cx.createClassLoader(parentLoader); + // Initialize invokersCache after creation of classloader + // since it can throw SecurityException. It prevents + // NullPointerException when accessing classLoader on + // the second Invoker invocation. + invokersCache = new Hashtable(); } else { result = (Invoker)invokersCache.get(method); if (result != null) { return result; } } classNum = ++classNumber; } String className = "inv" + classNum; ClassFileWriter cfw = new ClassFileWriter(className, "org.mozilla.javascript.Invoker", ""); cfw.setFlags((short)(ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); // Add our instantiator! cfw.startMethod("<init>", "()V", ClassFileWriter.ACC_PUBLIC); cfw.add(ByteCode.ALOAD_0); cfw.addInvoke(ByteCode.INVOKESPECIAL, "org.mozilla.javascript.Invoker", "<init>", "()V"); cfw.add(ByteCode.RETURN); cfw.stopMethod((short)1, null); // one argument -- this??? // Add the invoke() method call cfw.startMethod("invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)"+ "Ljava/lang/Object;", (short)(ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); // If we return a primitive type, then do something special! String declaringClassName = method.getDeclaringClass().getName ().replace('.', '/'); Class returnType = method.getReturnType(); String invokeSpecial = null; String invokeSpecialType = null; boolean returnsVoid = false; boolean returnsBoolean = false; if (returnType.isPrimitive()) { if (returnType == Boolean.TYPE) { returnsBoolean = true; invokeSpecialType = "(Z)V"; } else if (returnType == Void.TYPE) { returnsVoid = true; invokeSpecialType = "()V"; } else if (returnType == Integer.TYPE) { cfw.add(ByteCode.NEW, invokeSpecial = "java/lang/Integer"); cfw.add(ByteCode.DUP); invokeSpecialType = "(I)V"; } else if (returnType == Long.TYPE) { cfw.add(ByteCode.NEW, invokeSpecial = "java/lang/Long"); cfw.add(ByteCode.DUP); invokeSpecialType = "(J)V"; } else if (returnType == Short.TYPE) { cfw.add(ByteCode.NEW, invokeSpecial = "java/lang/Short"); cfw.add(ByteCode.DUP); invokeSpecialType = "(S)V"; } else if (returnType == Float.TYPE) { cfw.add(ByteCode.NEW, invokeSpecial = "java/lang/Float"); cfw.add(ByteCode.DUP); invokeSpecialType = "(F)V"; } else if (returnType == Double.TYPE) { cfw.add(ByteCode.NEW, invokeSpecial = "java/lang/Double"); cfw.add(ByteCode.DUP); invokeSpecialType = "(D)V"; } else if (returnType == Byte.TYPE) { cfw.add(ByteCode.NEW, invokeSpecial = "java/lang/Byte"); cfw.add(ByteCode.DUP); invokeSpecialType = "(B)V"; } else if (returnType == Character.TYPE) { cfw.add(ByteCode.NEW, invokeSpecial = "java/lang/Character"); cfw.add(ByteCode.DUP); invokeSpecialType = "(C)V"; } } // handle setup of call to virtual function (if calling non-static) if (!java.lang.reflect.Modifier.isStatic(method.getModifiers())) { cfw.add(ByteCode.ALOAD_1); cfw.add(ByteCode.CHECKCAST, declaringClassName); } // Handle parameters! StringBuffer params = new StringBuffer(2 + ((types!=null)?(20 * types.length):0)); params.append('('); if (types != null) { for(int i = 0; i < types.length; i++) { Class type = types[i]; cfw.add(ByteCode.ALOAD_2); if (i <= 5) { cfw.add((byte) (ByteCode.ICONST_0 + i)); } else if (i <= Byte.MAX_VALUE) { cfw.add(ByteCode.BIPUSH, i); } else if (i <= Short.MAX_VALUE) { cfw.add(ByteCode.SIPUSH, i); } else { cfw.addLoadConstant((int)i); } cfw.add(ByteCode.AALOAD); if (type.isPrimitive()) { // Convert enclosed type back to primitive. if (type == Boolean.TYPE) { cfw.add(ByteCode.CHECKCAST, "java/lang/Boolean"); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/Boolean", "booleanValue", "()Z"); params.append('Z'); } else if (type == Integer.TYPE) { cfw.add(ByteCode.CHECKCAST, "java/lang/Number"); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/Number", "intValue", "()I"); params.append('I'); } else if (type == Short.TYPE) { cfw.add(ByteCode.CHECKCAST, "java/lang/Number"); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/Number", "shortValue", "()S"); params.append('S'); } else if (type == Character.TYPE) { cfw.add(ByteCode.CHECKCAST, "java/lang/Character"); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/Character", "charValue", "()C"); params.append('C'); } else if (type == Double.TYPE) { cfw.add(ByteCode.CHECKCAST, "java/lang/Number"); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/Number", "doubleValue", "()D"); params.append('D'); } else if (type == Float.TYPE) { cfw.add(ByteCode.CHECKCAST, "java/lang/Number"); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/Number", "floatValue", "()F"); params.append('F'); } else if (type == Byte.TYPE) { cfw.add(ByteCode.CHECKCAST, "java/lang/Byte"); cfw.addInvoke(ByteCode.INVOKEVIRTUAL, "java/lang/Byte", "byteValue", "()B"); params.append('B'); } } else { String typeName = type.getName().replace('.', '/'); cfw.add(ByteCode.CHECKCAST, typeName); if (!type.isArray()) { params.append('L'); } params.append(typeName); if (!type.isArray()) { params.append(';'); } } } } params.append(')'); if (invokeSpecialType != null) { if (returnsVoid) { params.append('V'); } else { params.append(invokeSpecialType.charAt(1)); } } else if (returnType.isArray()) { params.append(returnType.getName().replace('.','/')); } else { params.append('L'); params.append(returnType.getName().replace('.','/')); params.append(';'); } // Call actual function! if (!java.lang.reflect.Modifier.isStatic(method.getModifiers())) { cfw.addInvoke(ByteCode.INVOKEVIRTUAL, declaringClassName, method.getName(), params.toString()); } else { cfw.addInvoke(ByteCode.INVOKESTATIC, declaringClassName, method.getName(), params.toString()); } // Handle return value if (returnsVoid) { cfw.add(ByteCode.ACONST_NULL); cfw.add(ByteCode.ARETURN); } else if (returnsBoolean) { // HACK //check to see if true; // '7' is the number of bytes of the ifeq<branch> plus getstatic<TRUE> plus areturn instructions cfw.add(ByteCode.IFEQ, 7); cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;"); cfw.add(ByteCode.ARETURN); cfw.add(ByteCode.GETSTATIC, "java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); cfw.add(ByteCode.ARETURN); } else if (invokeSpecial != null) { cfw.addInvoke(ByteCode.INVOKESPECIAL, invokeSpecial, "<init>", invokeSpecialType); cfw.add(ByteCode.ARETURN); } else { cfw.add(ByteCode.ARETURN); } cfw.stopMethod((short)3, null); // three arguments, including the this pointer??? byte[] bytes = cfw.toByteArray(); // Add class to our classloader. Class c = classLoader.defineClass(className, bytes); classLoader.linkClass(c); try { result = (Invoker)c.newInstance(); } catch (InstantiationException e) { throw new RuntimeException("unexpected " + e.toString()); } catch (IllegalAccessException e) { throw new RuntimeException("unexpected " + e.toString()); } if (false) { System.out.println ("Generated method delegate for: "+method.getName() +" on "+method.getDeclaringClass().getName()+" :: " +params.toString()+" :: "+types); } invokersCache.put(method, result); return result; } public Object invoke(Object that, Object [] args) { return null; } int classNumber; Hashtable invokersCache; GeneratedClassLoader classLoader; }
false
false
null
null
diff --git a/src/plugins/WebOfTrust/Identity.java b/src/plugins/WebOfTrust/Identity.java index a9366ebe..0a5b2bea 100644 --- a/src/plugins/WebOfTrust/Identity.java +++ b/src/plugins/WebOfTrust/Identity.java @@ -1,1007 +1,1010 @@ /* This code is part of WoT, a plugin for Freenet. It is distributed * under the GNU General Public License, version 2 (or at your option * any later version). See http://www.gnu.org/ for details of the GPL. */ package plugins.WebOfTrust; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import plugins.WebOfTrust.exceptions.InvalidParameterException; import freenet.keys.FreenetURI; import freenet.keys.USK; import freenet.support.Base64; import freenet.support.CurrentTimeUTC; import freenet.support.IllegalBase64Exception; import freenet.support.Logger; import freenet.support.StringValidityChecker; import freenet.support.codeshortification.IfNull; /** * An identity as handled by the WoT (a USK). * * It has a nickname and as many custom properties as needed (set by the user). * * @author xor (xor@freenetproject.org) * @author Julien Cornuwel (batosai@freenetproject.org) */ public class Identity extends Persistent implements Cloneable { public static transient final int MAX_NICKNAME_LENGTH = 30; public static transient final int MAX_CONTEXT_NAME_LENGTH = 32; public static transient final int MAX_CONTEXT_AMOUNT = 32; public static transient final int MAX_PROPERTY_NAME_LENGTH = 256; public static transient final int MAX_PROPERTY_VALUE_LENGTH = 10 * 1024; public static transient final int MAX_PROPERTY_AMOUNT = 64; /** A unique identifier used to query this Identity from the database. In fact, it is simply a String representing its routing key. */ @IndexedField protected final String mID; /** The USK requestURI used to fetch this identity from Freenet. It's edition number is the one of the data which we have currently stored * in the database (the values of this identity, trust values, etc.) if mCurrentEditionFetchState is Fetched or ParsingFailed, otherwise it * is the next edition number which should be downloaded. */ protected FreenetURI mRequestURI; public static enum FetchState { NotFetched, ParsingFailed, Fetched }; protected FetchState mCurrentEditionFetchState; /** When obtaining identities through other people's trust lists instead of identity introduction, we store the edition number they have * specified and pass it as a hint to the USKManager. */ protected long mLatestEditionHint; /** Date of the last time we successfully fetched the XML of this identity */ @IndexedField protected Date mLastFetchedDate; /** Date of this identity's last modification, for example when it has received new contexts, etc.*/ protected Date mLastChangedDate; /** The nickname of this Identity */ @IndexedField protected String mNickname; /** Whether this Identity publishes its trust list or not */ protected boolean mDoesPublishTrustList; /** A list of contexts (eg. client apps) this Identity is used for */ protected ArrayList<String> mContexts; /** A list of this Identity's custom properties */ protected HashMap<String, String> mProperties; /** * @see Identity#activateProperties() */ private transient boolean mPropertiesActivated; /* These booleans are used for preventing the construction of log-strings if logging is disabled (for saving some cpu cycles) */ private static transient volatile boolean logDEBUG = false; private static transient volatile boolean logMINOR = false; static { Logger.registerClass(Identity.class); } /** * A class for generating and validating Identity IDs. * Its purpose is NOT to be stored in the database: That would make the queries significantly slower. * We store the IDs as Strings instead for fast queries. * * Its purpose is to allow validation of IdentityIDs which we obtain from the database or from the network. * * TODO: This was added after we already had manual ID-generation / checking in the code everywhere. Use this class instead. */ public static final class IdentityID { /** * Length in characters of an ID, which is a SSK public key hash. */ public static transient final int LENGTH = 43; private final String mID; /** * Constructs an identityID from the given String. This is the inverse of IdentityID.toString(). * Checks whether the String matches the length limit. * Checks whether it is valid Base64-encoding. */ private IdentityID(String id) { if(id.length() > LENGTH) throw new IllegalArgumentException("ID is too long, length: " + id.length()); try { Base64.decode(id); } catch (IllegalBase64Exception e) { throw new RuntimeException("ID does not contain valid Base64: " + id); } mID = id; } /** * Constructs an IdentityID from the given {@link FreenetURI}. * Checks whether the URI is of the right type: Only USK or SSK is accepted. */ private IdentityID(FreenetURI uri) { if(!uri.isUSK() && !uri.isSSK()) throw new IllegalArgumentException("URI must be USK or SSK!"); try { uri = uri.deriveRequestURIFromInsertURI(); } catch(MalformedURLException e) { // It is already a request URI } /* WARNING: When changing this, also update Freetalk.WoT.WoTIdentity.getUIDFromURI()! */ mID = Base64.encode(uri.getRoutingKey()); } /** * Constructs an identityID from the given String. This is the inverse of IdentityID.toString(). * Checks whether the String matches the length limit. * Checks whether it is valid Base64-encoding. */ public static IdentityID constructAndValidateFromString(String id) { return new IdentityID(id); } /** * Generates a unique ID from a {@link FreenetURI}, which is the routing key of the author encoded with the Freenet-variant of Base64 * We use this to identify identities and perform requests on the database. * * Checks whether the URI is of the right type: Only USK or SSK is accepted. * * @param uri The requestURI or insertURI of the Identity * @return An IdentityID to uniquely identify the identity. */ public static IdentityID constructAndValidateFromURI(FreenetURI uri) { return new IdentityID(uri); } @Override public String toString() { return mID; } @Override public final boolean equals(final Object o) { if(o instanceof IdentityID) return mID.equals(((IdentityID)o).mID); if(o instanceof String) return mID.equals((String)o); return false; } /** * Gets the routing key to which this ID is equivalent. * * It is equivalent because: * An identity is uniquely identified by the USK URI which belongs to it and an USK URI is uniquely identified by its routing key. */ public byte[] getRoutingKey() throws IllegalBase64Exception { return Base64.decode(mID); } } /** * Creates an Identity. Only for being used by the WoT package and unit tests, not for user interfaces! * * @param newRequestURI A {@link FreenetURI} to fetch this Identity * @param newNickname The nickname of this identity * @param doesPublishTrustList Whether this identity publishes its trustList or not * @throws InvalidParameterException if a supplied parameter is invalid * @throws MalformedURLException if newRequestURI isn't a valid request URI */ protected Identity(WebOfTrust myWoT, FreenetURI newRequestURI, String newNickname, boolean doesPublishTrustList) throws InvalidParameterException, MalformedURLException { initializeTransient(myWoT); if (!newRequestURI.isUSK() && !newRequestURI.isSSK()) throw new IllegalArgumentException("Identity URI keytype not supported: " + newRequestURI); // We only use the passed edition number as a hint to prevent attackers from spreading bogus very-high edition numbers. mRequestURI = newRequestURI.setKeyType("USK").setDocName(WebOfTrust.WOT_NAME).setSuggestedEdition(0).setMetaString(null); //Check that mRequestURI really is a request URI USK.create(mRequestURI); mID = IdentityID.constructAndValidateFromURI(mRequestURI).toString(); try { mLatestEditionHint = Math.max(newRequestURI.getEdition(), 0); } catch (IllegalStateException e) { mLatestEditionHint = 0; } mCurrentEditionFetchState = FetchState.NotFetched; mLastFetchedDate = new Date(0); mLastChangedDate = (Date)mCreationDate.clone(); // Don't re-use objects which are stored by db4o to prevent issues when they are being deleted. if(newNickname == null) { mNickname = null; } else { setNickname(newNickname); } setPublishTrustList(doesPublishTrustList); mContexts = new ArrayList<String>(4); /* Currently we have: Introduction, Freetalk */ mProperties = new HashMap<String, String>(); if(logDEBUG) Logger.debug(this, "New identity: " + mNickname + ", URI: " + mRequestURI); } /** * Creates an Identity. Only for being used by the WoT package and unit tests, not for user interfaces! * * @param newRequestURI A String that will be converted to {@link FreenetURI} before creating the identity * @param newNickname The nickname of this identity * @param doesPublishTrustList Whether this identity publishes its trustList or not * @throws InvalidParameterException if a supplied parameter is invalid * @throws MalformedURLException if the supplied requestURI isn't a valid request URI */ public Identity(WebOfTrust myWoT, String newRequestURI, String newNickname, boolean doesPublishTrustList) throws InvalidParameterException, MalformedURLException { this(myWoT, new FreenetURI(newRequestURI), newNickname, doesPublishTrustList); } /** * Gets this Identity's ID, which is the routing key of the author encoded with the Freenet-variant of Base64. * We use this to identify identities and perform requests on the database. * * @return A unique identifier for this Identity. */ public final String getID() { checkedActivate(1); // String is a db4o primitive type so 1 is enough return mID; } /** * @return The requestURI ({@link FreenetURI}) to fetch this Identity */ public final FreenetURI getRequestURI() { checkedActivate(1); checkedActivate(mRequestURI, 2); return mRequestURI; } /** * Get the edition number of the request URI of this identity. * Safe to be called without any additional synchronization. */ public final long getEdition() { return getRequestURI().getEdition(); } public final FetchState getCurrentEditionFetchState() { checkedActivate(1); return mCurrentEditionFetchState; } /** * Sets the edition of the last fetched version of this identity. * That number is published in trustLists to limit the number of editions a newbie has to fetch before he actually gets ans Identity. * * @param newEdition A long representing the last fetched version of this identity. * @throws InvalidParameterException If the new edition is less than the current one. TODO: Evaluate whether we shouldn't be throwing a RuntimeException instead */ protected void setEdition(long newEdition) throws InvalidParameterException { checkedActivate(1); checkedActivate(mRequestURI, 2); // checkedActivate(mCurrentEditionFetchState, 1); is not needed, has no members // checkedActivate(mLatestEditionHint, 1); is not needed, long is a db4o primitive type long currentEdition = mRequestURI.getEdition(); if (newEdition < currentEdition) { throw new InvalidParameterException("The edition of an identity cannot be lowered."); } if (newEdition > currentEdition) { mRequestURI = mRequestURI.setSuggestedEdition(newEdition); mCurrentEditionFetchState = FetchState.NotFetched; if (newEdition > mLatestEditionHint) { // Do not call setNewEditionHint() to prevent confusing logging. mLatestEditionHint = newEdition; } updated(); } } public final long getLatestEditionHint() { checkedActivate(1); // long is a db4o primitive type so 1 is enough return mLatestEditionHint; } /** * Set the "edition hint" of the identity to the given new one. * The "edition hint" is an edition number of which other identities have told us that it is the latest edition. * We only consider it as a hint because they might lie about the edition number, i.e. specify one which is way too high so that the identity won't be * fetched anymore. * * @return True, if the given hint was newer than the already stored one. You have to tell the {@link IdentityFetcher} about that then. */ protected final boolean setNewEditionHint(long newLatestEditionHint) { checkedActivate(1); // long is a db4o primitive type so 1 is enough if (newLatestEditionHint > mLatestEditionHint) { mLatestEditionHint = newLatestEditionHint; if(logDEBUG) Logger.debug(this, "Received a new edition hint of " + newLatestEditionHint + " (current: " + mLatestEditionHint + ") for "+ this); return true; } return false; } /** * Decrease the current edition by one. Used by {@link #markForRefetch()}. */ private final void decreaseEdition() { checkedActivate(1); checkedActivate(mRequestURI, 2); mRequestURI = mRequestURI.setSuggestedEdition(Math.max(mRequestURI.getEdition() - 1, 0)); // TODO: I decided that we should not decrease the edition hint here. Think about that again. } /** * Marks the current edition of this identity as not fetched if it was fetched already. * If it was not fetched, decreases the edition of the identity by one. * * Called by the {@link WebOfTrust} when the {@link Score} of an identity changes from negative or 0 to > 0 to make the {@link IdentityFetcher} re-download it's * current trust list. This is necessary because we do not create the trusted identities of someone if he has a negative score. */ protected void markForRefetch() { checkedActivate(1); // checkedActivate(mCurrentEditionFetchState, 1); not needed, it has no members if (mCurrentEditionFetchState == FetchState.Fetched) { mCurrentEditionFetchState = FetchState.NotFetched; } else { decreaseEdition(); } } /** * @return The date when this identity was first seen in a trust list of someone. */ public final Date getAddedDate() { return (Date)getCreationDate().clone(); } /** * @return The date of this Identity's last modification. */ public final Date getLastFetchedDate() { checkedActivate(1); // Date is a db4o primitive type so 1 is enough return (Date)mLastFetchedDate.clone(); } /** * @return The date of this Identity's last modification. */ public final Date getLastChangeDate() { checkedActivate(1); // Date is a db4o primitive type so 1 is enough return (Date)mLastChangedDate.clone(); } /** * Has to be called when the identity was fetched and parsed successfully. Must not be called before setEdition! */ protected final void onFetched() { onFetched(CurrentTimeUTC.get()); } /** * Can be used for restoring the last-fetched date from a copy of the identity. * When an identity is fetched in normal operation, please use the version without a parameter. * * Must not be called before setEdition! */ protected final void onFetched(Date fetchDate) { checkedActivate(1); mCurrentEditionFetchState = FetchState.Fetched; // checkedDelete(mLastFetchedDate); /* Not stored because db4o considers it as a primitive */ mLastFetchedDate = (Date)fetchDate.clone(); // Clone it to prevent duplicate usage of db4o-stored objects updated(); } /** * Has to be called when the identity was fetched and parsing failed. Must not be called before setEdition! */ protected final void onParsingFailed() { checkedActivate(1); mCurrentEditionFetchState = FetchState.ParsingFailed; // checkedDelete(mLastFetchedDate); /* Not stored because db4o considers it as a primitive */ mLastFetchedDate = CurrentTimeUTC.get(); updated(); } /** * @return The Identity's nickName */ public final String getNickname() { checkedActivate(1); // String is a db4o primitive type so 1 is enough return mNickname; } /* IMPORTANT: This code is duplicated in plugins.Freetalk.WoT.WoTIdentity.validateNickname(). * Please also modify it there if you modify it here */ public static final boolean isNicknameValid(String newNickname) { return newNickname.length() > 0 && newNickname.length() <= MAX_NICKNAME_LENGTH && StringValidityChecker.containsNoIDNBlacklistCharacters(newNickname) && StringValidityChecker.containsNoInvalidCharacters(newNickname) && StringValidityChecker.containsNoLinebreaks(newNickname) && StringValidityChecker.containsNoControlCharacters(newNickname) && StringValidityChecker.containsNoInvalidFormatting(newNickname) && !newNickname.contains("@"); // Must not be allowed since we use it to generate "identity@public-key-hash" unique nicknames; } /** * Sets the nickName of this Identity. * * @param newNickname A String containing this Identity's NickName. Setting it to null means that it was not retrieved yet. * @throws InvalidParameterException If the nickname contains invalid characters, is empty or longer than MAX_NICKNAME_LENGTH characters. */ public final void setNickname(String newNickname) throws InvalidParameterException { if (newNickname == null) { throw new NullPointerException("Nickname is null"); } newNickname = newNickname.trim(); if(newNickname.length() == 0) { throw new InvalidParameterException("Blank nickname"); } if(newNickname.length() > MAX_NICKNAME_LENGTH) { throw new InvalidParameterException("Nickname is too long (" + MAX_NICKNAME_LENGTH + " chars max)"); } if(!isNicknameValid(newNickname)) { throw new InvalidParameterException("Nickname contains illegal characters."); } checkedActivate(1); // String is a db4o primitive type so 1 is enough if (mNickname != null && !mNickname.equals(newNickname)) { throw new InvalidParameterException("Changing the nickname of an identity is not allowed."); } mNickname = newNickname; updated(); } /** * Checks whether this identity publishes a trust list. * * @return Whether this Identity publishes its trustList or not. */ public final boolean doesPublishTrustList() { checkedActivate(1); // boolean is a db4o primitive type so 1 is enough return mDoesPublishTrustList; } /** * Sets if this Identity publishes its trust list or not. */ public final void setPublishTrustList(boolean doesPublishTrustList) { checkedActivate(1); // boolean is a db4o primitive type so 1 is enough if (mDoesPublishTrustList == doesPublishTrustList) { return; } mDoesPublishTrustList = doesPublishTrustList; updated(); } /** * Checks whether this identity offers the given contexts. * * @param context The context we want to know if this Identity has it or not * @return Whether this Identity has that context or not */ public final boolean hasContext(String context) { checkedActivate(1); checkedActivate(mContexts, 2); return mContexts.contains(context.trim()); } /** * Gets all this Identity's contexts. * * @return A copy of the ArrayList<String> of all contexts of this identity. */ @SuppressWarnings("unchecked") public final ArrayList<String> getContexts() { /* TODO: If this is used often - which it probably is, we might verify that no code corrupts the HashMap and return the original one * instead of a copy */ checkedActivate(1); checkedActivate(mContexts, 2); return (ArrayList<String>)mContexts.clone(); } /** * Adds a context to this identity. A context is a string, the identities contexts are a set of strings - no context will be added more than * once. * Contexts are used by client applications to identify what identities are relevant for their use. * Currently known contexts: * - WoT adds the "Introduction" context if an identity publishes catpchas to allow other to get on it's trust list * - Freetalk, the messaging system for Freenet, adds the "Freetalk" context to identities which use it. * * @param newContext Name of the context. Must be latin letters and numbers only. * @throws InvalidParameterException If the context name is empty */ public final void addContext(String newContext) throws InvalidParameterException { newContext = newContext.trim(); final int length = newContext.length(); if (length == 0) { throw new InvalidParameterException("A blank context cannot be added to an identity."); } if (length > MAX_CONTEXT_NAME_LENGTH) { throw new InvalidParameterException("Context names must not be longer than " + MAX_CONTEXT_NAME_LENGTH + " characters."); } if (!StringValidityChecker.isLatinLettersAndNumbersOnly(newContext)) { throw new InvalidParameterException("Context names must be latin letters and numbers only"); } checkedActivate(1); checkedActivate(mContexts, 2); if (!mContexts.contains(newContext)) { if (mContexts.size() >= MAX_CONTEXT_AMOUNT) { throw new InvalidParameterException("An identity may not have more than " + MAX_CONTEXT_AMOUNT + " contexts."); } mContexts.add(newContext); updated(); } } /** * Clears the list of contexts and sets it to the new list of contexts which was passed to the function. * Duplicate contexts are ignored. For invalid contexts an error is logged, all valid ones will be added. * * IMPORTANT: This always marks the identity as updated so it should not be used on OwnIdentities because it would result in * a re-insert even if nothing was changed. */ protected final void setContexts(List<String> newContexts) { checkedActivate(1); checkedActivate(mContexts, 2); mContexts.clear(); for (String context : newContexts) { try { addContext(context); } catch (InvalidParameterException e) { Logger.error(this, "setContexts(): addContext() failed.", e); } } mContexts.trimToSize(); } /** * Removes a context from this Identity, does nothing if it does not exist. * If this Identity is no longer used by a client application, the user can tell it and others won't try to fetch it anymore. * * @param context Name of the context. */ public final void removeContext(String context) throws InvalidParameterException { context = context.trim(); checkedActivate(1); checkedActivate(mContexts, 2); if (mContexts.contains(context)) { mContexts.remove(context); updated(); } } private synchronized final void activateProperties() { // We must not deactivate mProperties if it was already modified by a setter so we need this guard if(mPropertiesActivated) return; // TODO: As soon as the db4o bug with hashmaps is fixed, remove this workaround function & replace with: // checkedActivate(1); // checkedActivate(mProperties, 3); checkedActivate(1); if(mDB.isStored(mProperties)) { mDB.deactivate(mProperties); checkedActivate(mProperties, 3); } mPropertiesActivated = true; } /** * Gets the value of one of this Identity's properties. * * @param key The name of the requested custom property * @return The value of the requested custom property * @throws InvalidParameterException if this Identity doesn't have the required property */ public final String getProperty(String key) throws InvalidParameterException { key = key.trim(); activateProperties(); if (!mProperties.containsKey(key)) { throw new InvalidParameterException("The property '" + key +"' isn't set on this identity."); } return mProperties.get(key); } /** * Gets all custom properties from this Identity. * * @return A copy of the HashMap<String, String> referencing all this Identity's custom properties. */ @SuppressWarnings("unchecked") public final HashMap<String, String> getProperties() { activateProperties(); /* TODO: If this is used often, we might verify that no code corrupts the HashMap and return the original one instead of a copy */ return (HashMap<String, String>)mProperties.clone(); } /** * Sets a custom property on this Identity. Custom properties keys have to be unique. * This can be used by client applications that need to store additional informations on their Identities (crypto keys, avatar, whatever...). * The key is always trimmed before storage, the value is stored as passed. * * @param key Name of the custom property. Must be latin letters, numbers and periods only. Periods may only appear if surrounded by other characters. * @param value Value of the custom property. * @throws InvalidParameterException If the key or the value is empty. */ public final void setProperty(String key, String value) throws InvalidParameterException { // Double check in case someone removes the implicit checks... IfNull.thenThrow(key, "Key"); IfNull.thenThrow(value, "Value"); key = key.trim(); final int keyLength = key.length(); if (keyLength == 0) { throw new InvalidParameterException("Property names must not be empty."); } if (keyLength > MAX_PROPERTY_NAME_LENGTH) { throw new InvalidParameterException("Property names must not be longer than " + MAX_PROPERTY_NAME_LENGTH + " characters."); } String[] keyTokens = key.split("[.]", -1); // The 1-argument-version wont return empty tokens for (String token : keyTokens) { if (token.length() == 0) { throw new InvalidParameterException("Property names which contain periods must have at least one character before and after each period."); } if(!StringValidityChecker.isLatinLettersAndNumbersOnly(token)) throw new InvalidParameterException("Property names must contain only latin letters, numbers and periods."); } final int valueLength = value.length(); if (valueLength == 0) { throw new InvalidParameterException("Property values must not be empty."); } if (valueLength > MAX_PROPERTY_VALUE_LENGTH) { throw new InvalidParameterException("Property values must not be longer than " + MAX_PROPERTY_VALUE_LENGTH + " characters"); } activateProperties(); String oldValue = mProperties.get(key); if (oldValue == null && mProperties.size() >= MAX_PROPERTY_AMOUNT) { throw new InvalidParameterException("An identity may not have more than " + MAX_PROPERTY_AMOUNT + " properties."); } if (oldValue == null || oldValue.equals(value) == false) { mProperties.put(key, value); updated(); } } /** * Clears the list of properties and sets it to the new list of properties which was passed to the function. * For invalid properties an error is logged, all valid ones will be added. * * IMPORTANT: This always marks the identity as updated so it should not be used on OwnIdentities because it would result in * a re-insert even if nothing was changed. */ protected final void setProperties(HashMap<String, String> newProperties) { activateProperties(); checkedDelete(mProperties); mProperties = new HashMap<String, String>(newProperties.size() * 2); for (Entry<String, String> property : newProperties.entrySet()) { try { setProperty(property.getKey(), property.getValue()); } catch (InvalidParameterException e) { Logger.error(this, "setProperties(): setProperty() failed.", e); } } } /** * Removes a custom property from this Identity, does nothing if it does not exist. * * @param key Name of the custom property. */ public final void removeProperty(String key) throws InvalidParameterException { activateProperties(); key = key.trim(); if (mProperties.remove(key) != null) { updated(); } } /** * Tell that this Identity has been updated. * * Updated OwnIdentities will be reinserted by the IdentityInserter automatically. */ public final void updated() { checkedActivate(1); // Date is a db4o primitive type so 1 is enough // checkedDelete(mLastChangedDate); /* Not stored because db4o considers it as a primitive */ mLastChangedDate = CurrentTimeUTC.get(); } public final String toString() { checkedActivate(1); // String is a db4o primitive type so 1 is enough return mNickname + "(" + mID + ")"; } /** * Compares whether two identities are equal. * This checks <b>all</b> properties of the identities <b>excluding</b> the {@link Date} properties. */ public boolean equals(Object obj) { if (obj == this) { return true; } - if (!(obj instanceof Identity)) { + // - We need to return false when someone tries to compare an OwnIdentity to a non-own one. + // - We must also make sure that OwnIdentity can safely use this equals() function as foundation. + // Both cases are ensured by this check: + if (obj.getClass() != this.getClass()) { return false; } Identity other = (Identity)obj; if (!getID().equals(other.getID())) { return false; } if (!getRequestURI().equals(other.getRequestURI())) { return false; } if (getCurrentEditionFetchState() != other.getCurrentEditionFetchState()) { return false; } if (getLatestEditionHint() != other.getLatestEditionHint()) { return false; } final String nickname = getNickname(); final String otherNickname = other.getNickname(); if ((nickname == null) != (otherNickname == null)) { return false; } if(nickname != null && !nickname.equals(otherNickname)) { return false; } if (doesPublishTrustList() != other.doesPublishTrustList()) { return false; } String[] myContexts = (String[])getContexts().toArray(new String[1]); String[] otherContexts = (String[])other.getContexts().toArray(new String[1]); Arrays.sort(myContexts); Arrays.sort(otherContexts); if (!Arrays.deepEquals(myContexts, otherContexts)) { return false; } if (!getProperties().equals(other.getProperties())) { return false; } return true; } public int hashCode() { return getID().hashCode(); } /** * Clones this identity. Does <b>not</b> clone the {@link Date} attributes, they are initialized to the current time! */ public Identity clone() { try { Identity clone = new Identity(mWebOfTrust, getRequestURI(), getNickname(), doesPublishTrustList()); checkedActivate(4); // For performance only clone.mCurrentEditionFetchState = getCurrentEditionFetchState(); clone.mLastChangedDate = (Date)getLastChangeDate().clone(); clone.mLatestEditionHint = getLatestEditionHint(); // Don't use the setter since it won't lower the current edition hint. clone.setContexts(getContexts()); clone.setProperties(getProperties()); return clone; } catch (InvalidParameterException e) { throw new RuntimeException(e); } catch (MalformedURLException e) { /* This should never happen since we checked when this object was created */ Logger.error(this, "Caugth MalformedURLException in clone()", e); throw new IllegalStateException(e); } } /** * Stores this identity in the database without committing the transaction * You must synchronize on the WoT, on the identity and then on the database when using this function! */ protected void storeWithoutCommit() { try { // 4 is the maximal depth of all getter functions. You have to adjust this when introducing new member variables. checkedActivate(4); activateProperties(); // checkedStore(mID); /* Not stored because db4o considers it as a primitive and automatically stores it. */ checkedStore(mRequestURI); // checkedStore(mFirstFetchedDate); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedStore(mLastFetchedDate); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedStore(mLastChangedDate); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedStore(mNickname); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedStore(mDoesPublishTrustList); /* Not stored because db4o considers it as a primitive and automatically stores it. */ checkedStore(mProperties); checkedStore(mContexts); checkedStore(); } catch(final RuntimeException e) { checkedRollbackAndThrow(e); } } /** * Locks the WoT, locks the database and stores the identity. */ public final void storeAndCommit() { synchronized(mWebOfTrust) { synchronized(Persistent.transactionLock(mDB)) { try { storeWithoutCommit(); checkedCommit(this); } catch(RuntimeException e) { checkedRollbackAndThrow(e); } } } } /** * You have to lock the WoT and the IntroductionPuzzleStore before calling this function. * @param identity */ protected void deleteWithoutCommit() { try { // 4 is the maximal depth of all getter functions. You have to adjust this when introducing new member variables. checkedActivate(4); activateProperties(); // checkedDelete(mID); /* Not stored because db4o considers it as a primitive and automatically stores it. */ mRequestURI.removeFrom(mDB); checkedDelete(mCurrentEditionFetchState); // TODO: Is this still necessary? // checkedDelete(mLastFetchedDate); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedDelete(mLastChangedDate); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedDelete(mNickname); /* Not stored because db4o considers it as a primitive and automatically stores it. */ // checkedDelete(mDoesPublishTrustList); /* Not stored because db4o considers it as a primitive and automatically stores it. */ checkedDelete(mProperties); checkedDelete(mContexts); checkedDelete(); } catch(RuntimeException e) { checkedRollbackAndThrow(e); } } @Override public void startupDatabaseIntegrityTest() { checkedActivate(4); if(mID == null) throw new NullPointerException("mID==null"); if(mRequestURI == null) throw new NullPointerException("mRequestURI==null"); if(!mID.equals(IdentityID.constructAndValidateFromURI(mRequestURI).toString())) throw new IllegalStateException("ID does not match request URI!"); IdentityID.constructAndValidateFromString(mID); // Throws if invalid if(mCurrentEditionFetchState == null) throw new NullPointerException("mCurrentEditionFetchState==null"); if(mLatestEditionHint < 0 || mLatestEditionHint < mRequestURI.getEdition()) throw new IllegalStateException("Invalid edition hint: " + mLatestEditionHint + "; current edition: " + mRequestURI.getEdition()); if(mLastFetchedDate == null) throw new NullPointerException("mLastFetchedDate==null"); if(mLastFetchedDate.after(CurrentTimeUTC.get())) throw new IllegalStateException("mLastFetchedDate is in the future: " + mLastFetchedDate); if(mLastChangedDate == null) throw new NullPointerException("mLastChangedDate==null"); if(mLastChangedDate.before(mCreationDate)) throw new IllegalStateException("mLastChangedDate is before mCreationDate!"); if(mLastChangedDate.before(mLastFetchedDate)) throw new IllegalStateException("mLastChangedDate is before mLastFetchedDate!"); if(mLastChangedDate.after(CurrentTimeUTC.get())) throw new IllegalStateException("mLastChangedDate is in the future: " + mLastChangedDate); if(mNickname != null && !isNicknameValid(mNickname)) throw new IllegalStateException("Invalid nickname: " + mNickname); if(mContexts == null) throw new NullPointerException("mContexts==null"); if(mProperties == null) throw new NullPointerException("mProperties==null"); if(mContexts.size() > MAX_CONTEXT_AMOUNT) throw new IllegalStateException("Too many contexts: " + mContexts.size()); if(mProperties.size() > MAX_PROPERTY_AMOUNT) throw new IllegalStateException("Too many properties: " + mProperties.size()); // TODO: Verify context/property names/values } }
true
true
public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof Identity)) { return false; } Identity other = (Identity)obj; if (!getID().equals(other.getID())) { return false; } if (!getRequestURI().equals(other.getRequestURI())) { return false; } if (getCurrentEditionFetchState() != other.getCurrentEditionFetchState()) { return false; } if (getLatestEditionHint() != other.getLatestEditionHint()) { return false; } final String nickname = getNickname(); final String otherNickname = other.getNickname(); if ((nickname == null) != (otherNickname == null)) { return false; } if(nickname != null && !nickname.equals(otherNickname)) { return false; } if (doesPublishTrustList() != other.doesPublishTrustList()) { return false; } String[] myContexts = (String[])getContexts().toArray(new String[1]); String[] otherContexts = (String[])other.getContexts().toArray(new String[1]); Arrays.sort(myContexts); Arrays.sort(otherContexts); if (!Arrays.deepEquals(myContexts, otherContexts)) { return false; } if (!getProperties().equals(other.getProperties())) { return false; } return true; }
public boolean equals(Object obj) { if (obj == this) { return true; } // - We need to return false when someone tries to compare an OwnIdentity to a non-own one. // - We must also make sure that OwnIdentity can safely use this equals() function as foundation. // Both cases are ensured by this check: if (obj.getClass() != this.getClass()) { return false; } Identity other = (Identity)obj; if (!getID().equals(other.getID())) { return false; } if (!getRequestURI().equals(other.getRequestURI())) { return false; } if (getCurrentEditionFetchState() != other.getCurrentEditionFetchState()) { return false; } if (getLatestEditionHint() != other.getLatestEditionHint()) { return false; } final String nickname = getNickname(); final String otherNickname = other.getNickname(); if ((nickname == null) != (otherNickname == null)) { return false; } if(nickname != null && !nickname.equals(otherNickname)) { return false; } if (doesPublishTrustList() != other.doesPublishTrustList()) { return false; } String[] myContexts = (String[])getContexts().toArray(new String[1]); String[] otherContexts = (String[])other.getContexts().toArray(new String[1]); Arrays.sort(myContexts); Arrays.sort(otherContexts); if (!Arrays.deepEquals(myContexts, otherContexts)) { return false; } if (!getProperties().equals(other.getProperties())) { return false; } return true; }
diff --git a/plugins/org.eclipse.birt.core.ui/src/org/eclipse/birt/core/ui/utils/UIHelper.java b/plugins/org.eclipse.birt.core.ui/src/org/eclipse/birt/core/ui/utils/UIHelper.java index 92d647e9a..a7bdc499e 100644 --- a/plugins/org.eclipse.birt.core.ui/src/org/eclipse/birt/core/ui/utils/UIHelper.java +++ b/plugins/org.eclipse.birt.core.ui/src/org/eclipse/birt/core/ui/utils/UIHelper.java @@ -1,217 +1,218 @@ /*********************************************************************** * Copyright (c) 2004, 2007 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.core.ui.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.eclipse.birt.core.framework.Platform; import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase; import org.eclipse.birt.core.ui.plugin.CoreUIPlugin; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Monitor; import org.eclipse.swt.widgets.Shell; /** * This class has been created to hold methods that provide specific * functionality or services. */ public final class UIHelper { public static final String IMAGE_NAV_FORWARD = "icons/obj16/forward_nav.gif"; //$NON-NLS-1$ public static final String IMAGE_NAV_FORWARD_DIS = "icons/obj16/forward_nav_disabled.gif"; //$NON-NLS-1$ public static final String IMAGE_NAV_BACKWARD = "icons/obj16/backward_nav.gif"; //$NON-NLS-1$ public static final String IMAGE_NAV_BACKWARD_DIS = "icons/obj16/backward_nav_disabled.gif"; //$NON-NLS-1$ /** * This is a helper method created to get the location on screen of a * composite. It does not take into account multiple monitors. * * @param cmpTarget * The composite whose location on screen is required * @return The location of the composite on screen. */ public static Point getScreenLocation( Composite cmpTarget ) { Point ptScreen = new Point( 0, 0 ); try { Composite cTmp = cmpTarget; while ( !( cTmp instanceof Shell ) ) { ptScreen.x += cTmp.getLocation( ).x; ptScreen.y += cTmp.getLocation( ).y; cTmp = cTmp.getParent( ); } } catch ( Exception e ) { WizardBase.displayException( e ); } return cmpTarget.getShell( ).toDisplay( ptScreen ); } /** * This is a helper method created to center a shell on the screen. It * centers the shell on the primary monitor in a multi-monitor * configuration. * * @param shell * The shell to be centered on screen */ public static void centerOnScreen( Shell shell ) { if ( Display.getCurrent( ).getActiveShell( ) == null ) { centerOnMonitor( Display.getCurrent( ).getPrimaryMonitor( ), shell ); } else { centerOnMonitor( Display.getCurrent( ) .getActiveShell( ) .getMonitor( ), shell ); } } /** * Center shell on specified monitor. * * @param monitor specified monitor will display shell. * @param shell the shell to be centered on monitor. */ public static void centerOnMonitor( Monitor monitor, Shell shell) { Rectangle clientArea = monitor.getClientArea(); shell.setLocation( clientArea.x + ( clientArea.width / 2 ) - ( shell.getSize( ).x / 2 ), clientArea.y + ( clientArea.height / 2 ) - ( shell.getSize( ).y / 2 ) ); } /** * This method returns an URL for a resource given its plugin relative path. * It is intended to be used to abstract out the usage of the UI as a plugin * or standalone component when it comes to accessing resources. * * @param sPluginRelativePath * The path to the resource relative to the plugin location. * @return URL representing the location of the resource. */ public static URL getURL( String sPluginRelativePath ) { URL url = null; if ( isEclipseMode( ) ) { try { url = new URL( CoreUIPlugin.getDefault( ) .getBundle( ) .getEntry( "/" ), sPluginRelativePath ); //$NON-NLS-1$ } catch ( MalformedURLException e ) { WizardBase.displayException( e ); } } else { url = UIHelper.class.getResource( "/" + sPluginRelativePath ); //$NON-NLS-1$ if ( url == null ) { try { url = new URL( "file:///" + new File( sPluginRelativePath ).getAbsolutePath( ) ); //$NON-NLS-1$ } catch ( MalformedURLException e ) { WizardBase.displayException( e ); } } } return url; } private static Image createImage( String sPluginRelativePath ) { Image img = null; try { try { URL url = getURL( sPluginRelativePath ); if ( url != null ) { img = new Image( Display.getCurrent( ), url.openStream( ) ); } } catch ( MalformedURLException e1 ) { img = new Image( Display.getCurrent( ), new FileInputStream( getURL( sPluginRelativePath ).toString( ) ) ); } } catch ( FileNotFoundException e ) { WizardBase.displayException( e ); } catch ( IOException e ) { WizardBase.displayException( e ); } // If still can't load, return a dummy image. if ( img == null ) { img = new Image( Display.getCurrent( ), 1, 1 ); } return img; } /** * This is a convenience method to get an imgIcon from a URL. * * @param sPluginRelativePath * The URL for the imgIcon. * @return The imgIcon represented by the given URL. * @see #setImageCached( boolean ) */ public static Image getImage( String sPluginRelativePath ) { ImageRegistry registry = JFaceResources.getImageRegistry( ); - Image image = registry.get( sPluginRelativePath ); + String resourcePath = CoreUIPlugin.ID + "/" + sPluginRelativePath; //$NON-NLS-1$ + Image image = registry.get( resourcePath ); if ( image == null ) { image = createImage( sPluginRelativePath ); - registry.put( sPluginRelativePath, image ); + registry.put( resourcePath, image ); } return image; } /** * Returns if running in eclipse mode or stand-alone mode currently. * */ public static boolean isEclipseMode( ) { return Platform.getExtensionRegistry( ) != null; } } \ No newline at end of file
false
false
null
null
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/TestMRJobs.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/TestMRJobs.java index aa832aa1cc..437ae13571 100644 --- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/TestMRJobs.java +++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/TestMRJobs.java @@ -1,475 +1,475 @@ /** * 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.hadoop.mapreduce.v2; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.security.PrivilegedExceptionAction; import java.util.jar.JarOutputStream; import java.util.zip.ZipEntry; import junit.framework.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.FailingMapper; import org.apache.hadoop.RandomTextWriterJob; import org.apache.hadoop.RandomTextWriterJob.RandomInputFormat; import org.apache.hadoop.SleepJob; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeysPublic; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.LocalFileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.RemoteIterator; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counters; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobCounter; import org.apache.hadoop.mapreduce.JobStatus; import org.apache.hadoop.mapreduce.MRConfig; import org.apache.hadoop.mapreduce.MRJobConfig; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.TaskCompletionEvent; import org.apache.hadoop.mapreduce.TaskID; import org.apache.hadoop.mapreduce.TaskReport; import org.apache.hadoop.mapreduce.TaskType; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.Token; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class TestMRJobs { private static final Log LOG = LogFactory.getLog(TestMRJobs.class); protected static MiniMRYarnCluster mrCluster; private static Configuration conf = new Configuration(); private static FileSystem localFs; static { try { localFs = FileSystem.getLocal(conf); } catch (IOException io) { throw new RuntimeException("problem getting local fs", io); } } private static Path TEST_ROOT_DIR = new Path("target", TestMRJobs.class.getName() + "-tmpDir").makeQualified(localFs); static Path APP_JAR = new Path(TEST_ROOT_DIR, "MRAppJar.jar"); @BeforeClass public static void setup() throws IOException { if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) { LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR + " not found. Not running test."); return; } if (mrCluster == null) { mrCluster = new MiniMRYarnCluster(TestMRJobs.class.getName()); Configuration conf = new Configuration(); mrCluster.init(conf); mrCluster.start(); } // Copy MRAppJar and make it private. TODO: FIXME. This is a hack to // workaround the absent public discache. localFs.copyFromLocalFile(new Path(MiniMRYarnCluster.APPJAR), APP_JAR); localFs.setPermission(APP_JAR, new FsPermission("700")); } @AfterClass public static void tearDown() { if (mrCluster != null) { mrCluster.stop(); mrCluster = null; } } @Test public void testSleepJob() throws IOException, InterruptedException, ClassNotFoundException { LOG.info("\n\n\nStarting testSleepJob()."); if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) { LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR + " not found. Not running test."); return; } Configuration sleepConf = new Configuration(mrCluster.getConfig()); // set master address to local to test that local mode applied iff framework == classic and master_address == local sleepConf.set(MRConfig.MASTER_ADDRESS, "local"); SleepJob sleepJob = new SleepJob(); sleepJob.setConf(sleepConf); int numReduces = sleepConf.getInt("TestMRJobs.testSleepJob.reduces", 2); // or sleepConf.getConfig().getInt(MRJobConfig.NUM_REDUCES, 2); // job with 3 maps (10s) and numReduces reduces (5s), 1 "record" each: Job job = sleepJob.createJob(3, numReduces, 10000, 1, 5000, 1); job.addFileToClassPath(APP_JAR); // The AppMaster jar itself. job.setJarByClass(SleepJob.class); job.setMaxMapAttempts(1); // speed up failures job.waitForCompletion(true); boolean succeeded = job.waitForCompletion(true); Assert.assertTrue(succeeded); Assert.assertEquals(JobStatus.State.SUCCEEDED, job.getJobState()); verifySleepJobCounters(job); verifyTaskProgress(job); // TODO later: add explicit "isUber()" checks of some sort (extend // JobStatus?)--compare against MRJobConfig.JOB_UBERTASK_ENABLE value } protected void verifySleepJobCounters(Job job) throws InterruptedException, IOException { Counters counters = job.getCounters(); Assert.assertEquals(3, counters.findCounter(JobCounter.OTHER_LOCAL_MAPS) .getValue()); Assert.assertEquals(3, counters.findCounter(JobCounter.TOTAL_LAUNCHED_MAPS) .getValue()); Assert.assertEquals(2, counters.findCounter(JobCounter.TOTAL_LAUNCHED_REDUCES).getValue()); Assert .assertTrue(counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS) != null && counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS).getValue() != 0); Assert .assertTrue(counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS) != null && counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS).getValue() != 0); } protected void verifyTaskProgress(Job job) throws InterruptedException, IOException { for (TaskReport taskReport : job.getTaskReports(TaskType.MAP)) { Assert.assertTrue(0.9999f < taskReport.getProgress() && 1.0001f > taskReport.getProgress()); } for (TaskReport taskReport : job.getTaskReports(TaskType.REDUCE)) { Assert.assertTrue(0.9999f < taskReport.getProgress() && 1.0001f > taskReport.getProgress()); } } @Test public void testRandomWriter() throws IOException, InterruptedException, ClassNotFoundException { LOG.info("\n\n\nStarting testRandomWriter()."); if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) { LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR + " not found. Not running test."); return; } RandomTextWriterJob randomWriterJob = new RandomTextWriterJob(); mrCluster.getConfig().set(RandomTextWriterJob.TOTAL_BYTES, "3072"); mrCluster.getConfig().set(RandomTextWriterJob.BYTES_PER_MAP, "1024"); Job job = randomWriterJob.createJob(mrCluster.getConfig()); Path outputDir = new Path(mrCluster.getTestWorkDir().getAbsolutePath(), "random-output"); FileOutputFormat.setOutputPath(job, outputDir); job.addFileToClassPath(APP_JAR); // The AppMaster jar itself. job.setJarByClass(RandomTextWriterJob.class); job.setMaxMapAttempts(1); // speed up failures boolean succeeded = job.waitForCompletion(true); Assert.assertTrue(succeeded); Assert.assertEquals(JobStatus.State.SUCCEEDED, job.getJobState()); // Make sure there are three files in the output-dir RemoteIterator<FileStatus> iterator = FileContext.getFileContext(mrCluster.getConfig()).listStatus( outputDir); int count = 0; while (iterator.hasNext()) { FileStatus file = iterator.next(); if (!file.getPath().getName() .equals(FileOutputCommitter.SUCCEEDED_FILE_NAME)) { count++; } } Assert.assertEquals("Number of part files is wrong!", 3, count); verifyRandomWriterCounters(job); // TODO later: add explicit "isUber()" checks of some sort } protected void verifyRandomWriterCounters(Job job) throws InterruptedException, IOException { Counters counters = job.getCounters(); Assert.assertEquals(3, counters.findCounter(JobCounter.OTHER_LOCAL_MAPS) .getValue()); Assert.assertEquals(3, counters.findCounter(JobCounter.TOTAL_LAUNCHED_MAPS) .getValue()); Assert .assertTrue(counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS) != null && counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS).getValue() != 0); } @Test public void testFailingMapper() throws IOException, InterruptedException, ClassNotFoundException { LOG.info("\n\n\nStarting testFailingMapper()."); if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) { LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR + " not found. Not running test."); return; } Job job = runFailingMapperJob(); TaskID taskID = new TaskID(job.getJobID(), TaskType.MAP, 0); TaskAttemptID aId = new TaskAttemptID(taskID, 0); System.out.println("Diagnostics for " + aId + " :"); for (String diag : job.getTaskDiagnostics(aId)) { System.out.println(diag); } aId = new TaskAttemptID(taskID, 1); System.out.println("Diagnostics for " + aId + " :"); for (String diag : job.getTaskDiagnostics(aId)) { System.out.println(diag); } TaskCompletionEvent[] events = job.getTaskCompletionEvents(0, 2); Assert.assertEquals(TaskCompletionEvent.Status.FAILED, - events[0].getStatus().FAILED); - Assert.assertEquals(TaskCompletionEvent.Status.FAILED, - events[1].getStatus().FAILED); + events[0].getStatus()); + Assert.assertEquals(TaskCompletionEvent.Status.TIPFAILED, + events[1].getStatus()); Assert.assertEquals(JobStatus.State.FAILED, job.getJobState()); verifyFailingMapperCounters(job); // TODO later: add explicit "isUber()" checks of some sort } protected void verifyFailingMapperCounters(Job job) throws InterruptedException, IOException { Counters counters = job.getCounters(); Assert.assertEquals(2, counters.findCounter(JobCounter.OTHER_LOCAL_MAPS) .getValue()); Assert.assertEquals(2, counters.findCounter(JobCounter.TOTAL_LAUNCHED_MAPS) .getValue()); Assert.assertEquals(2, counters.findCounter(JobCounter.NUM_FAILED_MAPS) .getValue()); Assert .assertTrue(counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS) != null && counters.findCounter(JobCounter.SLOTS_MILLIS_MAPS).getValue() != 0); } protected Job runFailingMapperJob() throws IOException, InterruptedException, ClassNotFoundException { Configuration myConf = new Configuration(mrCluster.getConfig()); myConf.setInt(MRJobConfig.NUM_MAPS, 1); myConf.setInt("mapreduce.task.timeout", 10*1000);//reduce the timeout myConf.setInt(MRJobConfig.MAP_MAX_ATTEMPTS, 2); //reduce the number of attempts Job job = new Job(myConf); job.setJarByClass(FailingMapper.class); job.setJobName("failmapper"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setInputFormatClass(RandomInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); job.setMapperClass(FailingMapper.class); job.setNumReduceTasks(0); FileOutputFormat.setOutputPath(job, new Path(mrCluster.getTestWorkDir().getAbsolutePath(), "failmapper-output")); job.addFileToClassPath(APP_JAR); // The AppMaster jar itself. boolean succeeded = job.waitForCompletion(true); Assert.assertFalse(succeeded); return job; } //@Test public void testSleepJobWithSecurityOn() throws IOException, InterruptedException, ClassNotFoundException { LOG.info("\n\n\nStarting testSleepJobWithSecurityOn()."); if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) { return; } mrCluster.getConfig().set( CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); mrCluster.getConfig().set(YarnConfiguration.RM_KEYTAB, "/etc/krb5.keytab"); mrCluster.getConfig().set(YarnConfiguration.NM_KEYTAB, "/etc/krb5.keytab"); mrCluster.getConfig().set(YarnConfiguration.RM_PRINCIPAL, "rm/sightbusy-lx@LOCALHOST"); mrCluster.getConfig().set(YarnConfiguration.NM_PRINCIPAL, "nm/sightbusy-lx@LOCALHOST"); UserGroupInformation.setConfiguration(mrCluster.getConfig()); // Keep it in here instead of after RM/NM as multiple user logins happen in // the same JVM. UserGroupInformation user = UserGroupInformation.getCurrentUser(); LOG.info("User name is " + user.getUserName()); for (Token<? extends TokenIdentifier> str : user.getTokens()) { LOG.info("Token is " + str.encodeToUrlString()); } user.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { SleepJob sleepJob = new SleepJob(); sleepJob.setConf(mrCluster.getConfig()); Job job = sleepJob.createJob(3, 0, 10000, 1, 0, 0); // //Job with reduces // Job job = sleepJob.createJob(3, 2, 10000, 1, 10000, 1); job.addFileToClassPath(APP_JAR); // The AppMaster jar itself. job.waitForCompletion(true); Assert.assertEquals(JobStatus.State.SUCCEEDED, job.getJobState()); return null; } }); // TODO later: add explicit "isUber()" checks of some sort } public static class DistributedCacheChecker extends Mapper<LongWritable, Text, NullWritable, NullWritable> { @Override public void setup(Context context) throws IOException { Configuration conf = context.getConfiguration(); Path[] files = context.getLocalCacheFiles(); Path[] archives = context.getLocalCacheArchives(); FileSystem fs = LocalFileSystem.get(conf); // Check that 3(2+ appjar) files and 2 archives are present Assert.assertEquals(3, files.length); Assert.assertEquals(2, archives.length); // Check lengths of the files Assert.assertEquals(1, fs.getFileStatus(files[0]).getLen()); Assert.assertTrue(fs.getFileStatus(files[1]).getLen() > 1); // Check extraction of the archive Assert.assertTrue(fs.exists(new Path(archives[0], "distributed.jar.inside3"))); Assert.assertTrue(fs.exists(new Path(archives[1], "distributed.jar.inside4"))); // Check the class loaders LOG.info("Java Classpath: " + System.getProperty("java.class.path")); ClassLoader cl = Thread.currentThread().getContextClassLoader(); // Both the file and the archive should have been added to classpath, so // both should be reachable via the class loader. Assert.assertNotNull(cl.getResource("distributed.jar.inside2")); Assert.assertNotNull(cl.getResource("distributed.jar.inside3")); Assert.assertNotNull(cl.getResource("distributed.jar.inside4")); // Check that the symlink for the renaming was created in the cwd; File symlinkFile = new File("distributed.first.symlink"); Assert.assertTrue(symlinkFile.exists()); Assert.assertEquals(1, symlinkFile.length()); } } @Test public void testDistributedCache() throws Exception { if (!(new File(MiniMRYarnCluster.APPJAR)).exists()) { LOG.info("MRAppJar " + MiniMRYarnCluster.APPJAR + " not found. Not running test."); return; } // Create a temporary file of length 1. Path first = createTempFile("distributed.first", "x"); // Create two jars with a single file inside them. Path second = makeJar(new Path(TEST_ROOT_DIR, "distributed.second.jar"), 2); Path third = makeJar(new Path(TEST_ROOT_DIR, "distributed.third.jar"), 3); Path fourth = makeJar(new Path(TEST_ROOT_DIR, "distributed.fourth.jar"), 4); Job job = Job.getInstance(mrCluster.getConfig()); job.setJarByClass(DistributedCacheChecker.class); job.setMapperClass(DistributedCacheChecker.class); job.setOutputFormatClass(NullOutputFormat.class); FileInputFormat.setInputPaths(job, first); // Creates the Job Configuration job.addCacheFile( new URI(first.toUri().toString() + "#distributed.first.symlink")); job.addFileToClassPath(second); job.addFileToClassPath(APP_JAR); // The AppMaster jar itself. job.addArchiveToClassPath(third); job.addCacheArchive(fourth.toUri()); job.createSymlink(); job.setMaxMapAttempts(1); // speed up failures job.submit(); Assert.assertTrue(job.waitForCompletion(false)); } private Path createTempFile(String filename, String contents) throws IOException { Path path = new Path(TEST_ROOT_DIR, filename); FSDataOutputStream os = localFs.create(path); os.writeBytes(contents); os.close(); localFs.setPermission(path, new FsPermission("700")); return path; } private Path makeJar(Path p, int index) throws FileNotFoundException, IOException { FileOutputStream fos = new FileOutputStream(new File(p.toUri().getPath())); JarOutputStream jos = new JarOutputStream(fos); ZipEntry ze = new ZipEntry("distributed.jar.inside" + index); jos.putNextEntry(ze); jos.write(("inside the jar!" + index).getBytes()); jos.closeEntry(); jos.close(); localFs.setPermission(p, new FsPermission("700")); return p; } }
true
false
null
null
diff --git a/plugins/org.eclipse.dltk.ruby.launching/src/org/eclipse/dltk/ruby/internal/launching/GenericRubyInstall.java b/plugins/org.eclipse.dltk.ruby.launching/src/org/eclipse/dltk/ruby/internal/launching/GenericRubyInstall.java index 155e8fba..f02ecb93 100644 --- a/plugins/org.eclipse.dltk.ruby.launching/src/org/eclipse/dltk/ruby/internal/launching/GenericRubyInstall.java +++ b/plugins/org.eclipse.dltk.ruby.launching/src/org/eclipse/dltk/ruby/internal/launching/GenericRubyInstall.java @@ -1,162 +1,165 @@ package org.eclipse.dltk.ruby.internal.launching; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.dltk.core.DLTKCore; import org.eclipse.dltk.launching.AbstractInterpreterInstall; import org.eclipse.dltk.launching.IInterpreterInstallType; import org.eclipse.dltk.launching.IInterpreterRunner; import org.eclipse.dltk.ruby.launching.RubyLaunchingPlugin; import org.osgi.framework.Bundle; public class GenericRubyInstall extends AbstractInterpreterInstall { public class BuiltinsHelper { public BuiltinsHelper() { } protected void storeFile(File dest, URL url) throws IOException { InputStream input = null; OutputStream output = null; try { input = new BufferedInputStream(url.openStream()); output = new BufferedOutputStream(new FileOutputStream(dest)); // Simple copy int ch = -1; while ((ch = input.read()) != -1) { output.write(ch); } } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } } } protected File storeToMetadata(Bundle bundle, String name, String path) throws IOException { File pathFile = DLTKCore.getDefault().getStateLocation().append(name) .toFile(); storeFile(pathFile, FileLocator.resolve(bundle.getEntry(path))); return pathFile; } public String execute(String command) { Bundle bundle = RubyLaunchingPlugin.getDefault().getBundle(); File builder; try { builder = storeToMetadata(bundle, "builtin.rb", "scripts/builtin.rb"); } catch (IOException e1) { e1.printStackTrace(); return null; } String[] cmdLine = new String[] { GenericRubyInstall.this.getInstallLocation().getAbsolutePath(), builder.getAbsolutePath(), command}; BufferedReader input = null; OutputStreamWriter output = null; try { try { Process process = DebugPlugin.exec(cmdLine, null); input = new BufferedReader(new InputStreamReader(process .getInputStream())); StringBuffer sb = new StringBuffer(); String line = null; while ((line = input.readLine()) != null) { sb.append(line + "\n"); } return sb.toString(); } finally { if (output != null) { output.close(); } if (input != null) { input.close(); } } } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } public GenericRubyInstall(IInterpreterInstallType type, String id) { super(type, id); } public IInterpreterRunner getInterpreterRunner(String mode) { return new RubyInterpreterRunner(this); } private static final String prefix = "#### DLTK RUBY BUILTINS ####"; private static final int prefixLength = prefix.length(); private HashMap sources = null; private void initialize () { sources = new HashMap(); String content = new BuiltinsHelper().execute(""); int nl; int start = 0; int pos = content.indexOf(prefix, start); while (pos >= 0) { nl = content.indexOf('\n', pos); String filename = content.substring(pos + prefixLength, nl).trim(); String data = ""; pos = content.indexOf(prefix, nl + 1); if (pos != -1) data = content.substring(nl + 1, pos); else data = content.substring(nl + 1); + String prev = (String) sources.get(filename); + if (prev != null) + data = prev + data; sources.put(filename, data); } } public String getBuiltinModuleContent(String name) { if (sources == null) initialize(); return (String) sources.get(name); } public String[] getBuiltinModules() { if (sources == null) initialize(); return (String[]) sources.keySet().toArray(new String[sources.size()]); } } \ No newline at end of file
true
false
null
null
diff --git a/tests/org.eclipse.xtext.xtend2.tests/src/org/eclipse/xtext/xtend2/tests/linking/LinkingErrornessModelTest.java b/tests/org.eclipse.xtext.xtend2.tests/src/org/eclipse/xtext/xtend2/tests/linking/LinkingErrornessModelTest.java index 01a16697a..717c11c86 100644 --- a/tests/org.eclipse.xtext.xtend2.tests/src/org/eclipse/xtext/xtend2/tests/linking/LinkingErrornessModelTest.java +++ b/tests/org.eclipse.xtext.xtend2.tests/src/org/eclipse/xtext/xtend2/tests/linking/LinkingErrornessModelTest.java @@ -1,104 +1,107 @@ /******************************************************************************* * Copyright (c) 2011 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.xtext.xtend2.tests.linking; import java.io.InputStream; import java.util.List; import org.eclipse.emf.common.util.BasicDiagnostic; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource.Diagnostic; import org.eclipse.xtext.diagnostics.ExceptionDiagnostic; import org.eclipse.xtext.diagnostics.Severity; import org.eclipse.xtext.linking.lazy.LazyLinkingResource; import org.eclipse.xtext.resource.XtextResourceSet; import org.eclipse.xtext.util.CancelIndicator; import org.eclipse.xtext.util.Files; import org.eclipse.xtext.util.IAcceptor; import org.eclipse.xtext.util.StringInputStream; import org.eclipse.xtext.validation.CheckMode; import org.eclipse.xtext.validation.IDiagnosticConverter; import org.eclipse.xtext.validation.Issue; import org.eclipse.xtext.validation.ResourceValidatorImpl; import org.eclipse.xtext.xtend2.tests.AbstractXtend2TestCase; /** * A brute-force test class to ensure that parsing, linking and validation * don't throw exceptions on invalid models. * @author Sven Efftinge - Initial contribution and API * @author Sebastian Zarnekow + * + * TODO connect all model listeners (highlighting, outline) and compiler to + * verify that they do not throw any exceptions. */ public class LinkingErrornessModelTest extends AbstractXtend2TestCase { public void testParseErrornessModel_01() throws Exception { String string = readXtendFile(); for (int i = 0; i < string.length(); i++) { doParseLinkAndValidate(string.substring(0, i)); } } protected String readXtendFile() { final String name = "/"+getClass().getName().replace('.', '/')+"Data.xtend"; final InputStream resourceAsStream = getClass().getResourceAsStream(name); String string = Files.readStreamIntoString(resourceAsStream); return string; } public void testParseErrornessModel_02() throws Exception { String string = readXtendFile(); for (int i = 0; i < string.length(); i++) { doParseLinkAndValidate(string.substring(i)); } } //TODO fix me! // public void testParseErrornessModel_03() throws Exception { // String string = readXtendFile(); // for (int i = 0; i < string.length() - 1; i++) { // doParseLinkAndValidate(string.substring(0, i) + string.substring(i+1)); // } // } protected void doParseLinkAndValidate(final String string) throws Exception { try { XtextResourceSet set = get(XtextResourceSet.class); LazyLinkingResource resource = (LazyLinkingResource) set.createResource(URI.createURI("Test.xtend")); resource.load(new StringInputStream(string), null); resource.resolveLazyCrossReferences(CancelIndicator.NullImpl); ResourceValidatorImpl validator = new ResourceValidatorImpl(); assertNotSame(validator, resource.getResourceServiceProvider().getResourceValidator()); getInjector().injectMembers(validator); validator.setDiagnosticConverter(new IDiagnosticConverter() { public void convertValidatorDiagnostic(org.eclipse.emf.common.util.Diagnostic diagnostic, IAcceptor<Issue> acceptor) { if (diagnostic instanceof BasicDiagnostic) { List<?> data = diagnostic.getData(); if (!data.isEmpty() && data.get(0) instanceof Throwable) { Throwable t = (Throwable) data.get(0); // the framework catches runtime exception // and AssertionError does not take a throwable as argument throw new Error(new RuntimeException("Input was: " + string, t)); } } } public void convertResourceDiagnostic(Diagnostic diagnostic, Severity severity, IAcceptor<Issue> acceptor) { if (diagnostic instanceof ExceptionDiagnostic) { Exception e = ((ExceptionDiagnostic) diagnostic).getException(); // the framework catches runtime exception // and AssertionError does not take a throwable as argument throw new Error(new RuntimeException("Input was: " + string, e)); } } }); validator.validate(resource, CheckMode.ALL, CancelIndicator.NullImpl); } catch (Throwable e) { e.printStackTrace(); fail(e.getMessage()+" : Model was : \n\n"+string); } } }
true
false
null
null
diff --git a/src/org/openstreetmap/josm/gui/ExtendedDialog.java b/src/org/openstreetmap/josm/gui/ExtendedDialog.java index a7094d90..f36d2b12 100644 --- a/src/org/openstreetmap/josm/gui/ExtendedDialog.java +++ b/src/org/openstreetmap/josm/gui/ExtendedDialog.java @@ -1,395 +1,398 @@ package org.openstreetmap.josm.gui; import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.util.ArrayList; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.tools.GBC; import org.openstreetmap.josm.tools.ImageProvider; import org.openstreetmap.josm.tools.WindowGeometry; public class ExtendedDialog extends JDialog { private int result = 0; public static final int DialogNotShown = -99; public static final int DialogClosedOtherwise = 0; private boolean toggleable = false; private String rememberSizePref = ""; private WindowGeometry defaultWindowGeometry = null; private String togglePref = ""; private String toggleCheckboxText = tr("Do not show again"); private JCheckBox toggleCheckbox = null; private Component parent; private Component content; private final String[] bTexts; private String[] bIcons; /** * set to true if the content of the extended dialog should * be placed in a {@see JScrollPane} */ private boolean placeContentInScrollPane; // For easy access when inherited protected Object contentConstraints = GBC.eol().anchor(GBC.CENTER).fill(GBC.BOTH).insets(5,10,5,0); protected ArrayList<JButton> buttons = new ArrayList<JButton>(); /** * This method sets up the most basic options for the dialog. Add all more * advanced features with dedicated methods. * Possible features: * <ul> * <li><code>setButtonIcons</code></li> * <li><code>setContent</code></li> * <li><code>toggleEnable</code></li> * <li><code>toggleDisable</code></li> * <li><code>setToggleCheckboxText</code></li> * <li><code>setRememberWindowGeometry</code></li> * </ul> * * When done, call <code>showDialog</code> to display it. You can receive * the user's choice using <code>getValue</code>. Have a look at this function * for possible return values. * * @param parent The parent element that will be used for position and maximum size * @param title The text that will be shown in the window titlebar * @param buttonTexts String Array of the text that will appear on the buttons. The first button is the default one. */ public ExtendedDialog(Component parent, String title, String[] buttonTexts) { super(JOptionPane.getFrameForComponent(parent), title, true); this.parent = parent; bTexts = buttonTexts; } /** * Same as above but lets you define if the dialog should be modal. */ public ExtendedDialog(Component parent, String title, String[] buttonTexts, boolean modal) { super(JOptionPane.getFrameForComponent(parent), title, modal); this.parent = parent; bTexts = buttonTexts; } /** * Allows decorating the buttons with icons. Expects an String[] with paths * to images relative to JOSM/images. * @param buttonIcons */ public void setButtonIcons(String[] buttonIcons) { this.bIcons = buttonIcons; } /** * Sets the content that will be displayed in the message dialog. * * Note that depending on your other settings more UI elements may appear. * The content is played on top of the other elements though. * * @param content Any element that can be displayed in the message dialog */ public void setContent(Component content) { setContent(content, true); } /** * Sets the content that will be displayed in the message dialog. * * Note that depending on your other settings more UI elements may appear. * The content is played on top of the other elements though. * * @param content Any element that can be displayed in the message dialog * @param placeContentInScrollPane if true, places the content in a JScrollPane * */ public void setContent(Component content, boolean placeContentInScrollPane) { this.content = content; this.placeContentInScrollPane = placeContentInScrollPane; } /** * Sets the message that will be displayed. The String will be automatically * wrapped if it is too long. * * Note that depending on your other settings more UI elements may appear. * The content is played on top of the other elements though. * * @param message The text that should be shown to the user */ public void setContent(String message) { setContent(string2label(message), false); } /** * Show the dialog to the user. Call this after you have set all options * for the dialog. You can retrieve the result using <code>getValue</code> */ public void showDialog() { // Check if the user has set the dialog to not be shown again if(toggleCheckState(togglePref)) { result = ExtendedDialog.DialogNotShown; return; } setupDialog(); setVisible(true); toggleSaveState(); } /** * @return int * The selected button. The count starts with 1. * * A return value of ExtendedDialog.DialogClosedOtherwise means the dialog has been closed otherwise. * * A return value of ExtendedDialog.DialogNotShown means the * dialog has been toggled off in the past */ public int getValue() { return result; } @Deprecated protected void setupDialog(Component content, String[] buttonIcons) { this.setContent(content); this.setButtonIcons(buttonIcons); this.setupDialog(); } protected void setupDialog() { setupEscListener(); JButton button; JPanel buttonsPanel = new JPanel(new GridBagLayout()); for(int i=0; i < bTexts.length; i++) { Action action = new AbstractAction(bTexts[i]) { public void actionPerformed(ActionEvent evt) { buttonAction(evt); } }; button = new JButton(action); if(bIcons != null && bIcons[i] != null) { button.setIcon(ImageProvider.get(bIcons[i])); } if(i == 0) { rootPane.setDefaultButton(button); } buttonsPanel.add(button, GBC.std().insets(2,2,2,2)); buttons.add(button); } JPanel cp = new JPanel(new GridBagLayout()); cp.add(content, contentConstraints); if(toggleable) { toggleCheckbox = new JCheckBox(toggleCheckboxText); boolean showDialog = Main.pref.getBoolean("message."+ togglePref, true); toggleCheckbox.setSelected(!showDialog); cp.add(toggleCheckbox, GBC.eol().anchor(GBC.LINE_START).insets(5,5,5,5)); } cp.add(buttonsPanel, GBC.eol().anchor(GBC.CENTER).insets(5,5,5,5)); if (placeContentInScrollPane) { JScrollPane pane = new JScrollPane(cp); pane.setBorder(null); setContentPane(pane); } else { setContentPane(cp); } pack(); // Try to make it not larger than the parent window or at least not larger than 2/3 of the screen Dimension d = getSize(); Dimension x = findMaxDialogSize(); boolean limitedInWidth = d.width > x.width; boolean limitedInHeight = d.height > x.height; if(x.width > 0 && d.width > x.width) { d.width = x.width; } if(x.height > 0 && d.height > x.height) { d.height = x.height; } // We have a vertical scrollbar and enough space to prevent a horizontal one if(!limitedInWidth && limitedInHeight) { d.width += new JScrollBar().getPreferredSize().width; } setSize(d); setLocationRelativeTo(parent); } /** * This gets performed whenever a button is clicked or activated * @param evt the button event */ protected void buttonAction(ActionEvent evt) { String a = evt.getActionCommand(); for(int i=0; i < bTexts.length; i++) if(bTexts[i].equals(a)) { result = i+1; break; } setVisible(false); } /** * Tries to find a good value of how large the dialog should be * @return Dimension Size of the parent Component or 2/3 of screen size if not available */ protected Dimension findMaxDialogSize() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension x = new Dimension(Math.round(screenSize.width*2/3), Math.round(screenSize.height*2/3)); try { if(parent != null) { x = JOptionPane.getFrameForComponent(parent).getSize(); } } catch(NullPointerException e) { } return x; } /** * Makes the dialog listen to ESC keypressed */ private void setupEscListener() { Action actionListener = new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { // 0 means that the dialog has been closed otherwise. // We need to set it to zero again, in case the dialog has been re-used // and the result differs from its default value result = ExtendedDialog.DialogClosedOtherwise; setVisible(false); } }; - rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) + getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke("ESCAPE"), "ESCAPE"); - rootPane.getActionMap().put("ESCAPE", actionListener); + getRootPane().getActionMap().put("ESCAPE", actionListener); } + /** + * Override setVisible to be able to save the window geometry if required + */ @Override public void setVisible(boolean visible) { if (visible) { repaint(); } // Ensure all required variables are available if(rememberSizePref.length() == 0 && defaultWindowGeometry != null) { if(visible) { new WindowGeometry(rememberSizePref, defaultWindowGeometry).apply(this); } else { new WindowGeometry(this).remember(rememberSizePref); } } super.setVisible(visible); } /** * Call this if you want the dialog to remember the size set by the user. * Set the pref to <code>null</code> or to an empty string to disable again. * By default, it's disabled. * * Note: If you want to set the width of this dialog directly use the usual * setSize, setPreferredSize, setMaxSize, setMinSize * * @param pref The preference to save the dimension to * @param wg The default window geometry that should be used if no * existing preference is found (only takes effect if * <code>pref</code> is not null or empty * */ public void setRememberWindowGeometry(String pref, WindowGeometry wg) { rememberSizePref = pref == null ? "" : pref; defaultWindowGeometry = wg; } /** * Calling this will offer the user a "Do not show again" checkbox for the * dialog. Default is to not offer the choice; the dialog will be shown * every time. If the dialog is not shown due to the previous choice of the * user, the result <code>ExtendedDialog.DialogNotShown</code> is returned * @param togglePref The preference to save the checkbox state to */ public void toggleEnable(String togglePref) { this.toggleable = true; this.togglePref = togglePref; } /** * Call this if you "accidentally" called toggleEnable. This doesn't need * to be called for every dialog, as it's the default anyway. */ public void toggleDisable() { this.toggleable = false; } /** * Overwrites the default "Don't show again" text of the toggle checkbox * if you want to give more information. Only has an effect if * <code>toggleEnable</code> is set. * @param text */ public void setToggleCheckboxText(String text) { this.toggleCheckboxText = text; } /** * This function returns true if the dialog has been set to "do not show again" * @return true if dialog should not be shown again */ private boolean toggleCheckState(String togglePref) { toggleable = togglePref != null && !togglePref.equals(""); // No identifier given, so return false (= show the dialog) if(!toggleable) return false; this.togglePref = togglePref; // The pref is true, if the dialog should be shown. return !(Main.pref.getBoolean("message."+ togglePref, true)); } /** * This function checks the state of the "Do not show again" checkbox and * writes the corresponding pref */ private void toggleSaveState() { if(!toggleable || toggleCheckbox == null) return; Main.pref.put("message."+ togglePref, !toggleCheckbox.isSelected()); } /** * Convenience function that converts a given string into a JMultilineLabel * @param msg * @return JMultilineLabel */ private static JMultilineLabel string2label(String msg) { JMultilineLabel lbl = new JMultilineLabel(msg); // Make it not wider than 1/2 of the screen Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); lbl.setMaxWidth(Math.round(screenSize.width*1/2)); return lbl; } } \ No newline at end of file
false
false
null
null
diff --git a/src/cz/muni/stanse/automatonchecker/AutomatonChecker.java b/src/cz/muni/stanse/automatonchecker/AutomatonChecker.java index f9c2899..6c051bb 100644 --- a/src/cz/muni/stanse/automatonchecker/AutomatonChecker.java +++ b/src/cz/muni/stanse/automatonchecker/AutomatonChecker.java @@ -1,249 +1,249 @@ /** * @file AutomatonChecker.java * @brief Defines public final class AutomatonChecker which provides static * program verification specialized to locking problems, interrupts * enabling/disabling problems, unnecessary check optimizations and * points-to problems like null pointer dereference and memory leaks. * * Copyright (c) 2008-2009 Marek Trtik * * Licensed under GPLv2. */ package cz.muni.stanse.automatonchecker; import cz.muni.stanse.Stanse; import cz.muni.stanse.codestructures.CFGNode; import cz.muni.stanse.codestructures.LazyInternalStructures; import cz.muni.stanse.checker.CheckerErrorReceiver; import cz.muni.stanse.checker.CheckerProgressMonitor; import cz.muni.stanse.checker.CheckingResult; import cz.muni.stanse.checker.CheckingSuccess; import cz.muni.stanse.checker.CheckingFailed; import cz.muni.stanse.codestructures.CFGHandle; import cz.muni.stanse.utils.Pair; import cz.muni.stanse.utils.ClassLogger; import java.util.HashMap; import java.util.LinkedList; import java.util.Collections; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import java.io.File; /** * @brief Static checker which is able to detect locking problems, interrupts * enabling/disabling problems, unnecessary check optimizations and * points-to problems like null pointer dereference and memory leaks. * * The checker is based on execution of finite automata specified in XML file * whose states are propagated through program locations. Some automata states * are considered as erroneous, so when automaton's transition to such erroneous * state is invoked in some program location, then appropriate error message is * reported. Program locations, which are considered for automata state * propagation are found by pattern matching. These pattern are specified in * the XML file defining automata as well. * * @see cz.muni.stanse.checker.Checker */ final class AutomatonChecker extends cz.muni.stanse.checker.Checker { // public section /** * @brief Parses accepted XML automata definition and initializes internal * structures related to automata definition. * * @param XMLdefinition XML representation of AST * @throws XMLAutomatonSyntaxErrorException */ public AutomatonChecker(final File xmlFile) { super(); this.xmlFile = xmlFile; } /** * @brief Uniquelly identifies the checker by the string identifier. * * @return String which uniquelly identifies the checker. * @see cz.muni.stanse.checker.Checker#getName() */ @Override public String getName() { return AutomatonCheckerCreator.getNameForCheckerFactory() + " of " + getXmlFile().toString(); } /** * @brief Does the source code checking itself. * * Method searches through source code to find matching patterns defined * in XML automata definition file. Each such matched location in the source * code is assigned an instance of PatternLocation class. Initial location * in the program is always introduced and is initialized with initial * states of all automata to be run on the source code. * * The computation itself is simple distribution of automata states between * instances of PatternLocation class (locations are linked together with * respect to control-flow of source code). Automata states are transformed * with respect to transition rules assigned to each PatternLocation and * then distributed to linked locations. This procedure is finished, when * no location was delivered automaton state, which was not processed in * that location. * * Error detection is the final phase of the procedure. All PatternLocations * are crossed and checked for error states. Each PatternLocation has * assigned set of error transition rules which are applied to all processed * states in the location. If some error transition rule can be applied to * processed states, then it means the source code contains error. Each * error rule contains description of an error it checks for. Those error * transition rules are defined in XML automaton definition file. * * @param units List of translations units (described in internal structures * like CFGs and ASTs) * @return List of errors found in the source code. * @throws XMLAutomatonSyntaxErrorException Is thrown, when some semantic * error is detected in XML automata definition. * @see cz.muni.stanse.checker.Checker#check(java.util.List) */ @Override public CheckingResult check(final LazyInternalStructures internals, final CheckerErrorReceiver errReciver, final CheckerProgressMonitor monitor) throws XMLAutomatonSyntaxErrorException { CheckingResult result = new CheckingSuccess(); final AutomatonCheckerLogger automatonMonitor = new AutomatonCheckerLogger(monitor); automatonMonitor.note("Checker: " + getName()); automatonMonitor.pushTab(); automatonMonitor.phaseLog("parsing configuration XML file"); final XMLAutomatonDefinition XMLdefinition = parseXMLAutomatondefinition(loadXMLdefinition()); if (XMLdefinition != null) result = check(XMLdefinition,internals,errReciver,automatonMonitor); automatonMonitor.phaseBreak("checking done in "); return result; } // private section private CheckingResult check(final XMLAutomatonDefinition xmlAutomatonDefinition, final LazyInternalStructures internals, - final CheckerErrorReceiver errReciver, + final CheckerErrorReceiver errReceiver, final AutomatonCheckerLogger monitor) throws XMLAutomatonSyntaxErrorException { monitor.phaseLog("building pattern locations"); final HashMap<CFGNode,Pair<PatternLocation,PatternLocation>> nodeLocationDictionary = PatternLocationBuilder .buildPatternLocations(internals.getCFGHandles(), xmlAutomatonDefinition, internals.getArgumentPassingManager(), internals.getNavigator(), internals.getStartFunctions()); monitor.phaseLog("processing automata states"); final LinkedList<PatternLocation> progressQueue = new LinkedList<PatternLocation>(); for (final CFGHandle cfg: internals.getCFGHandles()) { final PatternLocation location = nodeLocationDictionary.get(cfg.getStartNode()).getSecond(); if (location.hasUnprocessedAutomataStates()) progressQueue.add(location); } final long startFixPointComputationTime = System.currentTimeMillis(); while (!progressQueue.isEmpty()) { final PatternLocation currentLocation = progressQueue.remove(); if (!currentLocation.hasUnprocessedAutomataStates()) continue; currentLocation.fireLocalAutomataStates(); final boolean successorsWereAffected = currentLocation.processUnprocessedAutomataStates(); if (successorsWereAffected) { progressQueue.addAll( currentLocation.getSuccessorPatternLocations()); if (currentLocation.getLocationForCallNotPassedStates() != null) progressQueue.add( currentLocation.getLocationForCallNotPassedStates()); } final long FixPointComputationTime = System.currentTimeMillis() - startFixPointComputationTime; /* 60 s is hard limit, 10 s when there are many locations */ if (FixPointComputationTime > 60000 || (FixPointComputationTime > 10000 && nodeLocationDictionary.size() > 500)) { monitor.pushTab(); final String errMsg = "*** FAILED: fix-point computation FAILED, " + "because of timeout. Location set is extremely " + "large: " + nodeLocationDictionary.size(); monitor.note(errMsg); monitor.popTab(); getLocationUnitName(currentLocation,internals); return new CheckingFailed(errMsg, getLocationUnitName(currentLocation,internals)); } } monitor.phaseLog("collecting false-positive detectors"); final java.util.List<FalsePositivesDetector> detectors = FalsePositivesDetectorFactory.getDetectors( xmlAutomatonDefinition,internals, Collections.unmodifiableMap(nodeLocationDictionary)); monitor.phaseLog("building error traces"); monitor.pushTab(); final CheckingResult result = CheckerErrorBuilder.buildErrorList(nodeLocationDictionary,internals, - detectors,errReciver,monitor, + detectors,errReceiver,monitor, getName()); monitor.popTab(); return result; } private String getNodeUnitName(final CFGNode node, final LazyInternalStructures internals) { return Stanse.getUnitManager().getUnitName( internals.getNodeToCFGdictionary().get(node)); } private String getLocationUnitName(final PatternLocation location, final LazyInternalStructures internals) { return getNodeUnitName(location.getCFGreferenceNode(),internals); } private File getXmlFile() { return xmlFile; } private Document loadXMLdefinition() { try { return (new SAXReader()).read(getXmlFile()); } catch (final DocumentException e) { ClassLogger.error(AutomatonChecker.class, "Cannot open '" + getXmlFile().getAbsolutePath() + "': " + e.getLocalizedMessage()); return null; } } private XMLAutomatonDefinition parseXMLAutomatondefinition(final Document XMLdefinition) { if (XMLdefinition == null) return null; try { return new XMLAutomatonDefinition(XMLdefinition.getRootElement()); } catch (final XMLAutomatonSyntaxErrorException e) { ClassLogger.error(AutomatonChecker.class, "Error found in XML definition file '" + getXmlFile().getAbsolutePath() + "': " + e.getLocalizedMessage()); return null; } } private final File xmlFile; } diff --git a/src/cz/muni/stanse/automatonchecker/CheckerErrorBuilder.java b/src/cz/muni/stanse/automatonchecker/CheckerErrorBuilder.java index 50d16c2..6e9432f 100644 --- a/src/cz/muni/stanse/automatonchecker/CheckerErrorBuilder.java +++ b/src/cz/muni/stanse/automatonchecker/CheckerErrorBuilder.java @@ -1,215 +1,215 @@ /** * @file CheckerErrorBuilder.java * @brief Implements final class CheckerErrorBuilder which is responsible to * compute all checker errors which can be translated from automata * states at PaternLocations. * * Copyright (c) 2008-2009 Marek Trtik * * Licensed under GPLv2. */ package cz.muni.stanse.automatonchecker; import cz.muni.stanse.Stanse; import cz.muni.stanse.codestructures.CFGNode; import cz.muni.stanse.codestructures.LazyInternalStructures; import cz.muni.stanse.codestructures.traversal.CFGTraversal; import cz.muni.stanse.checker.CheckerError; import cz.muni.stanse.checker.CheckerErrorTrace; import cz.muni.stanse.checker.CheckerErrorTraceLocation; import cz.muni.stanse.checker.CheckerErrorReceiver; import cz.muni.stanse.checker.CheckingResult; import cz.muni.stanse.checker.CheckingSuccess; import cz.muni.stanse.checker.CheckingFailed; import cz.muni.stanse.utils.Make; import cz.muni.stanse.utils.Pair; import java.util.Map; import java.util.List; import java.util.Vector; /** * @brief Provides static method buildErrorList which compute the checker-errors * from automata states at PattenLocations assigned to matching source * code locacions by use of error transition rules defined in XML * automata definition file. * * Class is not intended to be instantiated. * * @see cz.muni.stanse.checker.CheckerError * @see cz.muni.stanse.automatonchecker.AutomatonChecker */ final class CheckerErrorBuilder { // package-private section /** * @brief Computes a list of all checker-errors, which can be recognized by * error transition rules (defined in XML automata definition file) * from automata states at PattenLocations assigned to matching * source code locacions. * * @param edgeLocationDictionary Dictionary, which provides mapping from * CFGNodes (i.e. reference to souce code * locations) to related PatternLocations. * @return List of checker-errors recognized from automata states at * PatternLocations. */ static CheckingResult buildErrorList(final Map<CFGNode,Pair<PatternLocation,PatternLocation>> edgeLocationDictionary, final LazyInternalStructures internals, final java.util.List<FalsePositivesDetector> detectors, - final CheckerErrorReceiver errReciver, + final CheckerErrorReceiver errReceiver, final AutomatonCheckerLogger monitor, final String automatonName) { CheckingResult result = new CheckingSuccess(); int numErrors = 0; final long startTracingTime = System.currentTimeMillis(); for (Pair<PatternLocation,PatternLocation> locationsPair : edgeLocationDictionary.values()){ final long tracingTime = System.currentTimeMillis() - startTracingTime; if (tracingTime > 60000) return result; if (locationsPair.getFirst() != null) { final Pair<Integer,CheckingResult> locBuildResult = buildErrorsInLocation(locationsPair.getFirst(), edgeLocationDictionary,internals, - detectors,errReciver,monitor, + detectors,errReceiver,monitor, automatonName); numErrors += locBuildResult.getFirst(); if (result instanceof CheckingSuccess) result = locBuildResult.getSecond(); } } if (numErrors > 0) monitor.note("*** " + numErrors + " error(s) found"); return result; } // private section private static Pair<Integer,CheckingResult> buildErrorsInLocation(final PatternLocation location, final Map<CFGNode,Pair<PatternLocation,PatternLocation>> edgeLocationDictionary, final LazyInternalStructures internals, - final java.util.List<FalsePositivesDetector> detectors, - final CheckerErrorReceiver errReciver, + final List<FalsePositivesDetector> detectors, + final CheckerErrorReceiver errReceiver, final AutomatonCheckerLogger monitor, final String automatonName) { final CallSiteDetector callDetector = new CallSiteDetector(internals.getNavigator(), edgeLocationDictionary); final AutomatonStateTransferManager transferor = new AutomatonStateTransferManager( internals.getArgumentPassingManager(),callDetector); final CallSiteCFGNavigator callNavigator = new CallSiteCFGNavigator(internals.getNavigator(),callDetector); if (location.getProcessedAutomataStates().size() > 100 || location.getDeliveredAutomataStates().size() > 100) location.reduceStateSets(); CheckingResult result = new CheckingSuccess(); int numErrors = 0; final long startLocationTracingTime = System.currentTimeMillis(); for (final ErrorRule rule : location.getErrorRules()) for (final java.util.Stack<CFGNode> cfgContext : AutomatonStateCFGcontextAlgo.getContexts( location.getProcessedAutomataStates())){ final long locationTracingTime = System.currentTimeMillis() - startLocationTracingTime; if (locationTracingTime > 10000) return Pair.make(numErrors,result); if (rule.checkForError(AutomatonStateCFGcontextAlgo. filterStatesByContext( location.getProcessedAutomataStates(), cfgContext))) { final ErrorTracesListCreator creator = new ErrorTracesListCreator(rule,transferor, edgeLocationDictionary, location.getCFGreferenceNode(), internals,detectors,monitor); final List<CheckerErrorTrace> traces = CFGTraversal.traverseCFGPathsBackwardInterprocedural( callNavigator,location.getCFGreferenceNode(), creator,cfgContext).getErrorTracesList(); if (result instanceof CheckingSuccess && creator.getFailMessage() != null) result = new CheckingFailed(creator.getFailMessage(), getLocationUnitName(location,internals)); // Next condition eliminates cyclic dependances of two - // error locations (diferent). These locations have same - // error rule and theirs methods checkForError() returns + // (different) error locations. These locations have same + // error rule and their checkForError() methods return // true (so they are both error locations). But their - // cyclic dependancy disables to find starting nodes of - // theirs error traces -> both error traces returned will + // cyclic dependency disallows to find starting nodes of + // their error traces -> both error traces returned will // be empty. if (traces.isEmpty()) continue; int min_size = Integer.MAX_VALUE; CheckerErrorTrace min_trace = null; for (final CheckerErrorTrace trace : traces) { if (trace.getLocations().size() >= min_size) continue; min_size = trace.getLocations().size(); min_trace = trace; } final String shortDesc = rule.getErrorDescription(); final String fullDesc = "{" + automatonName + "} in function '" + internals.getNodeToCFGdictionary() .get(location.getCFGreferenceNode()) .getFunctionName() + "' " + shortDesc + " [traces: " + traces.size() + "]"; - errReciver.receive( + errReceiver.receive( new CheckerError(shortDesc,fullDesc, rule.getErrorLevel() + creator.getTotalImportance(), automatonName, Make.linkedList(min_trace))); ++numErrors; monitor.note("*** error found: " + shortDesc); } } return Pair.make(numErrors,result); } @Deprecated private static CheckerErrorTrace builOneLocationTrace(final PatternLocation location, final ErrorRule rule, final LazyInternalStructures internals) { final Vector<CheckerErrorTraceLocation> locs = new Vector<CheckerErrorTraceLocation>(); final String unitName = getLocationUnitName(location,internals); final int line = location.getCFGreferenceNode().getLine(); final int column = location.getCFGreferenceNode().getColumn(); final String desc =rule.getErrorDescription() + rule.getAutomatonID().getVarsAssignment().toString(); locs.add(new CheckerErrorTraceLocation(unitName,line,column,desc)); return new CheckerErrorTrace(locs,desc); } private static String getNodeUnitName(final CFGNode node, final LazyInternalStructures internals) { return Stanse.getUnitManager().getUnitName( internals.getNodeToCFGdictionary().get(node)); } private static String getLocationUnitName(final PatternLocation location, final LazyInternalStructures internals) { return getNodeUnitName(location.getCFGreferenceNode(),internals); } private CheckerErrorBuilder() { } }
false
false
null
null
diff --git a/src/main/java/com/google/gson/JsonParseException.java b/src/main/java/com/google/gson/JsonParseException.java index adbc26c6..b00df193 100644 --- a/src/main/java/com/google/gson/JsonParseException.java +++ b/src/main/java/com/google/gson/JsonParseException.java @@ -1,63 +1,63 @@ /* * Copyright (C) 2008 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.google.gson; /** * This exception is raised if there is a serious issue that occurs during parsing of a Json * string. One of the main usages for this class is for the Gson infrastructure. If the incoming * Json is bad/malicious, an instance of this exception is raised. * * <p>This exception is a {@link RuntimeException} because it is exposed to the client. Using a * {@link RuntimeException} avoids bad coding practices on the client side where they catch the * exception and do nothing. It is often the case that you want to blow up if there is a parsing - * error (i.e. often client do not know how to recover from a {@link JsonParseException}.</p> + * error (i.e. often clients do not know how to recover from a {@link JsonParseException}.</p> * * @author Joel Leitch */ public final class JsonParseException extends RuntimeException { static final long serialVersionUID = -4086729973971783390L; /** * Creates exception with the specified message. If you are wrapping another exception, consider * using {@link #JsonParseException(String, Throwable)} instead. * * @param msg error message describing a possible cause of this exception. */ public JsonParseException(String msg) { super(msg); } /** * Creates exception with the specified message and cause. * * @param msg error message describing what happened. * @param cause root exception that caused this exception to be thrown. */ public JsonParseException(String msg, Throwable cause) { super(msg, cause); } /** * Creates exception with the specified cause. Consider using * {@link #JsonParseException(String, Throwable)} instead if you can describe what happened. * * @param cause root exception that caused this exception to be thrown. */ public JsonParseException(Throwable cause) { super(cause); } }
true
false
null
null
diff --git a/src/test/java/javax/jmdns/test/DNSStatefulObjectTest.java b/src/test/java/javax/jmdns/test/DNSStatefulObjectTest.java index 02fcaff..599b00c 100644 --- a/src/test/java/javax/jmdns/test/DNSStatefulObjectTest.java +++ b/src/test/java/javax/jmdns/test/DNSStatefulObjectTest.java @@ -1,82 +1,82 @@ /** * */ package javax.jmdns.test; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import javax.jmdns.impl.DNSStatefulObject.DNSStatefulObjectSemaphore; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * */ public class DNSStatefulObjectTest { public static final class WaitingThread extends Thread { private final DNSStatefulObjectSemaphore _semaphore; private final long _timeout; private boolean _hasFinished; public WaitingThread(DNSStatefulObjectSemaphore semaphore, long timeout) { super("Waiting thread"); _semaphore = semaphore; _timeout = timeout; _hasFinished = false; } @Override public void run() { _semaphore.waitForEvent(_timeout); _hasFinished = true; } /** * @return the hasFinished */ public boolean hasFinished() { return _hasFinished; } } DNSStatefulObjectSemaphore _semaphore; @Before public void setup() { _semaphore = new DNSStatefulObjectSemaphore("test"); } @After public void teardown() { _semaphore = null; } @Test public void testWaitAndSignal() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, 0); thread.start(); - Thread.sleep(1); + Thread.sleep(2); assertFalse("The thread should be waiting.", thread.hasFinished()); _semaphore.signalEvent(); - Thread.sleep(1); + Thread.sleep(2); assertTrue("The thread should have finished.", thread.hasFinished()); } @Test public void testWaitAndTimeout() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, 100); thread.start(); Thread.sleep(1); assertFalse("The thread should be waiting.", thread.hasFinished()); Thread.sleep(150); assertTrue("The thread should have finished.", thread.hasFinished()); } }
false
true
public void testWaitAndSignal() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, 0); thread.start(); Thread.sleep(1); assertFalse("The thread should be waiting.", thread.hasFinished()); _semaphore.signalEvent(); Thread.sleep(1); assertTrue("The thread should have finished.", thread.hasFinished()); }
public void testWaitAndSignal() throws InterruptedException { WaitingThread thread = new WaitingThread(_semaphore, 0); thread.start(); Thread.sleep(2); assertFalse("The thread should be waiting.", thread.hasFinished()); _semaphore.signalEvent(); Thread.sleep(2); assertTrue("The thread should have finished.", thread.hasFinished()); }
diff --git a/src/main/java/com/intelix/digihdmi/app/views/PresetLoadListView.java b/src/main/java/com/intelix/digihdmi/app/views/PresetLoadListView.java index b21fef2..a83ffdc 100644 --- a/src/main/java/com/intelix/digihdmi/app/views/PresetLoadListView.java +++ b/src/main/java/com/intelix/digihdmi/app/views/PresetLoadListView.java @@ -1,20 +1,20 @@ package com.intelix.digihdmi.app.views; import com.intelix.digihdmi.util.IconImageButton; import javax.swing.JButton; import org.jdesktop.application.Application; public class PresetLoadListView extends ButtonListView { @Override protected void initializeHomePanel() { super.initializeHomePanel(); IconImageButton matrixView = new IconImageButton("MatrixIconBtn"); matrixView.setAction( - Application.getInstance().getContext().getActionMap().get("showMatrixView") + Application.getInstance().getContext().getActionMap().get("showAndLoadMatrixView") ); this.homePanel.add(matrixView); } }
true
true
protected void initializeHomePanel() { super.initializeHomePanel(); IconImageButton matrixView = new IconImageButton("MatrixIconBtn"); matrixView.setAction( Application.getInstance().getContext().getActionMap().get("showMatrixView") ); this.homePanel.add(matrixView); }
protected void initializeHomePanel() { super.initializeHomePanel(); IconImageButton matrixView = new IconImageButton("MatrixIconBtn"); matrixView.setAction( Application.getInstance().getContext().getActionMap().get("showAndLoadMatrixView") ); this.homePanel.add(matrixView); }
diff --git a/src/com/ukfast/GoogleMaps/MapsActivity.java b/src/com/ukfast/GoogleMaps/MapsActivity.java index b714509..c989f39 100644 --- a/src/com/ukfast/GoogleMaps/MapsActivity.java +++ b/src/com/ukfast/GoogleMaps/MapsActivity.java @@ -1,123 +1,123 @@ package com.ukfast.GoogleMaps; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; 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; public class MapsActivity extends MapActivity { private MapView mapView; private MapController mapController; private static final int SATELLITE_ID = 1; private static final int STREET_ID = 2; private static final int FIND_ME_ID = 3; private boolean isSatelliteView = false; private boolean isStreetView = false; private MyLocationOverlay myLocationOverlay; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapView = (MapView) findViewById(R.id.mapView); mapView.setBuiltInZoomControls(true); mapController = mapView.getController(); myLocationOverlay = new MyLocationOverlay(this, mapView); myLocationOverlay.enableMyLocation(); myLocationOverlay.enableCompass(); mapView.getOverlays().add(myLocationOverlay); } @Override protected boolean isRouteDisplayed() { return false; } @Override protected void onPause() { super.onPause(); myLocationOverlay.disableMyLocation(); myLocationOverlay.disableCompass(); } @Override protected void onResume() { super.onResume(); myLocationOverlay.enableMyLocation(); myLocationOverlay.enableCompass(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, SATELLITE_ID, 0, R.string.menu_satellite); menu.add(0, STREET_ID, 0, R.string.menu_street); menu.add(0, FIND_ME_ID, 0, R.string.find_me); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch(item.getItemId()) { case SATELLITE_ID: if(isSatelliteView == true) { isSatelliteView = false; } else { isSatelliteView = true; } mapView.setSatellite(isSatelliteView); return true; case STREET_ID: if(isStreetView == true) { isStreetView = false; } else { isStreetView = true; } mapView.setStreetView(isStreetView); return true; case FIND_ME_ID: findMe(); return true; } return super.onMenuItemSelected(featureId, item); } private void findMe() { GeoPoint point = myLocationOverlay.getMyLocation(); updateWithNewLocation(point); } public void updateWithNewLocation(GeoPoint point) { if (point != null) { mapController.animateTo(point); } else { AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setMessage("Unable to find your location, check that you have enabled Cell Tower or GPS Locationing.") + builder.setMessage(getResources().getString(R.string.location_error)) .setCancelable(false) .setNeutralButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } } } \ No newline at end of file
true
false
null
null
diff --git a/src/org/j3d/loaders/collada/ColladaParser.java b/src/org/j3d/loaders/collada/ColladaParser.java index 2ac18947..27d45cac 100644 --- a/src/org/j3d/loaders/collada/ColladaParser.java +++ b/src/org/j3d/loaders/collada/ColladaParser.java @@ -1,157 +1,157 @@ package org.j3d.loaders.collada; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Vector; import java.util.logging.Level; import javax.media.j3d.GeometryArray; import javax.media.j3d.TriangleArray; import javax.vecmath.Point3d; import javax.vecmath.Tuple3d; import javax.vecmath.Vector3f; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import replicatorg.app.Base; public class ColladaParser { Map<String, Vector<Tuple3d>> tupleMap = new HashMap<String, Vector<Tuple3d>>(); Map<String, TriangleArray> geometryMap = new HashMap<String, TriangleArray>(); Document doc; TriangleArray totalGeometry = null; public ColladaParser() { } private void loadFloatArray(Node n, Vector<Tuple3d> v) { int count = Integer.parseInt(n.getAttributes().getNamedItem("count").getNodeValue()); v.ensureCapacity(v.size() + (count/3)); String[] values = n.getTextContent().trim().split("\\s+"); for (int i = 0; i < values.length; i+= 3) { Tuple3d t = new Point3d( Double.parseDouble(values[i]), Double.parseDouble(values[i+1]), Double.parseDouble(values[i+2])); v.add(t); } } private void loadTuples(Element parent) { NodeList sources = parent.getElementsByTagName("source"); for (int idx = 0; idx < sources.getLength(); idx++) { Node n = sources.item(idx); Element e = (Element)n; String id = n.getAttributes().getNamedItem("id").getNodeValue(); NodeList arrays = e.getElementsByTagName("float_array"); Vector<Tuple3d> v = new Vector<Tuple3d>(); for (int i = 0; i < arrays.getLength(); i++) { loadFloatArray(arrays.item(i),v); } tupleMap.put(id,v); } } Map<String,Vector<Tuple3d>> loadVertices(Element e) { NodeList inputList = e.getElementsByTagName("input"); Map<String,Vector<Tuple3d>> verticesMap = new HashMap<String,Vector<Tuple3d>>(); for (int j = 0; j < inputList.getLength(); j++) { Element inputElement = (Element)inputList.item(j); String sourceRef = inputElement.getAttribute("source"); String sourceId = sourceRef.substring(1); Vector<Tuple3d> points = tupleMap.get(sourceId); String semantic = inputElement.getAttribute("semantic"); verticesMap.put(semantic.toLowerCase(), points); } return verticesMap; } private void loadGeometries() { NodeList geometries = doc.getElementsByTagName("geometry"); for (int idx = 0; idx < geometries.getLength(); idx++) { Element e = (Element)geometries.item(idx); loadTuples(e); String id = e.getAttribute("id"); - NodeList verticesList = doc.getElementsByTagName("vertices"); + NodeList verticesList = e.getElementsByTagName("vertices"); Map<String,Vector<Tuple3d>> verticesMap = loadVertices((Element)verticesList.item(0)); Vector<Tuple3d> positions = verticesMap.get("position"); Vector<Tuple3d> normals = verticesMap.get("normal"); - NodeList trianglesList = doc.getElementsByTagName("triangles"); + NodeList trianglesList = e.getElementsByTagName("triangles"); Element trianglesElement = (Element)trianglesList.item(0); int vertexCount = Integer.parseInt(trianglesElement.getAttribute("count")) * 3; TriangleArray tris = new TriangleArray(vertexCount, GeometryArray.NORMALS | GeometryArray.COORDINATES); String[] vertexIndices = trianglesElement.getTextContent().trim().split("\\s+"); for (int i = 0; i < vertexCount; i++) { int j = Integer.parseInt(vertexIndices[i]); tris.setCoordinate(i,new Point3d(positions.elementAt(j))); tris.setNormal(i,new Vector3f(normals.elementAt(j))); } geometryMap.put(id,tris); } } private void addGeometry(TriangleArray g) { if (totalGeometry == null) { totalGeometry = g; } else if (g != null) { // Merge geometries int vc = g.getVertexCount() + totalGeometry.getVertexCount(); TriangleArray newG = new TriangleArray(vc, GeometryArray.NORMALS | GeometryArray.COORDINATES); Point3d v = new Point3d(); Vector3f n = new Vector3f(); int gvc = g.getVertexCount(); for (int i = 0; i < gvc; i++) { g.getCoordinate(i, v); g.getNormal(i, n); newG.setCoordinate(i,v); newG.setNormal(i, n); } for (int i = 0; i < totalGeometry.getVertexCount(); i++) { totalGeometry.getCoordinate(i, v); totalGeometry.getNormal(i, n); newG.setCoordinate(gvc+i,v); newG.setNormal(gvc+i, n); } totalGeometry = newG; } } public TriangleArray getTotalGeometry() { return totalGeometry; } public boolean parse(InputSource is) { totalGeometry = null; DocumentBuilder db; try { db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); doc = db.parse(is); loadGeometries(); NodeList instances = doc.getElementsByTagName("instance_geometry"); for (int idx = 0; idx < instances.getLength(); idx++) { Node n = instances.item(idx); String u = n.getAttributes().getNamedItem("url").getNodeValue(); TriangleArray geometry = geometryMap.get(u.substring(1)); addGeometry(geometry); } return true; } catch (ParserConfigurationException e) { Base.logger.log(Level.SEVERE,"Could not configure parser",e); } catch (SAXException e) { Base.logger.log(Level.INFO,"Could not configure parser",e); } catch (IOException e) { Base.logger.log(Level.SEVERE,"IO Error during Collada document read",e); } return false; } }
false
false
null
null
diff --git a/exquery-restxq/src/test/java/org/exquery/restxq/impl/PathAnnotationImplTest.java b/exquery-restxq/src/test/java/org/exquery/restxq/impl/PathAnnotationImplTest.java index dba5f6a..2a19bc6 100644 --- a/exquery-restxq/src/test/java/org/exquery/restxq/impl/PathAnnotationImplTest.java +++ b/exquery-restxq/src/test/java/org/exquery/restxq/impl/PathAnnotationImplTest.java @@ -1,457 +1,457 @@ /* Copyright (c) 2012, Adam Retter All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Adam Retter Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Adam Retter BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.exquery.restxq.impl; import javax.xml.namespace.QName; +import org.exquery.ErrorCodes.ErrorCode; import org.exquery.restxq.RestXqErrorCodes; -import org.exquery.restxq.RestXqErrorCodes.RestXqErrorCode; import org.exquery.restxq.annotation.RestAnnotationException; import org.exquery.restxq.impl.annotation.PathAnnotationImpl; import org.exquery.xquery.Cardinality; import org.exquery.xquery.FunctionArgument; import org.exquery.xquery.Literal; import org.exquery.xquery.Type; import org.exquery.xquery3.Annotation; import org.exquery.xquery3.FunctionSignature; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * * @author Adam Retter <adam.retter@googlemail.com> */ public class PathAnnotationImplTest { @Test public void pathSpecificity_three_concrete_missing_preceding_slash() throws RestAnnotationException { final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new NoArgsFunctionSignature()); pa.setLiterals(new Literal[]{ new StringLiteral("person/elisabeth/nose") }); pa.initialise(); assertEquals(15, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_three_concrete() throws RestAnnotationException { final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new NoArgsFunctionSignature()); pa.setLiterals(new Literal[]{ new StringLiteral("/person/elisabeth/nose") }); pa.initialise(); assertEquals(15, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_two_concrete_one_template() throws RestAnnotationException { final FunctionArgument[] args = { new StrFnArg("part") }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/person/elisabeth/{$part}") }); pa.initialise(); assertEquals(14, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_one_concrete_one_template_one_concrete() throws RestAnnotationException { final FunctionArgument[] args = { new StrFnArg("name") }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/person/{$name}/nose") }); pa.initialise(); assertEquals(13, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_one_concrete_two_template_last() throws RestAnnotationException { final FunctionArgument[] args = { new StrFnArg("name"), new StrFnArg("part") }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/person/{$name}/{$part}") }); pa.initialise(); assertEquals(12, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_one_template_two_concrete() throws RestAnnotationException { final FunctionArgument[] args = { new StrFnArg("type"), new StrFnArg("part") }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/{$type}/elisabeth/nose") }); pa.initialise(); assertEquals(11, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_one_template_one_concrete_one_template() throws RestAnnotationException { final FunctionArgument[] args = { new StrFnArg("type"), new StrFnArg("part") }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/{$type}/elisabeth/{$part}") }); pa.initialise(); assertEquals(10, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_one_concrete_two_template_first() throws RestAnnotationException { final FunctionArgument[] args = { new StrFnArg("type"), new StrFnArg("name") }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/{$type}/{$name}/nose") }); pa.initialise(); assertEquals(9, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_three_template() throws RestAnnotationException { final FunctionArgument[] args = { new StrFnArg("type"), new StrFnArg("name"), new StrFnArg("part") }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/{$type}/{$name}/{$part}") }); pa.initialise(); assertEquals(8, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_two_concrete() throws RestAnnotationException { final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new NoArgsFunctionSignature()); pa.setLiterals(new Literal[]{ new StringLiteral("/person/elisabeth") }); pa.initialise(); assertEquals(7, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_one_concrete_one_template() throws RestAnnotationException { final FunctionArgument[] args = { new StrFnArg("name"), }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/person/{$name}") }); pa.initialise(); assertEquals(6, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_one_template_one_concrete() throws RestAnnotationException { final FunctionArgument[] args = { new StrFnArg("type"), }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/{$type}/elisabeth") }); pa.initialise(); assertEquals(5, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_two_template() throws RestAnnotationException { final FunctionArgument[] args = { new StrFnArg("type"), new StrFnArg("name") }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/{$type}/{$name}") }); pa.initialise(); assertEquals(4, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_one_concrete() throws RestAnnotationException { final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new NoArgsFunctionSignature()); pa.setLiterals(new Literal[]{ new StringLiteral("/person") }); pa.initialise(); assertEquals(3, pa.getPathSpecificityMetric()); } @Test public void pathSpecificity_one_template() throws RestAnnotationException { final FunctionArgument[] args = { new StrFnArg("type") }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/{$type}") }); pa.initialise(); assertEquals(2, pa.getPathSpecificityMetric()); } @Test public void path_fnArgItemType_one_template_isOk() throws RestAnnotationException { final FunctionArgument[] args = { new ItemFnArg("arg1") }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/{$type}") }); pa.initialise(); } @Test public void path_fnArgNodeType_one_template_isNotOk() throws RestAnnotationException { final FunctionArgument[] args = { new NodeFnArg("arg1") }; final PathAnnotationImpl pa = new PathAnnotationImpl(); pa.setFunctionSignature(new ArgsFunctionSignature(args)); pa.setLiterals(new Literal[]{ new StringLiteral("/{$type}") }); - RestXqErrorCode code = null; + ErrorCode code = null; try { pa.initialise(); } catch(final RestAnnotationException rae) { code = rae.getErrorCode(); } assertEquals(RestXqErrorCodes.RQST0006, code); } public class NodeFnArg implements FunctionArgument { private final String name; public NodeFnArg(final String name) { this.name = name; } @Override public String getName() { return name; } @Override public Type getType() { return Type.NODE; } @Override public Cardinality getCardinality() { return Cardinality.ZERO_OR_ONE; } } public class ItemFnArg implements FunctionArgument { private final String name; public ItemFnArg(final String name) { this.name = name; } @Override public String getName() { return name; } @Override public Type getType() { return Type.ITEM; } @Override public Cardinality getCardinality() { return Cardinality.ZERO_OR_ONE; } } public class StrFnArg implements FunctionArgument { private final String name; public StrFnArg(final String name) { this.name = name; } @Override public String getName() { return name; } @Override public Type getType() { return Type.STRING; } @Override public Cardinality getCardinality() { return Cardinality.ZERO_OR_ONE; } } public class NoArgsFunctionSignature implements FunctionSignature { @Override public QName getName() { return new QName("http://somewhere", "something"); } @Override public int getArgumentCount() { return 0; } @Override public FunctionArgument[] getArguments() { return new FunctionArgument[]{}; } @Override public Annotation[] getAnnotations() { return new Annotation[]{}; } } public class ArgsFunctionSignature implements FunctionSignature { private final FunctionArgument[] args; public ArgsFunctionSignature(final FunctionArgument[] args) { this.args = args; } @Override public QName getName() { return new QName("http://somewhere", "something"); } @Override public int getArgumentCount() { return args.length; } @Override public FunctionArgument[] getArguments() { return args; } @Override public Annotation[] getAnnotations() { return new Annotation[]{}; } } public class StringLiteral implements Literal { private final String str; public StringLiteral(final String str) { this.str = str; } @Override public Type getType() { return Type.STRING; } @Override public String getValue() { return str; } } }
false
false
null
null
diff --git a/BlaAgent/src/main/java/com/ismobile/blaagent/Assignment.java b/BlaAgent/src/main/java/com/ismobile/blaagent/Assignment.java index dcbf1da..96d3ae7 100644 --- a/BlaAgent/src/main/java/com/ismobile/blaagent/Assignment.java +++ b/BlaAgent/src/main/java/com/ismobile/blaagent/Assignment.java @@ -1,69 +1,76 @@ package com.ismobile.blaagent; /** * Created by pbm on 2013-07-03. */ public class Assignment { private float longi; private float lati; private String title; private String uid; private boolean booked; private String start; private String stop; - public Assignment() { + public Assignment(String title, String uid, boolean booked, String startTime, String stopTime, float latitude, float longitude) { + this.title = title; + this.uid = uid; + this.booked = booked; + this.start = startTime; + this.stop = stopTime; + this.lati = latitude; + this.longi = longitude; } - +/* public void setLongi(float longitude) { this.longi = longitude; } public void setLati(float latitude) { this.lati = latitude; } public void setTitle(String titleAss) { this.title = titleAss; } public void setUid(String uId) { this.uid = uId; } public void setBooked(boolean bookedAss) { this.booked = bookedAss; } public void setStart(String startTime) { this.start = startTime; } public void setStop(String stopTime) { this.stop = stopTime; } - +*/ public String getTitle() { //return this.title; return "Byte av glödlampa."; } public String getUid() { return this.uid; } public String getStart() { return this.start; } public String getStop() { //return this.stop; return "16:00"; } public boolean getBooked() { return this.booked; } public float getLongitude() { return this.longi; } public float getLatitude() { return this.lati; } }
false
false
null
null
diff --git a/src/java/mc/alk/arena/controllers/containers/AbstractAreaContainer.java b/src/java/mc/alk/arena/controllers/containers/AbstractAreaContainer.java index 69ea413..b003d81 100644 --- a/src/java/mc/alk/arena/controllers/containers/AbstractAreaContainer.java +++ b/src/java/mc/alk/arena/controllers/containers/AbstractAreaContainer.java @@ -1,323 +1,325 @@ package mc.alk.arena.controllers.containers; import mc.alk.arena.BattleArena; import mc.alk.arena.Defaults; import mc.alk.arena.competition.match.PerformTransition; import mc.alk.arena.controllers.MethodController; import mc.alk.arena.controllers.messaging.MessageHandler; import mc.alk.arena.events.BAEvent; import mc.alk.arena.events.players.ArenaPlayerLeaveEvent; import mc.alk.arena.events.players.ArenaPlayerLeaveLobbyEvent; import mc.alk.arena.events.players.ArenaPlayerTeleportEvent; import mc.alk.arena.listeners.PlayerHolder; import mc.alk.arena.listeners.competition.InArenaListener; import mc.alk.arena.objects.ArenaPlayer; import mc.alk.arena.objects.CompetitionState; import mc.alk.arena.objects.ContainerState; import mc.alk.arena.objects.LocationType; import mc.alk.arena.objects.MatchParams; import mc.alk.arena.objects.MatchState; import mc.alk.arena.objects.arenas.ArenaListener; import mc.alk.arena.objects.events.ArenaEventHandler; import mc.alk.arena.objects.options.TransitionOptions; import mc.alk.arena.objects.teams.ArenaTeam; import mc.alk.arena.objects.teams.TeamHandler; import mc.alk.arena.util.CommandUtil; import mc.alk.arena.util.Log; import mc.alk.arena.util.MessageUtil; import mc.alk.arena.util.PermissionsUtil; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.event.EventHandler; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public abstract class AbstractAreaContainer implements PlayerHolder, TeamHandler{ public static final AbstractAreaContainer HOMECONTAINER = new AbstractAreaContainer("home"){ @Override public LocationType getLocationType() {return LocationType.HOME;} @Override public ArenaTeam getTeam(ArenaPlayer player) {return null;} }; protected String name; protected String displayName; protected MatchParams params; ContainerState state = ContainerState.OPEN; + boolean disabledAllCommands; Set<String> disabledCommands; + Set<String> enabledCommands; private final MethodController methodController; protected Set<String> players = new HashSet<String>(); /** Spawn points */ protected List<Location> spawns = new ArrayList<Location>(); /** Main Spawn is different than the normal spawns. It is specified by Defaults.MAIN_SPAWN */ Location mainSpawn = null; /** Our teams */ protected List<ArenaTeam> teams = Collections.synchronizedList(new ArrayList<ArenaTeam>()); /** our values for the team index, only used if the Team.getIndex is null*/ final Map<ArenaTeam,Integer> teamIndexes = new ConcurrentHashMap<ArenaTeam,Integer>(); static Random r = new Random(); public AbstractAreaContainer(String name){ methodController = new MethodController("AAC " + name); methodController.addAllEvents(this); try{Bukkit.getPluginManager().registerEvents(this, BattleArena.getSelf());}catch(Exception e){ //noinspection PointlessBooleanExpression,ConstantConditions if (!Defaults.TESTSERVER && !Defaults.TESTSERVER_DEBUG) Log.printStackTrace(e); } this.name = name; } public void callEvent(BAEvent event){ methodController.callEvent(event); } public void playerLeaving(ArenaPlayer player){ methodController.updateEvents(MatchState.ONLEAVE, player); } protected void updateBukkitEvents(MatchState matchState,ArenaPlayer player){ methodController.updateEvents(matchState, player); } protected void teamLeaving(ArenaTeam team){ if (teams.remove(team)){ methodController.updateEvents(MatchState.ONLEAVE, team.getPlayers()); } } public boolean teamJoining(ArenaTeam team){ teams.add(team); teamIndexes.put(team, teams.size()); for (ArenaPlayer ap: team.getPlayers()){ players.add(ap.getName());} return true; } /** * Tekkit Servers don't get the @EventHandler methods (reason unknown) so have this method be * redundant. Possibly can now simplify to just the @ArenaEventHandler * @param event ArenaPlayerLeaveEvent */ @ArenaEventHandler public void onArenaPlayerLeaveEvent(ArenaPlayerLeaveEvent event) { _onArenaPlayerLeaveEvent(event); } @EventHandler public void _onArenaPlayerLeaveEvent(ArenaPlayerLeaveEvent event){ if (players.remove(event.getPlayer().getName())){ updateBukkitEvents(MatchState.ONLEAVE, event.getPlayer()); callEvent(new ArenaPlayerLeaveLobbyEvent(event.getPlayer(),event.getTeam())); event.addMessage(MessageHandler.getSystemMessage("you_left_competition", this.params.getName())); event.getPlayer().reset(); } } /** * Tekkit Servers don't get the @EventHandler methods (reason unknown) so have this method be * redundant. Possibly can now simplify to just the @ArenaEventHandler * @param event PlayerCommandPreprocessEvent */ @ArenaEventHandler public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { _onPlayerCommandPreprocess(event); } @EventHandler public void _onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event){ if (disabledCommands == null) return; if (!event.isCancelled() && InArenaListener.inQueue(event.getPlayer().getName()) && - CommandUtil.shouldCancel(event, disabledCommands)){ + CommandUtil.shouldCancel(event, disabledAllCommands, disabledCommands, enabledCommands)){ event.setCancelled(true); event.getPlayer().sendMessage(ChatColor.RED+"You cannot use that command when you are in the "+displayName); if (PermissionsUtil.isAdmin(event.getPlayer())){ MessageUtil.sendMessage(event.getPlayer(),"&cYou can set &6/bad allowAdminCommands true: &c to change");} } } public void setDisabledCommands(List<String> commands) { if (disabledCommands == null) disabledCommands = new HashSet<String>(); for (String s: commands){ disabledCommands.add("/" + s.toLowerCase());} } protected void doTransition(MatchState state, ArenaPlayer player, ArenaTeam team, boolean onlyInMatch){ if (player != null){ PerformTransition.transition(this, state, player,team, onlyInMatch); } else { PerformTransition.transition(this, state, team, onlyInMatch); } } @Override public boolean canLeave(ArenaPlayer p) { return false; } @Override public boolean leave(ArenaPlayer p) { return players.remove(p.getName()); } @Override public void addArenaListener(ArenaListener arenaListener) { this.methodController.addListener(arenaListener); } @Override public MatchParams getParams() { return params; } public void setParams(MatchParams mp) { this.params= mp; } @Override public MatchState getMatchState() { return MatchState.INLOBBY; } @Override public boolean isHandled(ArenaPlayer player) { return players.contains(player.getName()); } @Override public CompetitionState getState() { return null; } @Override public boolean checkReady(ArenaPlayer player, ArenaTeam team, TransitionOptions mo, boolean b) { return params.getTransitionOptions().playerReady(player, null); } @Override public Location getSpawn(int index, boolean random) { if (index == Defaults.MAIN_SPAWN) return mainSpawn != null ? mainSpawn : (spawns.size()==1 ? spawns.get(0) : null); if (random){ return spawns.get(r.nextInt(spawns.size())); } else{ return index >= spawns.size() ? spawns.get(index % spawns.size()) : spawns.get(index); } } @Override public Location getSpawn(ArenaPlayer player, boolean random) { return null; } /** * Set the spawn location for the team with the given index * @param index index of spawn * @param loc location */ public void setSpawnLoc(int index, Location loc) throws IllegalStateException{ if (index == Defaults.MAIN_SPAWN){ mainSpawn = loc; } else if (spawns.size() > index){ spawns.set(index, loc); } else if (spawns.size() == index){ spawns.add(loc); } else { throw new IllegalStateException("You must set spawn " + (spawns.size()+1) + " first"); } } public boolean validIndex(int index){ return spawns != null && spawns.size() < index; } public List<Location> getSpawns(){ return spawns; } public Location getMainSpawn(){ return mainSpawn; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDisplayName() { return displayName == null ? name : displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } @Override public void onPreJoin(ArenaPlayer player, ArenaPlayerTeleportEvent apte) {/* do nothing */} @Override public void onPostJoin(ArenaPlayer player, ArenaPlayerTeleportEvent apte) {/* do nothing */} @Override public void onPreQuit(ArenaPlayer player, ArenaPlayerTeleportEvent apte) {/* do nothing */} @Override public void onPostQuit(ArenaPlayer player, ArenaPlayerTeleportEvent apte) {/* do nothing */} @Override public void onPreEnter(ArenaPlayer player, ArenaPlayerTeleportEvent apte) {/* do nothing */} @Override public void onPostEnter(ArenaPlayer player,ArenaPlayerTeleportEvent apte) {/* do nothing */} @Override public void onPreLeave(ArenaPlayer player, ArenaPlayerTeleportEvent apte) {/* do nothing */} @Override public void onPostLeave(ArenaPlayer player, ArenaPlayerTeleportEvent apte) {/* do nothing */} public void setContainerState(ContainerState state) { this.state = state; } public ContainerState getContainerState() { return this.state; } public boolean isOpen() { return state.isOpen(); } public boolean isClosed() { return state.isClosed(); } public String getContainerMessage() { return state.getMsg(); } } diff --git a/src/java/mc/alk/arena/util/CommandUtil.java b/src/java/mc/alk/arena/util/CommandUtil.java index d53428e..bebe5c8 100644 --- a/src/java/mc/alk/arena/util/CommandUtil.java +++ b/src/java/mc/alk/arena/util/CommandUtil.java @@ -1,30 +1,31 @@ package mc.alk.arena.util; import mc.alk.arena.Defaults; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import java.util.Set; public class CommandUtil { public static boolean shouldCancel(PlayerCommandPreprocessEvent event, boolean allDisabled, Set<String> disabledCommands, Set<String> enabledCommands){ if (Defaults.DEBUG_COMMANDS){ event.getPlayer().sendMessage("event Message=" + event.getMessage() +" isCancelled=" + event.isCancelled());} - if (disabledCommands.isEmpty()) + if (disabledCommands == null || disabledCommands.isEmpty()) return false; if (Defaults.ALLOW_ADMIN_CMDS_IN_Q_OR_MATCH && PermissionsUtil.isAdmin(event.getPlayer())){ return false;} if (allDisabled && (enabledCommands.isEmpty())) return true; String cmd = event.getMessage(); final int index = cmd.indexOf(' '); if (index != -1){ cmd = cmd.substring(0, index); } cmd = cmd.toLowerCase(); - return !cmd.equals("/bad") && ( allDisabled ? !enabledCommands.contains(cmd) : - disabledCommands.contains(cmd) && !enabledCommands.contains(cmd) ); + return !cmd.equals("/bad") && ( allDisabled ? + (enabledCommands == null || !enabledCommands.contains(cmd)) : + disabledCommands.contains(cmd) && (enabledCommands==null || !enabledCommands.contains(cmd)) ); } }
false
false
null
null
diff --git a/node-common/src/main/java/com/github/nethad/clustermeister/node/common/ClustermeisterLauncher.java b/node-common/src/main/java/com/github/nethad/clustermeister/node/common/ClustermeisterLauncher.java index e31a79b..bf57739 100644 --- a/node-common/src/main/java/com/github/nethad/clustermeister/node/common/ClustermeisterLauncher.java +++ b/node-common/src/main/java/com/github/nethad/clustermeister/node/common/ClustermeisterLauncher.java @@ -1,229 +1,233 @@ /* * Copyright 2012 The Clustermeister Team. * * 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.github.nethad.clustermeister.node.common; import com.github.nethad.clustermeister.node.common.ClustermeisterProcessLauncher.StreamSink; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; import java.util.Observable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Launches a JPPF-Node in a new spawned process (JVM) and is able * to react (by returning or notifying) when the process is initialized. * * A dependent child process will keep this JVM running until the child process * or this JVM dies. Observers will be notified when the initialization is * complete. * * An independent process will kill this JVM (and thus "return") upon successful * initialization of the sub process. * * @author daniel */ public abstract class ClustermeisterLauncher extends Observable { private static final String JPPF_THREAD_NAME = "CMLauncherThread"; protected final static Logger logger = LoggerFactory.getLogger(ClustermeisterLauncher.class); /** * Custom Process Launcher. */ protected ClustermeisterProcessLauncher processLauncher = null; private Thread jppfThread = null; private boolean printUUIDtoStdOut = false; /** * Performs the launching of a new JVM using the runner from {@link #getRunner()}. * * @param launchAsChildProcess * Whether to launch a child process or independent process. * @param sink * Where to divert the sub-process's streams to. If launched as * independent process the streams are always diverted to file. */ synchronized public void doLaunch(boolean launchAsChildProcess, StreamSink sink) { PipedInputStream in = new PipedInputStream(); PrintStream sout = System.out; PipedOutputStream out = null; String uuidLine = null; try { out = new PipedOutputStream(in); //prepare to capture spawned processes output stream. System.setOut(new PrintStream(out)); try { //Spawn a new JVM startUp(launchAsChildProcess); - uuidLine = waitForUUID(in, sout); + uuidLine = waitForUUID(in, sout, sink); if(launchAsChildProcess) { if (sink == null) { processLauncher.setStreamSink(StreamSink.STD); } else { processLauncher.setStreamSink(sink); } } } catch (Exception ex) { logger.warn("Exception while launching.", ex); } } catch (IOException ex) { logger.warn("Can not read from pipe output stream of the JPPF sub-process.", ex); } finally { //restore output stream. System.setOut(sout); closeStream(in); closeStream(out); sout.flush(); } if(printUUIDtoStdOut) { System.out.println(uuidLine); } setChanged(); notifyObservers(uuidLine); } /** * Stops the sub-process (JVM). * * This method is as graceful as possible. * * @throws Exception when any exception occurs. */ synchronized public void shutdownProcess() throws Exception { if(processLauncher != null) { Process process = processLauncher.getProcess(); if(process != null) { final OutputStream outputStream = process.getOutputStream(); outputStream.write(ShutdownHandler.SHUTDOWN_STRING.getBytes(Constants.UTF8)); outputStream.flush(); } } } /** * Whether the UUID is printed to stdout. * * @return True if the UUID is printed to stdout. False otherwise. */ public boolean isPrintUUIDtoStdOut() { return printUUIDtoStdOut; } /** * Set whether the UUID should be printed to stdout. * * By default this is set to false. * * @param printUUIDtoStdOut true to print the UUID to stdout, false to not * print the UUID to stdout. */ public void setPrintUUIDtoStdOut(boolean printUUIDtoStdOut) { this.printUUIDtoStdOut = printUUIDtoStdOut; } protected ClustermeisterProcessLauncher createProcessLauncher() { return new ClustermeisterProcessLauncher(getRunner()); } /** * Get the fully qualified class name of the runner to use. * * @return the runner. */ abstract protected String getRunner(); /** * Starts the JPPF process (a new JVM). * * If launched as independent process the streams are always diverted to files. * * @param launchAsChildProcess * whether to launch as child process or independent process. * * @throws Exception when any exception occurs process spawning preparation. */ protected void startUp(boolean launchAsChildProcess) throws Exception { processLauncher = createProcessLauncher(); processLauncher.setLaunchAsChildProcess(launchAsChildProcess); if(!launchAsChildProcess) { processLauncher.setStreamSink(StreamSink.FILE); } jppfThread = new Thread(new Runnable() { @Override public void run() { processLauncher.run(); } }); jppfThread.setName(String.format("%s-%s", JPPF_THREAD_NAME, jppfThread.getId())); jppfThread.start(); } /** * Parse a boolean from given arguments and index. * If the argument array does not contain the index return the specified * default value. * * @param args the arguments. * @param index the argument index to parse. * @param defaultValue the default value. * @return the parsed boolean or the default value. */ protected static boolean getBooleanArgument(String[] args, int index, boolean defaultValue) { boolean value = defaultValue; if(args != null && args.length > index) { value = Boolean.parseBoolean(args[index]); } return value; } - private String waitForUUID(InputStream in, PrintStream sout) + private String waitForUUID(InputStream in, PrintStream sout, StreamSink sink) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in, Constants.UTF8)); logger.info("Waiting for UUID."); String line; while((line = reader.readLine()) != null) { if(line.startsWith(Constants.UUID_PREFIX)) { logger.info("Got {}.", line); return line; } else { - sout.println(line); + if(sink != null && sink == StreamSink.LOG) { + logger.info(line); + } else { + sout.println(line); + } } } return null; } private void closeStream(Closeable in) { if(in != null) { try { in.close(); } catch (IOException ex) { logger.warn("Can not close stream.", ex); } } } }
false
false
null
null
diff --git a/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/validation/ErrorModelJavaValidator.java b/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/validation/ErrorModelJavaValidator.java index 1c11c683..c8efcfac 100644 --- a/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/validation/ErrorModelJavaValidator.java +++ b/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/validation/ErrorModelJavaValidator.java @@ -1,821 +1,821 @@ package org.osate.xtext.aadl2.errormodel.validation; import java.util.Collection; import java.util.HashSet; import java.util.Hashtable; import java.util.Map; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.validation.Check; import org.eclipse.xtext.validation.CheckType; import org.osate.aadl2.Classifier; import org.osate.aadl2.ComponentClassifier; import org.osate.aadl2.ComponentImplementation; import org.osate.aadl2.Connection; import org.osate.aadl2.ConnectionEnd; import org.osate.aadl2.ContainedNamedElement; import org.osate.aadl2.ContainmentPathElement; import org.osate.aadl2.Context; import org.osate.aadl2.DirectionType; import org.osate.aadl2.Element; import org.osate.aadl2.Feature; import org.osate.aadl2.ModeTransition; import org.osate.aadl2.NamedElement; import org.osate.aadl2.Port; import org.osate.aadl2.PropertyAssociation; import org.osate.aadl2.Subcomponent; import org.osate.aadl2.modelsupport.util.AadlUtil; import org.osate.aadl2.util.Aadl2Util; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorEvent; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorState; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorStateMachine; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorTransition; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorEvent; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelFactory; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelLibrary; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelSubclause; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPath; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPropagation; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPropagations; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorSink; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorSource; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorType; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorTypes; import org.osate.xtext.aadl2.errormodel.errorModel.PropagationPoint; import org.osate.xtext.aadl2.errormodel.errorModel.PropagationPointConnection; import org.osate.xtext.aadl2.errormodel.errorModel.RecoverEvent; import org.osate.xtext.aadl2.errormodel.errorModel.TypeMappingSet; import org.osate.xtext.aadl2.errormodel.errorModel.TypeSet; import org.osate.xtext.aadl2.errormodel.errorModel.TypeToken; import org.osate.xtext.aadl2.errormodel.errorModel.TypeTransformationSet; import org.osate.xtext.aadl2.errormodel.errorModel.TypeUseContext; import org.osate.xtext.aadl2.errormodel.errorModel.impl.ErrorModelPackageImpl; import org.osate.xtext.aadl2.errormodel.util.EM2TypeSetUtil; import org.osate.xtext.aadl2.errormodel.util.EMV2Util; public class ErrorModelJavaValidator extends AbstractErrorModelJavaValidator { @Override protected boolean isResponsible(Map<Object, Object> context, EObject eObject) { return (eObject.eClass().getEPackage() == ErrorModelPackageImpl.eINSTANCE || eObject instanceof Connection || eObject instanceof PropertyAssociation); } @Check(CheckType.FAST) public void caseErrorPropagation(ErrorPropagation errorPropagation) { checkDirectionType(errorPropagation); } @Check(CheckType.FAST) public void casePropagationPoint(PropagationPoint propagationPoint) { checkUniquePropagationPointorConnection(propagationPoint); } @Check(CheckType.FAST) public void casePropertyAssociation(PropertyAssociation propertyAssociation) { // check that error type is contained in type set of target element EList<ContainedNamedElement> apto = propertyAssociation.getAppliesTos(); for (ContainedNamedElement containedNamedElement : apto) { EList<ContainmentPathElement> cpe = containedNamedElement .getContainmentPathElements(); if (cpe.size() > 1) { ContainmentPathElement obj = cpe.get(cpe.size() - 1); if (obj.getNamedElement() instanceof ErrorType) { ErrorType et = (ErrorType) obj.getNamedElement(); ContainmentPathElement target = cpe.get(cpe.size() - 2); NamedElement ne = target.getNamedElement(); TypeSet tts = null; if (ne instanceof ErrorBehaviorState) { tts = ((ErrorBehaviorState) ne).getTypeSet(); } else if (ne instanceof ErrorPropagation) { tts = ((ErrorPropagation) ne).getTypeSet(); } else if (ne instanceof ErrorEvent) { tts = ((ErrorEvent) ne).getTypeSet(); } TypeToken tt = ErrorModelFactory.eINSTANCE .createTypeToken(); tt.getType().add(et); if (EM2TypeSetUtil.contains(tts, tt)) { } } } } } @Check(CheckType.FAST) public void casePropagationPointConnection(PropagationPointConnection opc) { checkUniquePropagationPointorConnection(opc); } @Check(CheckType.FAST) public void caseErrorType(ErrorType et) { checkCyclicExtends(et); } @Check(CheckType.FAST) public void caseTypeSet(TypeSet ts) { checkTypeSetUniqueTypes(ts); } @Check(CheckType.FAST) public void caseTypeToken(TypeToken tt) { checkTypeTokenUniqueTypes(tt); } @Check(CheckType.FAST) public void caseRecoverEvent(RecoverEvent recoverEvent) { checkRecoverEventTriggerType(recoverEvent); } @Check(CheckType.NORMAL) public void caseErrorModelSubclause(ErrorModelSubclause subclause) { Collection<NamedElement> names = EMV2Util.getAllNamedElements(subclause); EList<NamedElement> doubles = AadlUtil.findDoubleNamedElementsInList(names); for (NamedElement namedElement : doubles) { error(namedElement, namedElement.getName()+" has duplicate definitions."); } } @Check(CheckType.NORMAL) public void caseErrorPropagations(ErrorPropagations errorPropagations) { checkOnePropagationAndContainmentPoint(errorPropagations); } @Check(CheckType.NORMAL) public void caseTypeMappingSet(TypeMappingSet tms) { // checkElementRuleConsistency(tms); } @Check(CheckType.NORMAL) public void caseErrorModelLibrary(ErrorModelLibrary errorModelLibrary) { if (errorModelLibrary.getName() == null) errorModelLibrary.setName("emv2"); boolean cyclicextends = checkCyclicExtends(errorModelLibrary); checkUniqueDefiningIdentifiers(errorModelLibrary, cyclicextends); } @Check(CheckType.NORMAL) public void caseErrorBehaviorStateMachine(ErrorBehaviorStateMachine ebsm) { // checkCyclicExtends(ebsm); checkUniqueEBSMElements(ebsm); } @Check(CheckType.NORMAL) public void caseTypeUseContext(TypeUseContext typeUseContext) { checkMultipleUses(typeUseContext); checkMultipleErrorTypesInUsesTypes(typeUseContext); } @Check(CheckType.NORMAL) public void caseErrorSource(ErrorSource ef) { checkErrorSourceTypes(ef); checkFlowDirection(ef); } @Check(CheckType.NORMAL) public void caseErrorSink(ErrorSink ef) { checkErrorSinkTypes(ef); checkFlowDirection(ef); } @Check(CheckType.NORMAL) public void caseErrorPath(ErrorPath ef) { checkErrorPathTypes(ef); checkFlowDirection(ef); } @Check(CheckType.NORMAL) public void caseConnection(Connection conn) { checkConnectionErrorTypes(conn); } private void checkRecoverEventTriggerType(RecoverEvent recoverEvent) { EList<NamedElement> cl = recoverEvent.getCondition(); for (NamedElement namedElement : cl) { if (!(namedElement instanceof Port || namedElement instanceof ModeTransition)) { error(recoverEvent, "Recover event trigger reference '" + namedElement.getName() + "' is not a port or mode transition."); } } } private void checkDirectionType(ErrorPropagation errorPropagation) { DirectionType pd = errorPropagation.getDirection(); Feature f = EMV2Util.getFeature(errorPropagation); if (!Aadl2Util.isNull(f) && f instanceof Port) { DirectionType portd = ((Port) f).getDirection(); if (!(pd.getName().equalsIgnoreCase(portd.getName()) || portd == DirectionType.IN_OUT)) error(errorPropagation, "Propagation direction does not match port direction."); } } private void checkOnePropagationAndContainmentPoint( ErrorPropagations errorPropagations) { EList<ErrorPropagation> eps = errorPropagations.getPropagations(); int epssize = eps.size(); for (int i = 0; i < epssize - 1; i++) { ErrorPropagation ep1 = eps.get(i); for (int k = i + 1; k < epssize; k++) { ErrorPropagation ep2 = eps.get(k); if (EMV2Util.getFeature(ep1) == EMV2Util.getFeature(ep2)) { - if (ep1.isNot() && ep2.isNot() || !ep1.isNot() - && !ep2.isNot()) { + if ((ep1.isNot() && ep2.isNot() || !ep1.isNot() + && !ep2.isNot()) && ep1.getDirection() == ep2.getDirection()) { error(ep2, (ep1.isNot() ? "Error containment " : "Error propagation ") + EMV2Util.getPrintName(ep2) + " already defined."); } } } } } private void checkFlowDirection(ErrorSource errorSource) { ErrorPropagation ep = errorSource.getOutgoing(); if (!Aadl2Util.isNull(ep)) { DirectionType epd = ep.getDirection(); if (!(epd.equals(DirectionType.OUT))) { error(errorSource, EMV2Util.getPrintName(ep) + " of error source is not an outgoing propagation point."); } } } private void checkFlowDirection(ErrorSink errorSink) { ErrorPropagation ep = errorSink.getIncoming(); if (!Aadl2Util.isNull(ep)) { DirectionType epd = ep.getDirection(); if (!(epd.equals(DirectionType.IN))) { error(errorSink, EMV2Util.getPrintName(ep) + " of error sink is not an incoming propagation point."); } } } private void checkFlowDirection(ErrorPath errorPath) { ErrorPropagation ep = errorPath.getIncoming(); if (!Aadl2Util.isNull(ep)) { DirectionType epd = ep.getDirection(); if (!(epd.equals(DirectionType.IN))) { error(errorPath, "Source " + EMV2Util.getPrintName(ep) + " of error path is not an incoming propagation point."); } } ep = errorPath.getOutgoing(); if (!Aadl2Util.isNull(ep)) { DirectionType epd = ep.getDirection(); if (!(epd.equals(DirectionType.OUT))) { error(errorPath, "Target " + EMV2Util.getPrintName(ep) + " of error path is not an outgoing propagation point."); } } } // private void checkElementMappingTypeConsistency(ElementTypeMapping // etMapping){ // ErrorType srcET = etMapping.getSource(); // ErrorType tgtET = etMapping.getTarget(); // if (!Aadl2Util.isNull(srcET) && !Aadl2Util.isNull(tgtET)){ // if (!EM2TypeSetUtil.inSameTypeHierarchy(srcET, tgtET)){ // error(etMapping, // "Source and target error types are not in same type hierarchy"); // } // } // } // // private void // checkElementTransformTypeConsistency(ElementTypeTransformation etXform){ // ErrorType srcET = etXform.getSource(); // ErrorType conET = etXform.getContributor(); // ErrorType tgtET = etXform.getTarget(); // if (!Aadl2Util.isNull(srcET) && !Aadl2Util.isNull(tgtET)){ // if (!EM2TypeSetUtil.inSameTypeHierarchy(srcET, tgtET)){ // error(etXform, // "Source type "+srcET.getName()+" and target type "+tgtET.getName()+" are not in same type hierarchy"); // } // } // if (!Aadl2Util.isNull(srcET) && !Aadl2Util.isNull(conET)){ // if (!EM2TypeSetUtil.inSameTypeHierarchy(srcET, conET)){ // error(etXform, // "Source type "+srcET.getName()+" and contributor type "+conET.getName()+" are not in same type hierarchy"); // } // } // } // // private void checkElementRuleConsistency(TypeMappingSet tms){ // HashSet<ErrorType> sourceTypes = new HashSet<ErrorType>(); // for (TypeMapping tm : tms.getMapping()){ // if (tm instanceof ElementTypeMapping){ // ErrorType et = ((ElementTypeMapping) tm).getSource(); // if (sourceTypes.contains(et)){ // error(tm, // "Type "+et.getName()+" already being mapped"); // } else { // sourceTypes.add(et); // } // } // } // } private void checkTypeSetUniqueTypes(TypeSet ts) { EList<TypeToken> etlist = ts.getElementType(); int size = etlist.size(); for (int i = 0; i < size - 1; i++) { TypeToken tok = etlist.get(i); for (int k = i + 1; k < size; k++) { TypeToken tok2 = etlist.get(k); if (EM2TypeSetUtil.contains(tok, tok2) || EM2TypeSetUtil.contains(tok2, tok)) { error(ts, "Typeset elements " + EMV2Util.getPrintName(tok) + " and " + EMV2Util.getPrintName(tok2) + " are not disjoint."); } } } } private void checkTypeTokenUniqueTypes(TypeToken ts) { HashSet<ErrorType> sourceTypes = new HashSet<ErrorType>(); for (ErrorType et : ts.getType()) { ErrorType root = EM2TypeSetUtil.rootType(et); if (sourceTypes.contains(root)) { error(et, "Another element type has same root type " + root.getName() + " as " + et.getName()); } else { sourceTypes.add(et); } } } private void checkMultipleUses(TypeUseContext tuc) { HashSet<ErrorModelLibrary> etlset = new HashSet<ErrorModelLibrary>(); for (ErrorModelLibrary etl : EMV2Util.getUseTypes(tuc)) { if (etlset.contains(etl)) { error(tuc, "Error type library " + EMV2Util.getPrintName(etl) + " exists more than once in 'uses types' clause"); } else { etlset.add(etl); } } } private void checkMultipleErrorTypesInUsesTypes(TypeUseContext tuc) { Hashtable<String, EObject> etlset = new Hashtable<String, EObject>(10, 10); for (ErrorModelLibrary etl : EMV2Util.getUseTypes(tuc)) { EList<ErrorTypes> typeslist = etl.getTypes(); for (ErrorTypes errorTypes : typeslist) { if (etlset.containsKey(errorTypes.getName())) { ErrorModelLibrary eml = EMV2Util .getContainingErrorModelLibrary((Element) etlset .get(errorTypes.getName())); error(tuc, "Error type or type set " + errorTypes.getName() + " in library " + EMV2Util.getPrintName(etl) + " already exists in error type library " + EMV2Util.getPrintName(eml)); } else { etlset.put(errorTypes.getName(), errorTypes); } } } } private void checkUniqueEBSMElements(ErrorBehaviorStateMachine ebsm) { Hashtable<String, EObject> etlset = new Hashtable<String, EObject>(10,10); for (ErrorBehaviorEvent oep : ebsm.getEvents()) { if (etlset.containsKey(oep.getName())) { error(oep, "error behavior event "+oep.getName()+ " defined more than once"); } else { etlset.put(oep.getName(), oep); } } for (ErrorBehaviorState oep : ebsm.getStates()) { if (etlset.containsKey(oep.getName())) { error(oep, "error behavior state "+oep.getName()+ " previously defined as "+etlset.get(oep.getName()).eClass().getName()); } else { etlset.put(oep.getName(), oep); } } for (ErrorBehaviorTransition oep : ebsm.getTransitions()) { if (etlset.containsKey(oep.getName())) { error(oep, "error behavior transition "+oep.getName()+ " previously defined as "+etlset.get(oep.getName()).eClass().getName()); } else { etlset.put(oep.getName(), oep); } } } private void checkUniquePropagationPointorConnection(NamedElement ep) { Collection<PropagationPoint> tab = EMV2Util.getAllPropagationPoints(ep.getContainingClassifier()); for (PropagationPoint oep : tab) { if (oep != ep && oep.getName().equalsIgnoreCase(ep.getName())) { error(ep, "Propagation point "+(ep instanceof PropagationPointConnection?"connection ":"") + ep.getName()+ " conflicts with propagation point."); } } for (PropagationPointConnection oep : EMV2Util.getAllPropagationPointConnections(ep.getContainingClassifier())) { if (oep != ep && oep.getName().equalsIgnoreCase(ep.getName())) { error(ep, "Propagation point "+(ep instanceof PropagationPointConnection?"connection ":"")+ ep.getName()+ "' conflicts with propagation point connection."); } } EObject searchResult = null; Classifier cl = AadlUtil.getContainingClassifier(ep); if (cl instanceof ComponentImplementation) { searchResult = ((ComponentImplementation) cl).getType() .findNamedElement(ep.getName()); } else { searchResult = AadlUtil.getContainingClassifier(ep) .findNamedElement(ep.getName()); } if (searchResult != null) { error(ep, "Propagation point " + ep.getName() + " conflicts with feature in component type " + cl.getName()); } } private void checkUniqueDefiningIdentifiers(ErrorModelLibrary etl, boolean cyclicextends) { Hashtable<String, EObject> types = new Hashtable<String, EObject>(10, 10); checkUniqueDefiningEBSMMappingsTransformations(etl, types); if (cyclicextends) return; for (ErrorModelLibrary xetl : etl.getExtends()) { checkUniqueInheritedDefiningErrorTypes(xetl, types); } } private void checkUniqueDefiningEBSMMappingsTransformations( ErrorModelLibrary etl, Hashtable<String, EObject> types) { for (ErrorBehaviorStateMachine ebsm : etl.getBehaviors()) { if (types.containsKey(ebsm.getName())) { error(ebsm, "Error behavior state machine identifier " + ebsm.getName() + " is not unique in error model library"); } types.put(ebsm.getName(), ebsm); } for (TypeMappingSet tms : etl.getMappings()) { if (types.containsKey(tms.getName())) { error(tms, "Type mapping set identifier " + tms.getName() + " is not unique in error model library"); } types.put(tms.getName(), tms); } for (TypeTransformationSet tts : etl.getTransformations()) { if (types.containsKey(tts.getName())) { error(tts, "Type transformation set identifier " + tts.getName() + " is not unique in error model library"); } types.put(tts.getName(), tts); } for (ErrorTypes ets : etl.getTypes()) { if (types.containsKey(ets.getName())) { error(ets, "Error type or type set (alias) identifier " + ets.getName() + " is not unique in error model library"); } types.put(ets.getName(), ets); } } private void checkUniqueInheritedDefiningErrorTypes(ErrorModelLibrary etl, Hashtable<String, EObject> types) { for (ErrorTypes et : etl.getTypes()) { if (types.containsKey(et.getName())) { ErrorModelLibrary eml = EMV2Util .getContainingErrorModelLibrary(et); error(et, "Error type or type set (alias) " + et.getName() + " inherited from " + EMV2Util.getPrintName(eml) + " conflicts with another defining identifier in error type library"); } types.put(et.getName(), et); } for (ErrorModelLibrary xetl : etl.getExtends()) { checkUniqueInheritedDefiningErrorTypes(xetl, types); } } private boolean checkCyclicExtends(ErrorModelLibrary etl) { if (etl.getExtends() == null) return false; HashSet<ErrorModelLibrary> result = new HashSet<ErrorModelLibrary>(); return recursiveCheckCyclicExtends(etl, result); } private boolean recursiveCheckCyclicExtends(ErrorModelLibrary etl, HashSet<ErrorModelLibrary> shetl) { boolean result = false; if (etl.getExtends() != null) { shetl.add(etl); EList<ErrorModelLibrary> etllist = etl.getExtends(); for (ErrorModelLibrary xetl : etllist) { if (shetl.contains(xetl)) { error(xetl, "Cycle in extends of error type library " + etl.getName()); result = true; } else { result = result || recursiveCheckCyclicExtends(xetl, shetl); } } shetl.remove(etl); } return result; } private void checkCyclicExtends(ErrorType origet) { ErrorType et = origet; if (et.getSuperType() == null) return; HashSet<ErrorType> result = new HashSet<ErrorType>(); while (et.getSuperType() != null) { result.add(et); et = et.getSuperType(); if (result.contains(et)) { error(origet, "Cycle in supertype hierarchy of error type " + origet.getName() + " at type " + et.getName()); return; } } } // private void checkCyclicExtends(ErrorBehaviorStateMachine origebsm){ // ErrorBehaviorStateMachine ebsm = origebsm; // if (ebsm.getExtends() == null) return; // HashSet<ErrorBehaviorStateMachine> result = new // HashSet<ErrorBehaviorStateMachine>(); // while (ebsm.getExtends() != null){ // result.add(ebsm); // ebsm = ebsm.getExtends(); // if (result.contains(ebsm)){ // error(origebsm, // "Cycle in extends of error behavior state machine "+origebsm.getName()); // return; // } // } // } private void checkErrorSourceTypes(ErrorSource ef) { ErrorPropagation ep = ef.getOutgoing(); if (!EM2TypeSetUtil.contains(ep.getTypeSet(), ef.getTypeTokenConstraint())) { error(ef, "Type token constraint " + EMV2Util.getPrintName(ef.getTypeTokenConstraint()) + " is not contained in type set of outgoing propagation " + EMV2Util.getPrintName(ep) + EMV2Util.getPrintName(ep.getTypeSet())); } } private void checkErrorSinkTypes(ErrorSink ef) { ErrorPropagation ep = ef.getIncoming(); if (!EM2TypeSetUtil.contains(ep.getTypeSet(), ef.getTypeTokenConstraint())) { error(ef, "Type token constraint is not contained in type set of incoming propagation \"" + EMV2Util.getPrintName(ep) + "\""); } } private void checkErrorPathTypes(ErrorPath ef) { if (ef.getTypeTokenConstraint() != null) { ErrorPropagation epin = ef.getIncoming(); if (!EM2TypeSetUtil.contains(epin.getTypeSet(), ef.getTypeTokenConstraint())) { error(ef, "Type token constraint is not contained in type set of incoming propagation \"" + EMV2Util.getPrintName(epin) + "\""); } } if (ef.getTargetToken() != null) { ErrorPropagation epout = ef.getOutgoing(); if (!EM2TypeSetUtil.contains(epout.getTypeSet(), ef.getTargetToken())) { error(ef, "Target token is not contained in type set of outgoing propagation " + EMV2Util.getPrintName(epout)); } } } private void checkConnectionErrorTypes(Connection conn) { ComponentImplementation cimpl = conn.getContainingComponentImpl(); ConnectionEnd src = conn.getAllSource(); Context srcCxt = conn.getAllSourceContext(); ErrorPropagation srcprop = null; ErrorPropagation srccontain = null; ErrorModelSubclause srcems = null; if (srcCxt instanceof Subcomponent) { ComponentClassifier cl = ((Subcomponent) srcCxt).getClassifier(); srcems = EMV2Util.getClassifierEMV2Subclause(cl); } else { srcems = EMV2Util.getClassifierEMV2Subclause(cimpl); } srcprop = EMV2Util.findOutgoingErrorPropagation(srcems, src.getName()); srccontain = EMV2Util.findOutgoingErrorContainment(srcems, src.getName()); ConnectionEnd dst = conn.getAllDestination(); Context dstCxt = conn.getAllDestinationContext(); ErrorModelSubclause dstems = null; ErrorPropagation dstprop = null; ErrorPropagation dstcontain = null; if (dstCxt instanceof Subcomponent) { ComponentClassifier cl = ((Subcomponent) dstCxt).getClassifier(); dstems = EMV2Util.getClassifierEMV2Subclause(cl); } else { dstems = EMV2Util.getClassifierEMV2Subclause(cimpl); } dstprop = EMV2Util.findIncomingErrorPropagation(dstems, dst.getName()); dstcontain = EMV2Util.findIncomingErrorContainment(dstems, dst.getName()); if (srcprop != null && dstprop != null) { if (!EM2TypeSetUtil.contains(dstprop.getTypeSet(), srcprop.getTypeSet())) { error(conn, "Outgoing propagation " + EMV2Util.getPrintName(srcprop) + EMV2Util.getPrintName(srcprop.getTypeSet()) + " has error types not handled by incoming propagation " + EMV2Util.getPrintName(dstprop) + EMV2Util.getPrintName(dstprop.getTypeSet())); } } if (srccontain != null && dstcontain != null) { if (!EM2TypeSetUtil.contains(srccontain.getTypeSet(), dstcontain.getTypeSet())) { error(conn, "Outgoing containment " + EMV2Util.getPrintName(srcprop) + EMV2Util.getPrintName(srcprop.getTypeSet()) + " does not contain error types listed by incoming containment " + EMV2Util.getPrintName(dstprop) + EMV2Util.getPrintName(dstprop.getTypeSet())); } } if (srcCxt instanceof Subcomponent && srcprop == null && srccontain == null && dstCxt instanceof Subcomponent && (dstprop != null || dstcontain != null)) { if (srcems != null) { // has an EMV2 subclause but no propagation specification for // the feature warning(conn, "Connection source has no error propagation/containment but target does: " + (dstprop != null ? EMV2Util .getPrintName(dstprop) : EMV2Util .getPrintName(dstcontain))); } else { // TODO check in instance model for connection end point if no // error model subclause info(conn, "Connection source has no error model subclause but target does: " + (dstprop != null ? EMV2Util .getPrintName(dstprop) : EMV2Util .getPrintName(dstcontain)) + ". Please add error model to source or validate against error model of source subcomponents in instance model"); } } if (dstCxt instanceof Subcomponent && dstprop == null && dstCxt instanceof Subcomponent && dstcontain == null && (srcprop != null || srccontain != null)) { if (dstems != null) { // has an EMV2 subclause but no propagation specification for // the feature error(conn, "Connection target has no error propagation/containment but source does: " + (srcprop != null ? EMV2Util .getPrintName(srcprop) : EMV2Util .getPrintName(srccontain))); } else { // TODO check in instance model for connection end point if no // error model subclause error(conn, "Connection target has no error model subclause but source does: " + (srcprop != null ? EMV2Util .getPrintName(srcprop) : EMV2Util .getPrintName(srccontain)) + ". Please add error model to target or validate against error model of target subcomponents in instance model"); } } if (conn.isBidirectional()) { // check for error flow in the opposite direction if (srcems != null) { dstprop = EMV2Util.findIncomingErrorPropagation(srcems, src.getName()); dstcontain = EMV2Util.findIncomingErrorContainment(srcems, src.getName()); } if (dstems != null) { srcprop = EMV2Util.findOutgoingErrorPropagation(dstems, dst.getName()); srccontain = EMV2Util.findOutgoingErrorContainment(dstems, dst.getName()); } if (srcprop != null && dstprop != null) { if (!EM2TypeSetUtil.contains(dstprop.getTypeSet(), srcprop.getTypeSet())) { error(conn, "Outgoing propagation " + EMV2Util.getPrintName(srcprop) + EMV2Util.getPrintName(srcprop .getTypeSet()) + " has error types not handled by incoming propagation " + EMV2Util.getPrintName(dstprop) + EMV2Util.getPrintName(dstprop .getTypeSet())); } } if (srccontain != null && dstcontain != null) { if (!EM2TypeSetUtil.contains(srccontain.getTypeSet(), dstcontain.getTypeSet())) { error(conn, "Outgoing containment " + EMV2Util.getPrintName(srcprop) + EMV2Util.getPrintName(srcprop .getTypeSet()) + " does not contain error types listed by incoming containment " + EMV2Util.getPrintName(dstprop) + EMV2Util.getPrintName(dstprop .getTypeSet())); } } if (srcCxt instanceof Subcomponent && dstCxt instanceof Subcomponent && srcprop == null && srccontain == null && (dstprop != null || dstcontain != null)) { if (dstems != null) { // we are doing opposite direction // has an EMV2 subclause but no propagation specification // for the feature warning(conn, "Connection source has no error propagation/containment but target does: " + (dstprop != null ? EMV2Util .getPrintName(dstprop) : EMV2Util .getPrintName(dstcontain))); } else { // TODO check in instance model for connection end point if // no error model subclause info(conn, "Connection source has no error model subclause but target does: " + (dstprop != null ? EMV2Util .getPrintName(dstprop) : EMV2Util .getPrintName(dstcontain)) + ". Please validate propagations in instance model"); } } if (dstCxt instanceof Subcomponent && dstCxt instanceof Subcomponent && dstprop == null && dstcontain == null && (srcprop != null || srccontain != null)) { if (dstems != null) { // has an EMV2 subclause but no propagation specification // for the feature error(conn, "Connection target has no error propagation/containment but source does: " + (srcprop != null ? EMV2Util .getPrintName(srcprop) : EMV2Util .getPrintName(srccontain))); } else { // TODO check in instance model for connection end point if // no error model subclause error(conn, "Connection target has no error model subclause but source does: " + (srcprop != null ? EMV2Util .getPrintName(srcprop) : EMV2Util .getPrintName(srccontain)) + ". Please validate propagations in instance model"); } } } } }
true
false
null
null
diff --git a/Routy/src/org/routy/DestinationActivity.java b/Routy/src/org/routy/DestinationActivity.java index 5a682f6..e79471a 100644 --- a/Routy/src/org/routy/DestinationActivity.java +++ b/Routy/src/org/routy/DestinationActivity.java @@ -1,616 +1,617 @@ package org.routy; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.UUID; import junit.framework.Assert; import org.routy.fragment.OneButtonDialog; import org.routy.model.AppProperties; import org.routy.model.GooglePlace; import org.routy.model.GooglePlacesQuery; import org.routy.model.Route; import org.routy.model.RouteOptimizePreference; import org.routy.model.RouteRequest; import org.routy.task.CalculateRouteTask; import org.routy.task.GooglePlacesQueryTask; import org.routy.view.DestinationRowView; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.location.Address; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; public class DestinationActivity extends FragmentActivity { private final String TAG = "DestinationActivity"; private final String SAVED_DESTS_JSON_KEY = "saved_destination_json"; private FragmentActivity mContext; private Address origin; private LinearLayout destLayout; private Button addDestButton; private Switch preferenceSwitch; // shared prefs for destination persistence private SharedPreferences destinationActivityPrefs; private SoundPool sounds; private int bad; private int click; private AudioManager audioManager; float volume; RouteOptimizePreference routeOptimized; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM); sounds = new SoundPool(3, AudioManager.STREAM_MUSIC, 0); bad = sounds.load(this, R.raw.routybad, 1); click = sounds.load(this, R.raw.routyclick, 1); setContentView(R.layout.activity_destination); mContext = this; addDestButton = (Button) findViewById(R.id.button_destination_add_new); // Get the layout containing the list of destination destLayout = (LinearLayout) findViewById(R.id.LinearLayout_destinations); routeOptimized = RouteOptimizePreference.PREFER_DISTANCE; preferenceSwitch = (Switch) findViewById(R.id.toggleDistDur); preferenceSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { onToggleClicked(isChecked); } }); // Get the origin address passed from OriginActivity Bundle extras = getIntent().getExtras(); if (extras != null) { origin = (Address) extras.get("origin"); Assert.assertNotNull(origin); Log.v(TAG, "Origin address: " + origin.getExtras().getString("formatted_address")); TextView originText = (TextView) findViewById(R.id.textview_destinations_origin); originText.setText(origin.getExtras().getString("formatted_address")); } // Initialize shared preferences destinationActivityPrefs = getSharedPreferences("destination_prefs", MODE_PRIVATE); String storedAddressesJson = destinationActivityPrefs.getString(SAVED_DESTS_JSON_KEY, null); if (storedAddressesJson != null && storedAddressesJson.length() > 0) { List<Address> restoredAddresses = Util.jsonToAddressList(storedAddressesJson); for (int i = 0; i < restoredAddresses.size(); i++) { Address address = restoredAddresses.get(i); Bundle addressExtras = address.getExtras(); if (addressExtras != null) { int status = addressExtras.getInt("valid_status"); DestinationRowView newRow = null; if (status == DestinationRowView.VALID) { // Put the new row in the list newRow = addDestinationRow(address.getFeatureName()); newRow.setAddress(address); newRow.setValid(); Log.v(TAG, "restored: " + newRow.getAddress().getFeatureName() + " [status=" + newRow.getStatus() + "]"); } else if (status == DestinationRowView.INVALID || status == DestinationRowView.NOT_VALIDATED) { String addressString = addressExtras.getString("address_string"); newRow = addDestinationRow(addressString); if (status == DestinationRowView.INVALID) { newRow.setInvalid(); } else { newRow.clearValidationStatus(); } Log.v(TAG, "restored: " + newRow.getAddressString() + " [status=" + newRow.getStatus() + "]"); } } } } else { addDestinationRow(); } // XXX temp "Test defaults" Button buttonTestDefaults = (Button) findViewById(R.id.button_test_defaults); buttonTestDefaults.setText("Test Default Destinations"); buttonTestDefaults.setOnClickListener(listenerTestDefaults); // TODO: for testing purposes. Remove before prod. showNoobDialog(); // First-time user dialog cookie boolean noobCookie = destinationActivityPrefs.getBoolean("noob_cookie", false); if (!noobCookie){ showNoobDialog(); userAintANoob(); } } /** * Displays an {@link AlertDialog} with one button that dismisses the dialog. Dialog displays helpful first-time info. * * @param message */ private void showNoobDialog() { OneButtonDialog dialog = new OneButtonDialog(getResources().getString(R.string.destination_noob_title), getResources().getString(R.string.destination_noob_instructions)) { @Override public void onButtonClicked(DialogInterface dialog, int which) { dialog.dismiss(); } }; dialog.show(mContext.getSupportFragmentManager(), TAG); } /** * If the user sees the first-time instruction dialog, they won't see it again next time. */ private void userAintANoob() { SharedPreferences.Editor ed = destinationActivityPrefs.edit(); ed.putBoolean("noob_cookie", true); ed.commit(); } /** * Adds a {@link DestinationRowView} to the Destinations list. * @param address * @return the row that was added, or null if no row was added */ DestinationRowView addDestinationRow() { return addDestinationRow(""); } /** * Adds a {@link DestinationRowView} to the Destinations list. * @param address * @return the row that was added, or null if no row was added */ DestinationRowView addDestinationRow(String address) { if (destLayout.getChildCount() < AppProperties.NUM_MAX_DESTINATIONS) { DestinationRowView v = new DestinationRowView(mContext, address) { @Override public void onRemoveClicked(UUID id) { removeDestinationRow(id); } // The user tapped on a different row and this row lost focus @Override public void onFocusLost(final UUID id) { // TODO Do validation and SHOW A LOADING SPINNER while working final DestinationRowView row = getRowById(id); Log.v(TAG, "FOCUS LOST row id=" + row.getUUID() + ": " + row.getAddressString() + " valid status=" + row.getStatus()); // The user tapped on a different text box. Do validation if necessary, but don't add an additional row. if (row.getAddressString() != null && row.getAddressString().length() > 0) { if (row.getStatus() == DestinationRowView.INVALID || row.getStatus() == DestinationRowView.NOT_VALIDATED) { new GooglePlacesQueryTask(mContext) { @Override public void onResult(GooglePlace place) { if (place != null && place.getAddress() != null) { row.setAddress(place.getAddress()); row.setValid(); if ((getRowIndexById(id) == destLayout.getChildCount() - 1) && (destLayout.getChildCount() < AppProperties.NUM_MAX_DESTINATIONS - 1)) { Log.v(TAG, "place validated...showing add button"); showAddButton(); } else { Log.v(TAG, "place validated...hiding add button"); hideAddButton(); } } else { row.setInvalid(); } } @Override public void onNoSelection() { // Doing nothing leaves it NOT_VALIDATED } }.execute(new GooglePlacesQuery(row.getAddressString(), origin.getLatitude(), origin.getLongitude())); } } } }; destLayout.addView(v, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); v.focusOnAddressField(); if (destLayout.getChildCount() == AppProperties.NUM_MAX_DESTINATIONS) { addDestButton.setVisibility(View.INVISIBLE); } return v; } else { volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM); volume = volume / audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM); sounds.play(bad, 1, 1, 1, 0, 1); showErrorDialog("Routy is all maxed out at " + AppProperties.NUM_MAX_DESTINATIONS + " destinations for now."); return null; } } /** * Removes the EditText and "remove" button row ({@link DestinationRowView}} with the given {@link UUID} from the screen. * @param id */ void removeDestinationRow(UUID id) { volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM); volume = volume / audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM); sounds.play(click, volume, volume, 1, 0, 1); int idx = 0; if (destLayout.getChildCount() > 1) { idx = getRowIndexById(id); if (idx >= 0) { Log.v(TAG, "Remove DestinationAddView id=" + id); destLayout.removeViewAt(idx); } else { Log.e(TAG, "attempt to remove a row that does not exist -- id=" + id); } } else if (destLayout.getChildCount() == 1) { idx = getRowIndexById(id); // Should be 0 all the time ((DestinationRowView) destLayout.getChildAt(idx)).reset(); } // set focus on the row idx one less than idx ((DestinationRowView) destLayout.getChildAt(Math.max(0, idx - 1))).focusOnAddressField(); if (destLayout.getChildCount() < AppProperties.NUM_MAX_DESTINATIONS) { addDestButton.setVisibility(View.VISIBLE); } } /** * Called when "Route It!" is clicked. Does any final validation and preparations before calculating * the best route and passing route data to the results activity. * * @param v */ public void acceptDestinations(final View v) { Log.v(TAG, "Validate destinations and calculate route if they're good."); volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM); volume = volume / audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM); sounds.play(click, volume, volume, 1, 0, 1); // Go through the list until you find one that is INVALID or NOT_VALIDATED List<Address> validAddresses = new ArrayList<Address>(); boolean hasDestinations = false; boolean hasError = false; DestinationRowView row = null; for (int i = 0; i < destLayout.getChildCount(); i++) { row = (DestinationRowView) destLayout.getChildAt(i); if (row.getAddressString() != null && row.getAddressString().length() > 0) { if (row.getStatus() == DestinationRowView.INVALID || row.getStatus() == DestinationRowView.NOT_VALIDATED) { + hasDestinations = true; hasError = true; - Log.v(TAG, "row id=" + row.getId() + " has valid status=" + row.getStatus()); + Log.v(TAG, "row id=" + row.getUUID() + " has valid status=" + row.getStatus()); break; } else { hasDestinations = true; validAddresses.add(row.getAddress()); } } } if (hasDestinations) { // If you encountered an "error" take steps to validate it. When it's done validating, call acceptDestinations again. if (hasError && row != null) { Log.v(TAG, "The destinations list has a row (id=" + row.getUUID() + ") in need of validation."); // Validate "row" final DestinationRowView r = row; new GooglePlacesQueryTask(mContext) { @Override public void onResult(GooglePlace place) { if (place != null && place.getAddress() != null) { r.setAddress(place.getAddress()); r.setValid(); acceptDestinations(v); } else { r.setInvalid(); // TODO Show an error message: couldn't match the query string to a place or address } } @Override public void onNoSelection() { // Doing nothing leaves it NOT_VALIDATED } }.execute(new GooglePlacesQuery(row.getAddressString(), origin.getLatitude(), origin.getLongitude())); } else { Log.v(TAG, "All destinations have been validated."); // If everything is valid, move on to the Results screen new CalculateRouteTask(this) { @Override public void onRouteCalculated(Route route) { // Call ResultsActivity activity Intent resultsIntent = new Intent(getBaseContext(), ResultsActivity.class); resultsIntent.putExtra("addresses", route.getAddresses()); resultsIntent.putExtra("distance", route.getTotalDistance()); resultsIntent.putExtra("optimize_for", routeOptimized); startActivity(resultsIntent); } }.execute(new RouteRequest(origin, validAddresses, false, routeOptimized/* ? RouteOptimizePreference.PREFER_DISTANCE : RouteOptimizePreference.PREFER_DURATION*/)); } } else { // No destinations entered volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM); volume = volume / audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM); sounds.play(bad, volume, volume, 1, 0, 1); showErrorDialog("Please enter at least one destination to continue."); } } public void changeOrigin(View v) { finish(); } public void onAddDestinationClicked(View v) { Log.v(TAG, "new destination row requested by user"); volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM); volume = volume / audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM); sounds.play(click, volume, volume, 1, 0, 1); // If the last row is not empty, add a new row DestinationRowView lastRow = (DestinationRowView) destLayout.getChildAt(destLayout.getChildCount() - 1); if (lastRow.getAddressString() != null && lastRow.getAddressString().length() > 0) { if (lastRow.needsValidation()) { // Validate the last row if it has not been validated. Otherwise, it puts the new row up first, and then validates due to focusChanged. Log.v(TAG, "validating last row before adding new one"); final DestinationRowView r = lastRow; // disable the onFocusLost listener just once so it doesn't try to validate twice here r.disableOnFocusLostCallback(true); // do the validation new GooglePlacesQueryTask(mContext) { @Override public void onResult(GooglePlace place) { if (place != null && place.getAddress() != null) { r.setAddress(place.getAddress()); r.setValid(); Log.v(TAG, "adding a new destination row"); addDestinationRow(); } else { r.setInvalid(); } // If the list is full, hide the add button if (destLayout.getChildCount() == AppProperties.NUM_MAX_DESTINATIONS) { addDestButton.setVisibility(View.INVISIBLE); } } @Override public void onNoSelection() { // Doing nothing leaves it NOT_VALIDATED } }.execute(new GooglePlacesQuery(lastRow.getAddressString(), origin.getLatitude(), origin.getLongitude())); } else { Log.v(TAG, "adding a new destination row"); addDestinationRow(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_destination, menu); return true; } /** * In the case that a user presses back to change an origin, or any other reason why they leave the destination screen, * we save their entered destinations to shared prefs so they don't have to re-enter the destinations again */ @Override public void onPause(){ super.onPause(); if(sounds != null) { sounds.release(); sounds = null; } Log.v(TAG, "building the JSON string from all the destination addresses"); List<Address> addressesToSave = new ArrayList<Address>(); for (int i = 0; i < destLayout.getChildCount(); i++) { DestinationRowView destView = (DestinationRowView) destLayout.getChildAt(i); if (destView.getAddressString() != null && destView.getAddressString().length() > 0) { Address address = null; if (destView.getStatus() == DestinationRowView.VALID) { // Add the address from this row to the list address = destView.getAddress(); // It's valid so we'll just keep track of that Bundle extras = address.getExtras(); extras.putInt("valid_status", destView.getStatus()); } else if (destView.getStatus() == DestinationRowView.INVALID || destView.getStatus() == DestinationRowView.NOT_VALIDATED) { // Manually create an Address object with just the EditText value and the status because it won't be there address = new Address(Locale.getDefault()); // Since it'll need to be validated when we come back, we need to save what was in the EditText with the status Bundle extras = address.getExtras(); extras.putString("address_string", destView.getAddressString()); extras.putInt("valid_status", destView.getStatus()); } else { // bah! throw new IllegalStateException("Destination row " + i + " had an invalid status value of: " + destView.getStatus()); } Assert.assertNotNull(address); addressesToSave.add(address); } } String json = Util.addressListToJSON(addressesToSave); Log.v(TAG, "saved destinations json: " + json); // Put the storedAddresses into shared prefs via a set of strings Log.v(TAG, "Saving destinations in shared prefs"); SharedPreferences.Editor ed = destinationActivityPrefs.edit(); ed.putString(SAVED_DESTS_JSON_KEY, json); // ed.putStringSet("saved_destination_strings", storedAddresses); ed.commit(); } /** * Displays an {@link AlertDialog} with one button that dismisses the dialog. Use this to display error messages * to the user. * * @param message */ private void showErrorDialog(String message) { OneButtonDialog dialog = new OneButtonDialog(getResources().getString(R.string.error_message_title), message) { @Override public void onButtonClicked(DialogInterface dialog, int which) { dialog.dismiss(); } }; dialog.show(mContext.getSupportFragmentManager(), TAG); } private int getRowIndexById(UUID id) { for (int i = 0; i < destLayout.getChildCount(); i++) { if (((DestinationRowView) destLayout.getChildAt(i)).getUUID().equals(id)) { return i; } } return -1; } private DestinationRowView getRowById(UUID id) { int idx = getRowIndexById(id); return (DestinationRowView) destLayout.getChildAt(idx); } @Override protected void onResume() { super.onResume(); sounds = new SoundPool(3, AudioManager.STREAM_MUSIC, 0); bad = sounds.load(this, R.raw.routybad, 1); click = sounds.load(this, R.raw.routyclick, 1); } public void onToggleClicked(boolean on) { Log.v(TAG, "route optimize preference changed!"); if (on) { routeOptimized = RouteOptimizePreference.PREFER_DURATION; } else { routeOptimized = RouteOptimizePreference.PREFER_DISTANCE; } } public void showAddButton() { addDestButton.setVisibility(View.VISIBLE); } public void hideAddButton() { addDestButton.setVisibility(View.INVISIBLE); } // XXX temp /** * Loads the 3 test destinations we've been using. */ View.OnClickListener listenerTestDefaults = new View.OnClickListener() { @Override public void onClick(View v) { volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM); volume = volume / audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM); sounds.play(click, volume, volume, 1, 0, 1); if (destLayout.getChildCount() < 3) { for (int i = destLayout.getChildCount(); i < 3; i++) { addDestinationRow(); } } DestinationRowView view = (DestinationRowView) destLayout.getChildAt(0); ((EditText) view.findViewById(R.id.edittext_destination_add)).setText(getResources().getString(R.string.test_destination_1)); view = (DestinationRowView) destLayout.getChildAt(1); ((EditText) view.findViewById(R.id.edittext_destination_add)).setText(getResources().getString(R.string.test_destination_2)); view = (DestinationRowView) destLayout.getChildAt(2); ((EditText) view.findViewById(R.id.edittext_destination_add)).setText(getResources().getString(R.string.test_destination_3)); } }; } diff --git a/Routy/src/org/routy/view/DestinationRowView.java b/Routy/src/org/routy/view/DestinationRowView.java index 72ec91c..d15d645 100644 --- a/Routy/src/org/routy/view/DestinationRowView.java +++ b/Routy/src/org/routy/view/DestinationRowView.java @@ -1,222 +1,223 @@ package org.routy.view; import java.util.UUID; import org.routy.R; import android.content.Context; import android.location.Address; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; public abstract class DestinationRowView extends LinearLayout { private final String TAG = "DestinationRowView"; public static final int VALID = 0; public static final int INVALID = 1; public static final int NOT_VALIDATED = 2; private UUID id; private int status; private String addressString; private Address address; private EditText editText; // private Button addButton; private Button removeButton; private boolean ignoreOnFocusLostCallback; private boolean ignoreOnFocusLostCallbackTemp; /** * Called when the "remove" button is clicked for a DestinationAddView * @param id the {@link UUID} of the DestinationAddView to remove */ public abstract void onRemoveClicked(UUID id); // public abstract void onAddClicked(UUID id); public abstract void onFocusLost(UUID id); public DestinationRowView(Context context) { this(context, ""); } public DestinationRowView(Context context, AttributeSet attrs) { super(context, attrs); this.id = UUID.randomUUID(); this.addressString = ""; this.address = null; this.status = DestinationRowView.NOT_VALIDATED; this.ignoreOnFocusLostCallback = false; initViews(context); } public DestinationRowView(Context context, String addressString) { super(context); this.id = UUID.randomUUID(); this.addressString = addressString; this.address = null; this.status = DestinationRowView.NOT_VALIDATED; this.ignoreOnFocusLostCallback = false; initViews(context); } public DestinationRowView(Context context, Address address) { super(context); this.id = UUID.randomUUID(); this.address = address; this.status = DestinationRowView.VALID; this.addressString = address.getFeatureName(); this.ignoreOnFocusLostCallback = false; initViews(context); } private void initViews(Context context) { // Inflate the view for an "add destination" text field and remove button LayoutInflater inflater = LayoutInflater.from(context); inflater.inflate(R.layout.view_destination_row, this); editText = (EditText) findViewById(R.id.edittext_destination_add); editText.setText(addressString); editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Changing the text in this row should throw out any previous validation clearValidationStatus(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // this space intentionally left blank } @Override public void afterTextChanged(Editable s) { // this space intentionally left blank } }); editText.setOnFocusChangeListener(new OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { Log.v(TAG, "onFocusChange (lost focus) from row with id=" + id); if (!ignoreOnFocusLostCallback) { onFocusLost(id); } else { if (ignoreOnFocusLostCallbackTemp) { ignoreOnFocusLostCallback = false; } } } } }); removeButton = (Button) findViewById(R.id.button_destination_remove); removeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.v(TAG, "onRemoveClicked from row with id=" + id); onRemoveClicked(id); } }); } public UUID getUUID() { return this.id; } public void setInvalid() { editText.setTextColor(getResources().getColor(R.color.Red)); status = DestinationRowView.INVALID; } public void setValid() { editText.setTextColor(getResources().getColor(R.color.White)); status = DestinationRowView.VALID; } public void clearValidationStatus() { + Log.v(TAG, "clearing validation status"); editText.setTextColor(getResources().getColor(R.color.White)); status = DestinationRowView.NOT_VALIDATED; } /** * Resets this destination row. Re-enables the add button, clears the text field, * and resets the validation status. */ public void reset() { editText.setText(""); status = DestinationRowView.NOT_VALIDATED; } public String getAddressString() { return editText.getText().toString(); } public int getStatus() { return status; } public void setAddress(Address address) { this.address = address; String formattedAddress = this.address.getExtras().getString("formatted_address"); editText.setText(address.getFeatureName() + " - " + formattedAddress); } public Address getAddress() { return this.address; } public void focusOnAddressField() { editText.requestFocus(); } /** * Tell this row to ignore the onFocusLost callback. * * @param temporary true will restore normal behavior after onFocusLost is called once, * false will leave it off until manually turned back on */ public void disableOnFocusLostCallback(boolean temporary) { ignoreOnFocusLostCallback = true; ignoreOnFocusLostCallbackTemp = temporary; } public void enableOnFocusLostCallback() { ignoreOnFocusLostCallback = false; } public boolean needsValidation() { return getStatus() == DestinationRowView.INVALID || getStatus() == DestinationRowView.NOT_VALIDATED; } }
false
false
null
null
diff --git a/src/main/java/org/swfparser/operation/DefineFunctionOperation.java b/src/main/java/org/swfparser/operation/DefineFunctionOperation.java index a4e3fa0..4812c04 100755 --- a/src/main/java/org/swfparser/operation/DefineFunctionOperation.java +++ b/src/main/java/org/swfparser/operation/DefineFunctionOperation.java @@ -1,105 +1,113 @@ /* * DefineFunctionOperation.java * @Author Oleg Gorobets * Created: Jul 29, 2007 * CVS-ID: $Id: *************************************************************************/ package org.swfparser.operation; +import java.util.ArrayList; import java.util.List; import java.util.Stack; +import com.jswiff.swfrecords.RegisterParam; import org.springframework.util.StringUtils; import org.apache.log4j.Logger; import org.swfparser.CodeUtil; import org.swfparser.ExecutionContext; import org.swfparser.Operation; import org.swfparser.PatternAnalyzerEx; import org.swfparser.annotations.NewAnalyzer; import org.swfparser.exception.StatementBlockException; import com.jswiff.swfrecords.actions.Action; import com.jswiff.swfrecords.actions.DefineFunction; @NewAnalyzer public class DefineFunctionOperation extends AbstractCompoundOperation { private static Logger logger = Logger.getLogger(DefineFunctionOperation.class); private List<Operation> operations; private DefineFunction defineFunction; public DefineFunctionOperation(Stack<Operation> stack, ExecutionContext context, DefineFunction defineFunction) throws StatementBlockException { super(context); this.defineFunction = defineFunction; String functionName = defineFunction.getName(); logger.debug(functionName+"()"); logger.debug("params = "+defineFunction.getParameters().length); logger.debug("code size = "+defineFunction.getCode()); List<Action> actions = defineFunction.getBody().getActions(); // Saving context before calling function context.getOperationStack().push(this); // save execution stack & branch analyzer before calling function Stack<Operation> executionStack = context.getExecStack(); // PatternAnalyzer patternAnalyzer = context.getPatternAnalyzer(); PatternAnalyzerEx patternAnalyzer = context.getPatternAnalyzerEx(); // create new execution stack and branch analyzer context.setExecStack( createEmptyExecutionStack() ); // context.setPatternAnalyzer(null); context.setPatternAnalyzerEx(null); statementBlock.setExecutionContext(context); statementBlock.read(actions); operations = statementBlock.getOperations(); // restore execution stack context.setExecStack(executionStack); // restore branch analyzer // context.setPatternAnalyzer(patternAnalyzer); context.setPatternAnalyzerEx(patternAnalyzer); context.getOperationStack().pop(); } public String getStringValue(int level) { StringBuffer buf = new StringBuffer(); if (StringUtils.hasText(defineFunction.getName())) { buf .append(CodeUtil.getIndent(level)) .append("function ") .append(defineFunction.getName()); } else { buf // .append(CodeUtil.getIndent(level)) .append("function"); } - - buf - .append("()") - .append(" {\n"); - + + List<String> params = new ArrayList<>(); + for (String param: defineFunction.getParameters()) { + params.add(param); + } + + buf.append("("); + buf.append(org.apache.commons.lang.StringUtils.join(params, ",")); + buf.append(")") + .append("{\n"); + for (Operation op : operations) { buf.append(op.getStringValue(level+1)+CodeUtil.endOfStatement(op)+"\n"); } buf.append(CodeUtil.getIndent(level)); buf.append("}"); return buf.toString(); } @Override public String toString() { return "DefineFunction("+defineFunction.getName()+")"; } }
false
false
null
null
diff --git a/src/org/parboiled/asm/LabelApplicator.java b/src/org/parboiled/asm/LabelApplicator.java index a53d5d49..4b2ea6cc 100644 --- a/src/org/parboiled/asm/LabelApplicator.java +++ b/src/org/parboiled/asm/LabelApplicator.java @@ -1,74 +1,81 @@ /* * Copyright (C) 2009-2010 Mathias Doenitz * * 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.parboiled.asm; import org.jetbrains.annotations.NotNull; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.*; import org.parboiled.common.Preconditions; import org.parboiled.common.StringUtils; import static org.parboiled.common.Utils.merge; class LabelApplicator implements ClassTransformer, Opcodes, Types { private final ClassTransformer nextTransformer; public LabelApplicator(ClassTransformer nextTransformer) { this.nextTransformer = nextTransformer; } @SuppressWarnings("unchecked") public ParserClassNode transform(@NotNull ParserClassNode classNode) throws Exception { for (ParserMethod method : merge(classNode.ruleMethods, classNode.labelMethods)) { createLabellingCode(method); } return nextTransformer != null ? nextTransformer.transform(classNode) : classNode; } @SuppressWarnings({"unchecked"}) private void createLabellingCode(ParserMethod method) { InsnList instructions = method.instructions; AbstractInsnNode current = instructions.getFirst(); while (current.getOpcode() != ARETURN) { current = current.getNext(); } // stack: <rule> + instructions.insertBefore(current, new InsnNode(DUP)); + // stack: <rule> :: <rule> + LabelNode isNullLabel = new LabelNode(); + instructions.insertBefore(current, new JumpInsnNode(IFNULL, isNullLabel)); + // stack: <rule> instructions.insertBefore(current, new LdcInsnNode(getLabelText(method))); // stack: <rule> :: <labelText> instructions.insertBefore(current, new MethodInsnNode(INVOKEINTERFACE, RULE_TYPE.getInternalName(), "label", "(Ljava/lang/String;)" + RULE_TYPE.getDescriptor())); // stack: <rule> + instructions.insertBefore(current, isNullLabel); + // stack: <rule> } public String getLabelText(ParserMethod method) { if (method.visibleAnnotations != null) { for (Object annotationObj : method.visibleAnnotations) { AnnotationNode annotation = (AnnotationNode) annotationObj; if (annotation.desc.equals(LABEL_TYPE.getDescriptor()) && annotation.values != null) { Preconditions.checkState("value".equals(annotation.values.get(0))); String labelValue = (String) annotation.values.get(1); return StringUtils.isEmpty(labelValue) ? method.name : labelValue; } } } return method.name; } } \ No newline at end of file diff --git a/src/org/parboiled/asm/LeafApplicator.java b/src/org/parboiled/asm/LeafApplicator.java index 918d5038..540af2a4 100644 --- a/src/org/parboiled/asm/LeafApplicator.java +++ b/src/org/parboiled/asm/LeafApplicator.java @@ -1,71 +1,75 @@ /* * Copyright (C) 2009-2010 Mathias Doenitz * * 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.parboiled.asm; import org.jetbrains.annotations.NotNull; import org.objectweb.asm.Opcodes; -import org.objectweb.asm.tree.AbstractInsnNode; -import org.objectweb.asm.tree.AnnotationNode; -import org.objectweb.asm.tree.InsnList; -import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.*; import org.parboiled.common.Preconditions; class LeafApplicator implements ClassTransformer, Opcodes, Types { private final ClassTransformer nextTransformer; public LeafApplicator(ClassTransformer nextTransformer) { this.nextTransformer = nextTransformer; } public ParserClassNode transform(@NotNull ParserClassNode classNode) throws Exception { for (ParserMethod method : classNode.leafMethods) { createLeafMarkingCode(method); } return nextTransformer != null ? nextTransformer.transform(classNode) : classNode; } @SuppressWarnings({"unchecked"}) private void createLeafMarkingCode(ParserMethod method) { InsnList instructions = method.instructions; AbstractInsnNode current = instructions.getFirst(); while (current.getOpcode() != ARETURN) { current = current.getNext(); } // stack: <rule> + instructions.insertBefore(current, new InsnNode(DUP)); + // stack: <rule> :: <rule> + LabelNode isNullLabel = new LabelNode(); + instructions.insertBefore(current, new JumpInsnNode(IFNULL, isNullLabel)); + // stack: <rule> instructions.insertBefore(current, new MethodInsnNode(INVOKEINTERFACE, RULE_TYPE.getInternalName(), "asLeaf", "()" + RULE_TYPE.getDescriptor())); // stack: <rule> + instructions.insertBefore(current, isNullLabel); + // stack: <rule> } public String getLabelText(ParserMethod method) { if (method.visibleAnnotations != null) { for (Object annotationObj : method.visibleAnnotations) { AnnotationNode annotation = (AnnotationNode) annotationObj; if (annotation.desc.equals(LABEL_TYPE.getDescriptor()) && annotation.values != null) { Preconditions.checkState("label".equals(annotation.values.get(0))); return (String) annotation.values.get(1); } } } return method.name; } } \ No newline at end of file diff --git a/test/org/parboiled/asm/ClassNodeInializerAndMethodCategorizerTest.java b/test/org/parboiled/asm/ClassNodeInializerAndMethodCategorizerTest.java index fc48388d..4758ac78 100644 --- a/test/org/parboiled/asm/ClassNodeInializerAndMethodCategorizerTest.java +++ b/test/org/parboiled/asm/ClassNodeInializerAndMethodCategorizerTest.java @@ -1,57 +1,57 @@ /* * Copyright (C) 2009 Mathias Doenitz * * 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.parboiled.asm; import static org.parboiled.test.TestUtils.assertEqualsMultiline; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; import java.util.List; public class ClassNodeInializerAndMethodCategorizerTest { @Test public void testClassNodeSetup() throws Exception { ParserClassNode classNode = new ParserClassNode(TestParser.class); new ClassNodeInitializer( new MethodCategorizer(null) ).transform(classNode); assertEquals(classNode.name, "org/parboiled/asm/TestParser$$parboiled"); assertEquals(classNode.superName, "org/parboiled/asm/TestParser"); assertEqualsMultiline(join(classNode.constructors), "<init>"); assertEqualsMultiline(join(classNode.ruleMethods), "noActionRule,simpleActionRule,upSetActionRule,booleanExpressionActionRule,complexActionsRule,any,empty"); assertEqualsMultiline(join(classNode.cachedMethods), - "ch,charIgnoreCase,charRange,charSet,string,stringIgnoreCase,firstOf,oneOrMore,optional,sequence,enforcedSequence,test,testNot,zeroOrMore"); + "ch,charIgnoreCase,charRange,charSet,string,stringIgnoreCase,firstOf,oneOrMore,optional,sequence,test,testNot,zeroOrMore"); assertEqualsMultiline(join(classNode.labelMethods), - ""); + "skipCharAndRetry,insertCharAndRetry,resynchronize,defaultRecovery"); assertEqualsMultiline(join(classNode.leafMethods), "charSet,string,stringIgnoreCase"); } private String join(List<ParserMethod> methods) { StringBuilder sb = new StringBuilder(); for (ParserMethod method : methods) { if (sb.length() > 0) sb.append(','); sb.append(method.name); } return sb.toString(); } }
false
false
null
null
diff --git a/library/src/com/nostra13/universalimageloader/core/DisplayImageOptions.java b/library/src/com/nostra13/universalimageloader/core/DisplayImageOptions.java index f83e077..6b6654a 100644 --- a/library/src/com/nostra13/universalimageloader/core/DisplayImageOptions.java +++ b/library/src/com/nostra13/universalimageloader/core/DisplayImageOptions.java @@ -1,483 +1,483 @@ /******************************************************************************* * Copyright 2011-2013 Sergey Tarasevich * * 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.nostra13.universalimageloader.core; import android.graphics.Bitmap; import android.graphics.BitmapFactory.Options; import android.os.Handler; import android.widget.ImageView; import com.nostra13.universalimageloader.core.assist.ImageLoadingListener; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.display.BitmapDisplayer; import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer; import com.nostra13.universalimageloader.core.download.ImageDownloader; import com.nostra13.universalimageloader.core.process.BitmapProcessor; /** * Contains options for image display. Defines: * <ul> * <li>whether stub image will be displayed in {@link android.widget.ImageView ImageView} during image loading</li> * <li>whether stub image will be displayed in {@link android.widget.ImageView ImageView} if empty URI is passed</li> * <li>whether stub image will be displayed in {@link android.widget.ImageView ImageView} if image loading fails</li> * <li>whether {@link android.widget.ImageView ImageView} should be reset before image loading start</li> * <li>whether loaded image will be cached in memory</li> * <li>whether loaded image will be cached on disc</li> * <li>image scale type</li> * <li>decoding options (including bitmap decoding configuration)</li> * <li>delay before loading of image</li> * <li>auxiliary object which will be passed to {@link ImageDownloader#getStream(String, Object) ImageDownloader}</li> * <li>pre-processor for image Bitmap (before caching in memory)</li> * <li>post-processor for image Bitmap (after caching in memory, before displaying)</li> * <li>how decoded {@link Bitmap} will be displayed</li> * </ul> * <p/> * You can create instance: * <ul> * <li>with {@link Builder}:<br /> * <b>i.e.</b> : * <code>new {@link DisplayImageOptions}.{@link Builder#Builder() Builder()}.{@link Builder#cacheInMemory() cacheInMemory()}. - * {@link Builder#showStubImage(int) showStubImage()}.{@link Builder#build() build()}</code><br /> + * {@link Builder#showImageOnLoading(int)} showImageOnLoading()}.{@link Builder#build() build()}</code><br /> * </li> * <li>or by static method: {@link #createSimple()}</li> <br /> * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) * @since 1.0.0 */ public final class DisplayImageOptions { private final int imageResOnLoading; private final int imageResForEmptyUri; private final int imageResOnFail; private final Bitmap bitmapOnLoading; private final Bitmap bitmapForEmptyUri; private final Bitmap bitmapOnFail; private final boolean resetViewBeforeLoading; private final boolean cacheInMemory; private final boolean cacheOnDisc; private final ImageScaleType imageScaleType; private final Options decodingOptions; private final int delayBeforeLoading; private final Object extraForDownloader; private final BitmapProcessor preProcessor; private final BitmapProcessor postProcessor; private final BitmapDisplayer displayer; private final Handler handler; private DisplayImageOptions(Builder builder) { imageResOnLoading = builder.imageResOnLoading; imageResForEmptyUri = builder.imageResForEmptyUri; imageResOnFail = builder.imageResOnFail; bitmapOnLoading = builder.bitmapOnLoading; bitmapForEmptyUri = builder.bitmapForEmptyUri; bitmapOnFail = builder.bitmapOnFail; resetViewBeforeLoading = builder.resetViewBeforeLoading; cacheInMemory = builder.cacheInMemory; cacheOnDisc = builder.cacheOnDisc; imageScaleType = builder.imageScaleType; decodingOptions = builder.decodingOptions; delayBeforeLoading = builder.delayBeforeLoading; extraForDownloader = builder.extraForDownloader; preProcessor = builder.preProcessor; postProcessor = builder.postProcessor; displayer = builder.displayer; handler = builder.handler; } public boolean shouldShowImageResOnLoading() { return imageResOnLoading != 0; } public boolean shouldShowBitmapOnLoading() { return bitmapOnLoading != null; } public boolean shouldShowImageResForEmptyUri() { return imageResForEmptyUri != 0; } public boolean shouldShowBitmapForEmptyUri() { return bitmapForEmptyUri != null; } public boolean shouldShowImageResOnFail() { return imageResOnFail != 0; } public boolean shouldShowBitmapOnFail() { return bitmapOnFail != null; } public boolean shouldPreProcess() { return preProcessor != null; } public boolean shouldPostProcess() { return postProcessor != null; } public boolean shouldDelayBeforeLoading() { return delayBeforeLoading > 0; } public int getImageResOnLoading() { return imageResOnLoading; } public Bitmap getBitmapOnLoading() { return bitmapOnLoading; } public int getImageResForEmptyUri() { return imageResForEmptyUri; } public Bitmap getBitmapForEmptyUri() { return bitmapForEmptyUri; } public int getImageResOnFail() { return imageResOnFail; } public Bitmap getBitmapOnFail() { return bitmapOnFail; } public boolean isResetViewBeforeLoading() { return resetViewBeforeLoading; } public boolean isCacheInMemory() { return cacheInMemory; } public boolean isCacheOnDisc() { return cacheOnDisc; } public ImageScaleType getImageScaleType() { return imageScaleType; } public Options getDecodingOptions() { return decodingOptions; } public int getDelayBeforeLoading() { return delayBeforeLoading; } public Object getExtraForDownloader() { return extraForDownloader; } public BitmapProcessor getPreProcessor() { return preProcessor; } public BitmapProcessor getPostProcessor() { return postProcessor; } public BitmapDisplayer getDisplayer() { return displayer; } public Handler getHandler() { return (handler == null ? new Handler() : handler); } /** * Builder for {@link DisplayImageOptions} * * @author Sergey Tarasevich (nostra13[at]gmail[dot]com) */ public static class Builder { private int imageResOnLoading = 0; private int imageResForEmptyUri = 0; private int imageResOnFail = 0; private Bitmap bitmapOnLoading = null; private Bitmap bitmapForEmptyUri = null; private Bitmap bitmapOnFail = null; private boolean resetViewBeforeLoading = false; private boolean cacheInMemory = false; private boolean cacheOnDisc = false; private ImageScaleType imageScaleType = ImageScaleType.IN_SAMPLE_POWER_OF_2; private Options decodingOptions = new Options(); private int delayBeforeLoading = 0; private Object extraForDownloader = null; private BitmapProcessor preProcessor = null; private BitmapProcessor postProcessor = null; private BitmapDisplayer displayer = DefaultConfigurationFactory.createBitmapDisplayer(); private Handler handler = null; public Builder() { decodingOptions.inPurgeable = true; decodingOptions.inInputShareable = true; } /** * Stub image will be displayed in {@link android.widget.ImageView ImageView} during image loading * * @param imageRes Stub image resource * @deprecated Use {@link #showImageOnLoading(int)} instead */ @Deprecated public Builder showStubImage(int imageRes) { imageResOnLoading = imageRes; return this; } /** * Incoming image will be displayed in {@link android.widget.ImageView ImageView} during image loading * * @param imageRes Image resource */ public Builder showImageOnLoading(int imageRes) { imageResOnLoading = imageRes; return this; } /** * Incoming image will be displayed in {@link android.widget.ImageView ImageView} during image loading. * This option will be ignored if {@link DisplayImageOptions.Builder#showImageOnLoading(int)} is set. * * @param bitmap Image bitmap */ public Builder showImageOnLoading(Bitmap bitmap) { bitmapOnLoading = bitmap; return this; } /** * Incoming image will be displayed in {@link android.widget.ImageView ImageView} if empty URI (null or empty * string) will be passed to <b>ImageLoader.displayImage(...)</b> method. * * @param imageRes Image resource */ public Builder showImageForEmptyUri(int imageRes) { imageResForEmptyUri = imageRes; return this; } /** * Incoming image will be displayed in {@link android.widget.ImageView ImageView} if empty URI (null or empty * string) will be passed to <b>ImageLoader.displayImage(...)</b> method. * This option will be ignored if {@link DisplayImageOptions.Builder#showImageForEmptyUri(int)} is set. * * @param bitmap Image bitmap */ public Builder showImageForEmptyUri(Bitmap bitmap) { bitmapForEmptyUri = bitmap; return this; } /** * Incoming image will be displayed in {@link android.widget.ImageView ImageView} if some error occurs during * requested image loading/decoding. * * @param imageRes Image resource */ public Builder showImageOnFail(int imageRes) { imageResOnFail = imageRes; return this; } /** * Incoming image will be displayed in {@link android.widget.ImageView ImageView} if some error occurs during * requested image loading/decoding. * This option will be ignored if {@link DisplayImageOptions.Builder#showImageOnFail(int)} is set. * * @param bitmap Image bitmap */ public Builder showImageOnFail(Bitmap bitmap) { bitmapOnFail = bitmap; return this; } /** * {@link android.widget.ImageView ImageView} will be reset (set <b>null</b>) before image loading start * * @deprecated Use {@link #resetViewBeforeLoading(boolean) resetViewBeforeLoading(true)} instead */ public Builder resetViewBeforeLoading() { resetViewBeforeLoading = true; return this; } /** Sets whether {@link android.widget.ImageView ImageView} will be reset (set <b>null</b>) before image loading start */ public Builder resetViewBeforeLoading(boolean resetViewBeforeLoading) { this.resetViewBeforeLoading = resetViewBeforeLoading; return this; } /** * Loaded image will be cached in memory * * @deprecated Use {@link #cacheInMemory(boolean) cacheInMemory(true)} instead */ public Builder cacheInMemory() { cacheInMemory = true; return this; } /** Sets whether loaded image will be cached in memory */ public Builder cacheInMemory(boolean cacheInMemory) { this.cacheInMemory = cacheInMemory; return this; } /** * Loaded image will be cached on disc * * @deprecated Use {@link #cacheOnDisc(boolean) cacheOnDisc(true)} instead */ public Builder cacheOnDisc() { cacheOnDisc = true; return this; } /** Sets whether loaded image will be cached on disc */ public Builder cacheOnDisc(boolean cacheOnDisc) { this.cacheOnDisc = cacheOnDisc; return this; } /** * Sets {@linkplain ImageScaleType scale type} for decoding image. This parameter is used while define scale * size for decoding image to Bitmap. Default value - {@link ImageScaleType#IN_SAMPLE_POWER_OF_2} */ public Builder imageScaleType(ImageScaleType imageScaleType) { this.imageScaleType = imageScaleType; return this; } /** Sets {@link Bitmap.Config bitmap config} for image decoding. Default value - {@link Bitmap.Config#ARGB_8888} */ public Builder bitmapConfig(Bitmap.Config bitmapConfig) { if (bitmapConfig == null) throw new IllegalArgumentException("bitmapConfig can't be null"); decodingOptions.inPreferredConfig = bitmapConfig; return this; } /** * Sets options for image decoding.<br /> * <b>NOTE:</b> {@link Options#inSampleSize} of incoming options will <b>NOT</b> be considered. Library * calculate the most appropriate sample size itself according yo {@link #imageScaleType(ImageScaleType)} * options.<br /> * <b>NOTE:</b> This option overlaps {@link #bitmapConfig(android.graphics.Bitmap.Config) bitmapConfig()} * option. */ public Builder decodingOptions(Options decodingOptions) { if (decodingOptions == null) throw new IllegalArgumentException("decodingOptions can't be null"); this.decodingOptions = decodingOptions; return this; } /** Sets delay time before starting loading task. Default - no delay. */ public Builder delayBeforeLoading(int delayInMillis) { this.delayBeforeLoading = delayInMillis; return this; } /** Sets auxiliary object which will be passed to {@link ImageDownloader#getStream(String, Object)} */ public Builder extraForDownloader(Object extra) { this.extraForDownloader = extra; return this; } /** * Sets bitmap processor which will be process bitmaps before they will be cached in memory. So memory cache * will contain bitmap processed by incoming preProcessor.<br /> * Image will be pre-processed even if caching in memory is disabled. */ public Builder preProcessor(BitmapProcessor preProcessor) { this.preProcessor = preProcessor; return this; } /** * Sets bitmap processor which will be process bitmaps before they will be displayed in {@link ImageView} but * after they'll have been saved in memory cache. */ public Builder postProcessor(BitmapProcessor postProcessor) { this.postProcessor = postProcessor; return this; } /** * Sets custom {@link BitmapDisplayer displayer} for image loading task. Default value - * {@link DefaultConfigurationFactory#createBitmapDisplayer()} */ public Builder displayer(BitmapDisplayer displayer) { if (displayer == null) throw new IllegalArgumentException("displayer can't be null"); this.displayer = displayer; return this; } /** * Sets custom {@linkplain Handler handler} for displaying images and firing {@linkplain ImageLoadingListener * listener} events. */ public Builder handler(Handler handler) { this.handler = handler; return this; } /** Sets all options equal to incoming options */ public Builder cloneFrom(DisplayImageOptions options) { imageResOnLoading = options.imageResOnLoading; imageResForEmptyUri = options.imageResForEmptyUri; imageResOnFail = options.imageResOnFail; bitmapOnLoading = options.bitmapOnLoading; bitmapForEmptyUri = options.bitmapForEmptyUri; bitmapOnFail = options.bitmapOnFail; resetViewBeforeLoading = options.resetViewBeforeLoading; cacheInMemory = options.cacheInMemory; cacheOnDisc = options.cacheOnDisc; imageScaleType = options.imageScaleType; decodingOptions = options.decodingOptions; delayBeforeLoading = options.delayBeforeLoading; extraForDownloader = options.extraForDownloader; preProcessor = options.preProcessor; postProcessor = options.postProcessor; displayer = options.displayer; handler = options.handler; return this; } /** Builds configured {@link DisplayImageOptions} object */ public DisplayImageOptions build() { return new DisplayImageOptions(this); } } /** * Creates options appropriate for single displaying: * <ul> * <li>View will <b>not</b> be reset before loading</li> * <li>Loaded image will <b>not</b> be cached in memory</li> * <li>Loaded image will <b>not</b> be cached on disc</li> * <li>{@link ImageScaleType#IN_SAMPLE_POWER_OF_2} decoding type will be used</li> * <li>{@link Bitmap.Config#ARGB_8888} bitmap config will be used for image decoding</li> * <li>{@link SimpleBitmapDisplayer} will be used for image displaying</li> * </ul> * <p/> * These option are appropriate for simple single-use image (from drawables or from Internet) displaying. */ public static DisplayImageOptions createSimple() { return new Builder().build(); } }
true
false
null
null