answer
stringlengths
17
10.2M
package com.huetoyou.chatexchange; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.huetoyou.chatexchange.auth.AuthenticatorActivity; public class MainActivity extends AppCompatActivity { private SharedPreferences mSharedPrefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSharedPrefs = getSharedPreferences(getResources().getText(R.string.app_name).toString(), MODE_PRIVATE); startActivity(new Intent(this, AuthenticatorActivity.class)); } }
package com.test.smartnotes.database; import android.content.ContentValues; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.SQLException; import android.content.Context; import android.database.Cursor; import android.util.Log; import com.test.smartnotes.database.NotesDbSchema.NotesTable; import java.util.ArrayList; import java.util.List; public class DBAdapter { /** if debug is set true then it will show all Logcat message **/ public static final boolean DEBUG = true; /** Logcat TAG **/ public static final String LOG_TAG = "DBAdapter"; /** Database Version **/ private static final int DATABASE_VERSION = 1; /** Database Name **/ private static final String DATABASE_NAME = "SmartNotes.db"; /** Used to open database in synchronized way **/ private static DataBaseHelper DBHelper = null; public static void init(Context context) { if (DBHelper == null) { if (DEBUG) Log.i("DBAdapter", context.toString()); DBHelper = new DataBaseHelper(context); } } /** Create notes table **/ private static final String NOTES_CREATE = "CREATE TABLE" + NotesTable.NAME + "(" + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " + NotesTable.Cols.NOTE_TITLE + " TEXT, " + NotesTable.Cols.NOTE_TEXT + " TEXT, " + NotesTable.Cols.IMPORTANCE + " INTEGER, " + NotesTable.Cols.IMAGE_PATH + " TEXT, " + NotesTable.Cols.LATITUDE + " REAL, " + NotesTable.Cols.LONGITUDE + " REAL);"; /** Main Database creation INNER class **/ private static class DataBaseHelper extends SQLiteOpenHelper { public DataBaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { if (DEBUG) Log.i(LOG_TAG, "notes table create"); try { db.execSQL(NOTES_CREATE); } catch (Exception exception) { if (DEBUG) Log.i(LOG_TAG, "Exception onCreate() exception"); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } /** Open database for insert, update, delete in synchronized manner **/ private static synchronized SQLiteDatabase open() throws SQLException { return DBHelper.getWritableDatabase(); } /** Escape string for single quotes (insert, update) **/ private static String sqlEscapeString(String aString) { String aReturn = ""; if (null != aString) { //aReturn = aString.replace("'", "''"); aReturn = DatabaseUtils.sqlEscapeString(aString); // Remove the enclosing single quotes ... aReturn = aReturn.substring(1, aReturn.length() - 1); } return aReturn; } /** UnEscape string for single quotes (show data) **/ private static String sqlUnEscapeString(String aString) { String aReturn = ""; if (null != aString) { aReturn = aString.replace("''", "'"); } return aReturn; } // CRUD Operations /** Add a new Note **/ public static void addNoteData(NoteData noteData) { final SQLiteDatabase db = open(); String noteTitle = sqlEscapeString(noteData.getNoteTitle()); String noteText = sqlEscapeString(noteData.getNoteText()); int importance = noteData.getImportance(); String imagePath = noteData.getImagePath(); double latitude = noteData.getLatitude(); double longitude = noteData.getLongitude(); ContentValues noteValues = new ContentValues(); noteValues.put(NotesTable.Cols.NOTE_TITLE, noteTitle); noteValues.put(NotesTable.Cols.NOTE_TEXT, noteText); noteValues.put(NotesTable.Cols.IMPORTANCE, importance); noteValues.put(NotesTable.Cols.IMAGE_PATH, imagePath); noteValues.put(NotesTable.Cols.LATITUDE, latitude); noteValues.put(NotesTable.Cols.LONGITUDE, longitude); db.insert(NotesTable.NAME, null, noteValues); db.close(); } /** Get a Note **/ public static NoteData getNoteData(int id) { final SQLiteDatabase db = open(); Cursor cursor = db.query(NotesTable.NAME, new String[] { NotesTable.Cols.ID, NotesTable.Cols.NOTE_TITLE, NotesTable.Cols.NOTE_TEXT, NotesTable.Cols.IMPORTANCE, NotesTable.Cols.IMAGE_PATH, NotesTable.Cols.LATITUDE, NotesTable.Cols.LONGITUDE }, NotesTable.Cols.ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); } return new NoteData( Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), Integer.parseInt(cursor.getString(3)), cursor.getString(4), Double.parseDouble(cursor.getString(5)), Double.parseDouble(cursor.getString(6)) ); } /** Get All Notes **/ public static List<NoteData> getAllUserData() { List<NoteData> notesList = new ArrayList<>(); String selectQuery = "SELECT * FROM " + NotesTable.NAME; final SQLiteDatabase db = open(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { NoteData data = new NoteData(); data.setID(Integer.parseInt(cursor.getString(0))); data.setNoteTitle(cursor.getString(1)); data.setNoteText(cursor.getString(2)); data.setImportance(Integer.parseInt(cursor.getString(3))); data.setImagePath(cursor.getString(4)); data.setLatitude(Double.parseDouble(cursor.getString(5))); data.setLongitude(Double.parseDouble(cursor.getString(6))); notesList.add(data); } while (cursor.moveToNext()); } cursor.close(); return notesList; } /** Update a Note **/ public static int updateNoteData(NoteData data) { final SQLiteDatabase db = open(); ContentValues noteValues = new ContentValues(); noteValues.put(NotesTable.Cols.NOTE_TITLE, data.getNoteTitle()); noteValues.put(NotesTable.Cols.NOTE_TEXT, data.getNoteText()); noteValues.put(NotesTable.Cols.IMPORTANCE, data.getImportance()); noteValues.put(NotesTable.Cols.IMAGE_PATH, data.getImagePath()); noteValues.put(NotesTable.Cols.LATITUDE, data.getLatitude()); noteValues.put(NotesTable.Cols.LONGITUDE, data.getLongitude()); return db.update(NotesTable.NAME, noteValues, NotesTable.Cols.ID + " = ?", new String[] { String.valueOf(data.getID()) }); } /** Delete a Note **/ public static void deleteUserData(NoteData data) { final SQLiteDatabase db = open(); db.delete(NotesTable.NAME, NotesTable.Cols.ID + " = ?", new String[] { String.valueOf(data.getID()) }); db.close(); } }
package com.sendgrid; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; public class MailTest { @Test public void testHelloWorld() throws IOException { Email from = new Email("test@example.com"); String subject = "Sending with SendGrid is Fun"; Email to = new Email("test@example.com"); Content content = new Content("text/plain", "and easy to do anywhere, even with Java"); Mail mail = new Mail(from, subject, to, content); Assert.assertEquals(mail.build(), "{\"from\":{\"email\":\"test@example.com\"},\"subject\":\"Sending with SendGrid is Fun\",\"personalizations\":[{\"to\":[{\"email\":\"test@example.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"and easy to do anywhere, even with Java\"}]}"); } @Test public void testKitchenSink() throws IOException { Mail mail = new Mail(); Email fromEmail = new Email(); fromEmail.setName("Example User"); fromEmail.setEmail("test@example.com"); mail.setFrom(fromEmail); mail.setSubject("Hello World from the SendGrid Java Library"); Personalization personalization = new Personalization(); Email to = new Email(); to.setName("Example User"); to.setEmail("test@example.com"); personalization.addTo(to); to.setName("Example User"); to.setEmail("test@example.com"); personalization.addTo(to); Email cc = new Email(); cc.setName("Example User"); cc.setEmail("test@example.com"); personalization.addCc(cc); cc.setName("Example User"); cc.setEmail("test@example.com"); personalization.addCc(cc); Email bcc = new Email(); bcc.setName("Example User"); bcc.setEmail("test@example.com"); personalization.addBcc(bcc); bcc.setName("Example User"); bcc.setEmail("test@example.com"); personalization.addBcc(bcc); personalization.setSubject("Hello World from the Personalized SendGrid Java Library"); personalization.addHeader("X-Test", "test"); personalization.addHeader("X-Mock", "true"); personalization.addSubstitution("%name%", "Example User"); personalization.addSubstitution("%city%", "Denver"); personalization.addCustomArg("user_id", "343"); personalization.addCustomArg("type", "marketing"); personalization.setSendAt(1443636843); mail.addPersonalization(personalization); Personalization personalization2 = new Personalization(); Email to2 = new Email(); to2.setName("Example User"); to2.setEmail("test@example.com"); personalization2.addTo(to2); to2.setName("Example User"); to2.setEmail("test@example.com"); personalization2.addTo(to2); Email cc2 = new Email(); cc2.setName("Example User"); cc2.setEmail("test@example.com"); personalization2.addCc(cc2); cc2.setName("Example User"); cc2.setEmail("test@example.com"); personalization2.addCc(cc2); Email bcc2 = new Email(); bcc2.setName("Example User"); bcc2.setEmail("test@example.com"); personalization2.addBcc(bcc2); bcc2.setName("Example User"); bcc2.setEmail("test@example.com"); personalization2.addBcc(bcc2); personalization2.setSubject("Hello World from the Personalized SendGrid Java Library"); personalization2.addHeader("X-Test", "test"); personalization2.addHeader("X-Mock", "true"); personalization2.addSubstitution("%name%", "Example User"); personalization2.addSubstitution("%city%", "Denver"); personalization2.addCustomArg("user_id", "343"); personalization2.addCustomArg("type", "marketing"); personalization2.setSendAt(1443636843); mail.addPersonalization(personalization2); Personalization personalization3 = new Personalization(); Email to3 = new Email(); to3.setName("Example User"); to3.setEmail("test@example.com"); personalization3.addTo(to3); to3.setName("Example User"); to3.setEmail("test@example.com"); personalization3.addTo(to3); Email cc3 = new Email(); cc3.setName("Example User"); cc3.setEmail("test@example.com"); personalization3.addCc(cc3); cc3.setName("Example User"); cc3.setEmail("test@example.com"); personalization3.addCc(cc3); Email bcc3 = new Email(); bcc3.setName("Example User"); bcc3.setEmail("test@example.com"); personalization3.addBcc(bcc3); bcc3.setName("Example User"); bcc3.setEmail("test@example.com"); personalization3.addBcc(bcc3); personalization3.setSubject("Hello World from the Personalized SendGrid Java Library"); personalization3.addHeader("X-Test", "test"); personalization3.addHeader("X-Mock", "true"); personalization3.addDynamicTemplateData("name", "Example User"); personalization3.addDynamicTemplateData("city", "Denver"); personalization3.addCustomArg("user_id", "343"); personalization3.addCustomArg("type", "marketing"); personalization3.setSendAt(1443636843); mail.addPersonalization(personalization3); Content content = new Content(); content.setType("text/plain"); content.setValue("some text here"); mail.addContent(content); content.setType("text/html"); content.setValue("<html><body>some text here</body></html>"); mail.addContent(content); Attachments attachments = new Attachments(); attachments.setContent("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12"); attachments.setType("application/pdf"); attachments.setFilename("balance_001.pdf"); attachments.setDisposition("attachment"); attachments.setContentId("Balance Sheet"); mail.addAttachments(attachments); Attachments attachments2 = new Attachments(); attachments2.setContent("BwdW"); attachments2.setType("image/png"); attachments2.setFilename("banner.png"); attachments2.setDisposition("inline"); attachments2.setContentId("Banner"); mail.addAttachments(attachments2); mail.setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932"); mail.addSection("%section1%", "Substitution Text for Section 1"); mail.addSection("%section2%", "Substitution Text for Section 2"); mail.addHeader("X-Test1", "1"); mail.addHeader("X-Test2", "2"); mail.addCategory("May"); mail.addCategory("2016"); mail.addCustomArg("campaign", "welcome"); mail.addCustomArg("weekday", "morning"); mail.setSendAt(1443636842); ASM asm = new ASM(); asm.setGroupId(99); asm.setGroupsToDisplay(new int[] {4,5,6,7,8}); mail.setASM(asm); // mail.setBatchId("sendgrid_batch_id"); mail.setIpPoolId("23"); MailSettings mailSettings = new MailSettings(); BccSettings bccSettings = new BccSettings(); bccSettings.setEnable(true); bccSettings.setEmail("test@example.com"); mailSettings.setBccSettings(bccSettings); Setting sandBoxMode = new Setting(); sandBoxMode.setEnable(true); mailSettings.setSandboxMode(sandBoxMode); Setting bypassListManagement = new Setting(); bypassListManagement.setEnable(true); mailSettings.setBypassListManagement(bypassListManagement); FooterSetting footerSetting = new FooterSetting(); footerSetting.setEnable(true); footerSetting.setText("Footer Text"); footerSetting.setHtml("<html><body>Footer Text</body></html>"); mailSettings.setFooterSetting(footerSetting); SpamCheckSetting spamCheckSetting = new SpamCheckSetting(); spamCheckSetting.setEnable(true); spamCheckSetting.setSpamThreshold(1); spamCheckSetting.setPostToUrl("https://spamcatcher.sendgrid.com"); mailSettings.setSpamCheckSetting(spamCheckSetting); mail.setMailSettings(mailSettings); TrackingSettings trackingSettings = new TrackingSettings(); ClickTrackingSetting clickTrackingSetting = new ClickTrackingSetting(); clickTrackingSetting.setEnable(true); clickTrackingSetting.setEnableText(false); trackingSettings.setClickTrackingSetting(clickTrackingSetting); OpenTrackingSetting openTrackingSetting = new OpenTrackingSetting(); openTrackingSetting.setEnable(true); openTrackingSetting.setSubstitutionTag("Optional tag to replace with the open image in the body of the message"); trackingSettings.setOpenTrackingSetting(openTrackingSetting); SubscriptionTrackingSetting subscriptionTrackingSetting = new SubscriptionTrackingSetting(); subscriptionTrackingSetting.setEnable(true); subscriptionTrackingSetting.setText("text to insert into the text/plain portion of the message"); subscriptionTrackingSetting.setHtml("<html><body>html to insert into the text/html portion of the message</body></html>"); subscriptionTrackingSetting.setSubstitutionTag("Optional tag to replace with the open image in the body of the message"); trackingSettings.setSubscriptionTrackingSetting(subscriptionTrackingSetting); GoogleAnalyticsSetting googleAnalyticsSetting = new GoogleAnalyticsSetting(); googleAnalyticsSetting.setEnable(true); googleAnalyticsSetting.setCampaignSource("some source"); googleAnalyticsSetting.setCampaignTerm("some term"); googleAnalyticsSetting.setCampaignContent("some content"); googleAnalyticsSetting.setCampaignName("some name"); googleAnalyticsSetting.setCampaignMedium("some medium"); trackingSettings.setGoogleAnalyticsSetting(googleAnalyticsSetting); mail.setTrackingSettings(trackingSettings); Email replyTo = new Email(); replyTo.setName("Example User"); replyTo.setEmail("test@example.com"); mail.setReplyTo(replyTo); Assert.assertEquals(mail.build(), "{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Hello World from the SendGrid Java Library\",\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"cc\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"bcc\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"subject\":\"Hello World from the Personalized SendGrid Java Library\",\"headers\":{\"X-Mock\":\"true\",\"X-Test\":\"test\"},\"substitutions\":{\"%city%\":\"Denver\",\"%name%\":\"Example User\"},\"custom_args\":{\"type\":\"marketing\",\"user_id\":\"343\"},\"send_at\":1443636843},{\"to\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"cc\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"bcc\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"subject\":\"Hello World from the Personalized SendGrid Java Library\",\"headers\":{\"X-Mock\":\"true\",\"X-Test\":\"test\"},\"substitutions\":{\"%city%\":\"Denver\",\"%name%\":\"Example User\"},\"custom_args\":{\"type\":\"marketing\",\"user_id\":\"343\"},\"send_at\":1443636843},{\"to\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"cc\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"bcc\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"},{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"subject\":\"Hello World from the Personalized SendGrid Java Library\",\"headers\":{\"X-Mock\":\"true\",\"X-Test\":\"test\"},\"custom_args\":{\"type\":\"marketing\",\"user_id\":\"343\"},\"dynamic_template_data\":{\"city\":\"Denver\",\"name\":\"Example User\"},\"send_at\":1443636843}],\"content\":[{\"type\":\"text/plain\",\"value\":\"some text here\"},{\"type\":\"text/html\",\"value\":\"<html><body>some text here</body></html>\"}],\"attachments\":[{\"content\":\"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12\",\"type\":\"application/pdf\",\"filename\":\"balance_001.pdf\",\"disposition\":\"attachment\",\"content_id\":\"Balance Sheet\"},{\"content\":\"BwdW\",\"type\":\"image/png\",\"filename\":\"banner.png\",\"disposition\":\"inline\",\"content_id\":\"Banner\"}],\"template_id\":\"13b8f94f-bcae-4ec6-b752-70d6cb59f932\",\"sections\":{\"%section1%\":\"Substitution Text for Section 1\",\"%section2%\":\"Substitution Text for Section 2\"},\"headers\":{\"X-Test1\":\"1\",\"X-Test2\":\"2\"},\"categories\":[\"May\",\"2016\"],\"custom_args\":{\"campaign\":\"welcome\",\"weekday\":\"morning\"},\"send_at\":1443636842,\"asm\":{\"group_id\":99,\"groups_to_display\":[4,5,6,7,8]},\"ip_pool_name\":\"23\",\"mail_settings\":{\"bcc\":{\"enable\":true,\"email\":\"test@example.com\"},\"bypass_list_management\":{\"enable\":true},\"footer\":{\"enable\":true,\"text\":\"Footer Text\",\"html\":\"<html><body>Footer Text</body></html>\"},\"sandbox_mode\":{\"enable\":true},\"spam_check\":{\"enable\":true,\"threshold\":1,\"post_to_url\":\"https://spamcatcher.sendgrid.com\"}},\"tracking_settings\":{\"click_tracking\":{\"enable\":true,\"enable_text\":false},\"open_tracking\":{\"enable\":true,\"substitution_tag\":\"Optional tag to replace with the open image in the body of the message\"},\"subscription_tracking\":{\"enable\":true,\"text\":\"text to insert into the text/plain portion of the message\",\"html\":\"<html><body>html to insert into the text/html portion of the message</body></html>\",\"substitution_tag\":\"Optional tag to replace with the open image in the body of the message\"},\"ganalytics\":{\"enable\":true,\"utm_source\":\"some source\",\"utm_term\":\"some term\",\"utm_content\":\"some content\",\"utm_campaign\":\"some name\",\"utm_medium\":\"some medium\"}},\"reply_to\":{\"name\":\"Example User\",\"email\":\"test@example.com\"}}"); } @Test public void fromShouldReturnCorrectFrom() { Mail mail = new Mail(); Email from = new Email(); mail.setFrom(from); Assert.assertSame(from, mail.getFrom()); } @Test public void mailDeserialization() throws IOException { Email to = new Email("foo@bar.com"); Content content = new Content("text/plain", "test"); Email from = new Email("no-reply@bar.com"); Mail mail = new Mail(from, "subject", to, content); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(mail); Mail deserialized = mapper.readValue(json, Mail.class); Assert.assertEquals(deserialized, mail); } }
package com.wt.pinger.fragment; import android.annotation.SuppressLint; import android.content.ActivityNotFoundException; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; 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.text.method.TextKeyListener; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Toast; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.ContentViewEvent; import com.hivedi.console.Console; import com.hivedi.era.ERA; import com.squareup.otto.Subscribe; import com.wt.pinger.BuildConfig; import com.wt.pinger.R; import com.wt.pinger.R2; import com.wt.pinger.proto.SimpleQueryHandler; import com.wt.pinger.providers.CmdContentProvider; import com.wt.pinger.providers.DbContentProvider; import com.wt.pinger.service.CmdService; import com.wt.pinger.utils.BusProvider; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class ConsoleFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { @BindView(R2.id.cmd_edit) EditText edit; @BindView(R2.id.cmd_list) ListView list; @BindView(R2.id.cmd_placeholder) LinearLayout placeholder; @BindView(R2.id.cmdBtn) ImageView cmdBtn; private interface OnSelectCommand{ void onResult(Cursor cursor); } private static class SelectCommandItems { private ContentResolver mContentResolver; private OnSelectCommand mOnSelectCommand; SelectCommandItems(Context cr) { mContentResolver = cr.getContentResolver(); } SelectCommandItems callback(OnSelectCommand c) { mOnSelectCommand = c; return this; } SelectCommandItems execute() { new AsyncQueryHandler(mContentResolver){ @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { if (mOnSelectCommand != null) { mOnSelectCommand.onResult(cursor); } else { cursor.close(); } } }.startQuery(0, null, DbContentProvider.URI_CONTENT_COMMANDS, null, null, null, null); return this; } } @OnClick(R2.id.cmdSelectBtn) void cmdSelectBtnClick(View v) { new SelectCommandItems(getActivity()).callback(new OnSelectCommand() { @Override public void onResult(Cursor cursor) { final ArrayList<Long> commandsIdList = new ArrayList<>(); CharSequence[] commands = new CharSequence[]{}; if (cursor != null) { if (cursor.moveToFirst()) { commands = new CharSequence[cursor.getCount()]; int col1 = cursor.getColumnIndex(DbContentProvider.Commands.FIELD_COMMAND_TEXT); int col2 = cursor.getColumnIndex(DbContentProvider.Commands.FIELD_COMMAND_ID); int counter = 0; do { commands[counter] = cursor.getString(col1); commandsIdList.add(cursor.getLong(col2)); counter++; } while (cursor.moveToNext()); } cursor.close(); } if (!isAdded()) { // skip show dialog window, activity is gone // query may take long time - activity may be closed return; } new MaterialDialog.Builder(getActivity()) .title(R.string.label_list_of_commands) .items(commands) .autoDismiss(false) .itemsCallback(new MaterialDialog.ListCallback() { @Override public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) { dialog.dismiss(); edit.setText(text); } }) .itemsLongCallback(new MaterialDialog.ListLongCallback() { @Override public boolean onLongSelection(final MaterialDialog dialog, View itemView, final int position, CharSequence text) { if (isAdded()) { String posString; try { posString = Long.toString(commandsIdList.get(position)); } catch (Exception e) { posString = "0"; } new AsyncQueryHandler(getActivity().getContentResolver()){ @Override protected void onDeleteComplete(int token, Object cookie, int result) { try { commandsIdList.remove(position); } catch (Exception e) { // ignore } if (isAdded() && dialog.isShowing()) { new SelectCommandItems(getActivity()).callback(new OnSelectCommand(){ @Override public void onResult(Cursor cursor) { CharSequence[] cc = new CharSequence[]{}; if (cursor.moveToFirst()) { int counter = 0; int col1 = cursor.getColumnIndex(DbContentProvider.Commands.FIELD_COMMAND_TEXT); cc = new CharSequence[cursor.getCount()]; do { cc[counter] = cursor.getString(col1); counter++; } while (cursor.moveToNext()); } cursor.close(); if (isAdded() && dialog.isShowing()) { dialog.setItems(cc); Toast.makeText(getActivity(), R.string.toast_command_deleted, Toast.LENGTH_SHORT).show(); } } }).execute(); } } }.startDelete(0, null, DbContentProvider.URI_CONTENT_COMMANDS, DbContentProvider.Commands.FIELD_COMMAND_ID + "=?", new String[]{posString}); } return true; } }) .neutralText(R.string.label_restore_defaults) .onNeutral(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull final MaterialDialog dialog, @NonNull DialogAction which) { new AsyncQueryHandler(getActivity().getContentResolver()){ @Override protected void onInsertComplete(int token, Object cookie, Uri uri) { if (isAdded() && dialog.isShowing()) { dialog.setItems(DbContentProvider.DEFAULT_COMMAND_LIST); commandsIdList.clear(); new SelectCommandItems(getActivity()).callback(new OnSelectCommand(){ @Override public void onResult(Cursor cursor) { if (cursor.moveToFirst()) { int col1 = cursor.getColumnIndex(DbContentProvider.Commands.FIELD_COMMAND_ID); do { commandsIdList.add(cursor.getLong(col1)); } while (cursor.moveToNext()); } cursor.close(); } }).execute(); } } }.startInsert(0, null, DbContentProvider.URI_CONTENT_COMMANDS_RESET, null); } }) .positiveText(R.string.label_close) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { dialog.dismiss(); } }) .build() .show(); } }).execute(); } @OnClick(R2.id.cmdAddBtn) void cmdAddBtnClick(View v) { String text = edit.getText().toString(); if (text.length() > 0) { final Context ctx = getActivity().getApplicationContext(); ContentValues values = new ContentValues(); values.put(DbContentProvider.Commands.FIELD_COMMAND_TEXT, text); new AsyncQueryHandler(ctx.getContentResolver()) { @Override protected void onInsertComplete(int token, Object cookie, Uri uri) { Toast.makeText(ctx, R.string.toast_command_added, Toast.LENGTH_SHORT).show(); } }.startInsert(0, null, DbContentProvider.URI_CONTENT_COMMANDS, values); } } private SimpleCursorAdapter adapter; public ConsoleFragment() {} @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View res = inflater.inflate(R.layout.fragment_console, container, false); ButterKnife.bind(this, res); adapter = new SimpleCursorAdapter(getActivity(), R.layout.item_cmd, null, new String[]{"data"}, new int[]{R.id.cmd_item}, 0); list.setAdapter(adapter); cmdBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { list.setSelectionAfterHeaderView(); cmdBtn.setImageResource(R.drawable.ic_clear_black_24dp); CmdService.executeCmd(getActivity(), edit.getText().toString()); } }); edit.setText(""); TextKeyListener.clear(edit.getText()); return res; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); menu.add(R.string.label_share).setIcon(R.drawable.ic_share_white_24dp).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { if (getActivity() != null) { // <- fox NPE on getActivity() SimpleQueryHandler qh = new SimpleQueryHandler(getActivity().getContentResolver(), new SimpleQueryHandler.QueryListener() { @SuppressLint("StaticFieldLeak") @Override public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (cursor != null) { new AsyncTask<Cursor, Void, String>() { @Override protected String doInBackground(Cursor... params) { StringBuilder sb = new StringBuilder(); Cursor cursor = params[0]; final int maxShareSize = 250 * 1024; if (cursor.moveToFirst()) { do { sb.append(cursor.getString(cursor.getColumnIndex("data"))); sb.append("\n"); int len = sb.length(); if (len > maxShareSize) { // trim sb.setLength(maxShareSize); ERA.log("Share length trim from " + len); ERA.logException(new Exception("Share length trim from " + len)); break; } } while (cursor.moveToNext()); } cursor.close(); return sb.toString(); } @Override protected void onPostExecute(String s) { if (s.length() > 0) { try { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, s); sendIntent.setType("text/plain"); startActivity(sendIntent); } catch (ActivityNotFoundException e) { ERA.logException(e); } } else { if (getActivity() != null) { Toast.makeText(getActivity(), R.string.toast_no_data_to_share, Toast.LENGTH_LONG).show(); } } } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, cursor); } else { if (getActivity() != null) { Toast.makeText(getActivity(), R.string.toast_no_data_to_share, Toast.LENGTH_LONG).show(); } } } }); qh.startQuery(0, null, CmdContentProvider.URI_CONTENT, null, null, null, null); } return false; } }).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getLoaderManager().initLoader(1, null, this); } @Override public void onResume() { super.onResume(); Answers.getInstance().logContentView( new ContentViewEvent() .putContentId("console-fragment") .putContentName("Console Fragment") .putContentType("fragment") ); BusProvider.getInstance().register(this); CmdService.checkService(getActivity()); } @Override public void onPause() { BusProvider.getInstance().unregister(this); super.onPause(); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(getActivity(), CmdContentProvider.URI_CONTENT, null, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { adapter.swapCursor(data); placeholder.setVisibility(data != null && data.getCount() > 0 ? View.GONE : View.VISIBLE); } @Override public void onLoaderReset(Loader<Cursor> loader) { adapter.swapCursor(null); } @Subscribe @SuppressWarnings("unused") public void serviceMessages(CmdService.CmdServiceMessage msg) { if (BuildConfig.DEBUG) { Console.logi("serviceMessages " + msg.type + ", data=" + msg.data); } switch(msg.type) { case CmdService.CMD_MSG_CHECK: boolean isWorking = msg.getDataAsBool(false); cmdBtn.setImageResource(!isWorking ? R.drawable.ic_send_black_24dp : R.drawable.ic_clear_black_24dp); break; } } }
package org.jaxen.expr; import org.jaxen.Context; import org.jaxen.JaxenException; import org.jaxen.Navigator; import org.jaxen.function.BooleanFunction; class DefaultAndExpr extends DefaultLogicalExpr implements LogicalExpr { public DefaultAndExpr(Expr lhs, Expr rhs) { super( lhs, rhs ); } public String getOperator() { return "and"; } public String toString() { return "[(DefaultAndExpr): " + getLHS() + ", " + getRHS() + "]"; } public Object evaluate(Context context) throws JaxenException { Navigator nav = context.getNavigator(); Boolean lhsValue = BooleanFunction.evaluate( getLHS().evaluate( context ), nav ); if ( !lhsValue.booleanValue() ) { return Boolean.FALSE; } // Short circuits are required in XPath. "The right operand is not // evaluated if the left operand evaluates to false." Boolean rhsValue = BooleanFunction.evaluate( getRHS().evaluate( context ), nav ); if ( !rhsValue.booleanValue() ) { return Boolean.FALSE; } return Boolean.TRUE; } public void accept(Visitor visitor) { visitor.visit(this); } }
package com.tfl.api.test; import com.frameworkium.core.api.tests.BaseTest; import com.tfl.api.dto.carparkoccupancy.CarParkOccupancies; import com.tfl.api.dto.carparkoccupancy.CarParkOccupancy; import com.tfl.api.service.carparks.CarParkOccupancyService; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static com.google.common.truth.Truth.assertThat; @Test public class CarParksTest extends BaseTest { private CarParkOccupancies carParkOccupancies; /** * Make the service call only once using {@link BeforeClass} to speed up * tests while allowing fine grain tests. */ @BeforeClass public void setUp() { carParkOccupancies = new CarParkOccupancyService().getCarParkOccupancies(); } public void all_car_park_occupancies_more_than_10_spaces() { assertThat(carParkOccupancies.getTotalNumFree()) .isGreaterThan(10); } public void all_car_park_occupancies_contains_ruislip() { assertThat(carParkOccupancies.getNames()) .contains("Ruislip Gardens Stn (LUL)"); } public void single_car_park_request_information_the_same() { // N.B. this test might fail if the number of free/used bays changes // between the first and subsequent service call // this is due to using a live service and not controlling test data CarParkOccupancy randomCPO = carParkOccupancies.getRandom(); // Get said CPO via ID CarParkOccupancy specificCPO = new CarParkOccupancyService() .getCarParkOccupancyByID(randomCPO.id); // Make sure they are the same ignoring the details of the bays assertThat(specificCPO.equalsIgnoringBays(randomCPO)).isTrue(); } public void single_car_park_has_sane_number_of_free_spaces() { String randomCPOID = carParkOccupancies.getRandom().id; // Get said CP via ID int freeSpaces = new CarParkOccupancyService() .getCarParkOccupancyByID(randomCPOID) .getNumFreeSpaces(); // Make sure things are sane assertThat(freeSpaces).isAtLeast(0); assertThat(freeSpaces).isLessThan(10000); } @Test public void free_and_occupied_equals_total() { assertThat(carParkOccupancies.getTotalNumSpaces()) .isEqualTo(carParkOccupancies.getTotalNumFreeAndOccupied()); } }
package de.danoeh.antennapod; import android.os.Build; import android.util.Log; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import de.danoeh.antennapod.core.preferences.UserPreferences; public class CrashReportWriter implements Thread.UncaughtExceptionHandler { private static final String TAG = "CrashReportWriter"; private final Thread.UncaughtExceptionHandler defaultHandler; public CrashReportWriter() { defaultHandler = Thread.getDefaultUncaughtExceptionHandler(); } public static File getFile() { return new File(UserPreferences.getDataFolder(null), "crash-report.log"); } @Override public void uncaughtException(Thread thread, Throwable ex) { File path = getFile(); PrintWriter out = null; try { out = new PrintWriter(new FileWriter(path)); out.println("## Crash info"); out.println("Time: " + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date())); out.println("AntennaPod version: " + BuildConfig.VERSION_NAME); out.println(); out.println("## StackTrace"); out.println("```"); ex.printStackTrace(out); out.println("```"); } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); } finally { IOUtils.closeQuietly(out); } defaultHandler.uncaughtException(thread, ex); } public static String getSystemInfo() { return "## Environment" + "\nAndroid version: " + Build.VERSION.RELEASE + "\nOS version: " + System.getProperty("os.version") + "\nAntennaPod version: " + BuildConfig.VERSION_NAME + "\nModel: " + Build.MODEL + "\nDevice: " + Build.DEVICE + "\nProduct: " + Build.PRODUCT; } }
package gam.org.com.leidianzhanji.play; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.util.Log; import android.view.KeyEvent; import gam.org.com.leidianzhanji.R; public class DayGift { public static int day = 0; public static int id = 0; GameDraw gameDraw; Bitmap im, zi; Bitmap di1, di2, di3; Bitmap an1; int mode, t; int alp, av; public DayGift(GameDraw _mc) { gameDraw = _mc; } public void init(Resources res) { im = BitmapFactory.decodeResource(res, R.drawable.mr_im); zi = BitmapFactory.decodeResource(res, R.drawable.mr_zi1); di1 = BitmapFactory.decodeResource(res, R.drawable.mr_di1); di2 = BitmapFactory.decodeResource(res, R.drawable.mr_di2); di3 = BitmapFactory.decodeResource(res, R.drawable.mr_di3); an1 = BitmapFactory.decodeResource(res, R.drawable.mr_an1); } public void free() { im = null; zi = null; di1 = null; di2 = null; di3 = null; an1 = null; } public void reset() { mode = 0; t = 0; alp = 100; av = 15; gameDraw.canvasIndex = GameDraw.CANVAS_DAY_GIFT; } public void render(Canvas g, Paint paint) { gameDraw.menu.render(g, paint); switch (mode) { case 0: case 21: g.drawColor(((t * 30) << 24) | 0xffffff); break; case 1: case 20: g.drawColor(((100) << 24) | 0xffffff); renderJM(g, t * 25 + 5, paint); break; case 2: g.drawColor(((100) << 24) | 0xffffff); renderJM(g, 255, paint); break; } } public void renderJM(Canvas g, int a, Paint paint) { paint.setAlpha(a); g.drawBitmap(im, 660, 73, paint); Tools.paintMImage(g, im, 960, 73, paint); Tools.paintM2Image(g, im, 660, 531, paint); Tools.paintRotateImage(g, im, 960, 531, 180, 302, 458, paint); for (int i = 0; i < 8; i++) { if (i < id) { g.drawBitmap(di2, 724, 300 + 65 * i, paint); } else if (i == id) { g.drawBitmap(di3, 724, 300 + 65 * i, paint); paint.setAlpha(a * alp / 100); g.drawBitmap(di1, 724, 300 + 65 * i, paint); paint.setAlpha(a); } else { g.drawBitmap(di3, 724, 300 + 65 * i, paint); } } g.drawBitmap(zi, 748, 116, paint); g.drawBitmap(an1, 863, 837, paint); paint.setAlpha(255); } public void upData() { alp += av; if (alp >= 100) { alp = 100; av = -Math.abs(av); } else if (alp <= 30) { alp = 30; av = Math.abs(av); } switch (mode) { case 0: t++; if (t >= 3) { t = 0; mode = 1; } else if (t == 2) { init(gameDraw.res); } break; case 1: t++; if (t >= 10) { t = 0; mode = 2; } break; case 20: t if (t <= 0) { t = 3; mode = 21; } break; case 21: t if (t <= 0) { t = 0; gameDraw.canvasIndex = GameDraw.CANVAS_MENU; Data.load(); } else if (t == 1) { free(); } break; } } public void getGift(int id) { switch (id) { case 0: Game.mnuey += 500; gameDraw.getGift.reset(0, 8); break; case 1: Game.bisha++; Data.bh++; gameDraw.getGift.reset(1, 8); break; case 2: Game.mnuey += 1000; gameDraw.getGift.reset(2, 8); break; case 3: Game.bisha++; Game.baseLife = 4; gameDraw.getGift.reset(3, 8); break; case 4: Game.mnuey += 1500; gameDraw.getGift.reset(4, 8); break; case 5: Game.mnuey += 2000; gameDraw.getGift.reset(5, 8); break; case 6: Game.bisha++; Game.baseLife = 4; Data.bh++; gameDraw.getGift.reset(6, 8); break; case 7: getGift(Math.abs(GameDraw.random.nextInt() % 7)); break; } } public void touchDown(float tx, float ty) { switch (mode) { case 2: if (tx > 883 && tx < 883 + 153 && ty > 700 && ty < 700 + 78) { GameDraw.gameSound(1); mode = 20; t = 10; getGift(id); } break; } } public void chack() { int d = (int) (System.currentTimeMillis() / (1000 * 60 * 60 * 24)); if (d == day + 1) { if (id < 7) { id++; } reset(); } else if (d > day + 1) { id = 0; reset(); } day = d; Data.save(); } public void keyDown(int k) { switch (k) { case KeyEvent.KEYCODE_DPAD_UP: Log.e("jamie", ""); break; case KeyEvent.KEYCODE_DPAD_DOWN: Log.e("jamie", ""); break; case KeyEvent.KEYCODE_DPAD_LEFT: Log.e("jamie", ""); break; case KeyEvent.KEYCODE_DPAD_RIGHT: Log.e("jamie", ""); break; case KeyEvent.KEYCODE_ENTER: Log.e("jamie", ""); switch (mode) { case 2: GameDraw.gameSound(1); mode = 20; t = 10; getGift(id); break; } break; case KeyEvent.KEYCODE_BACK: Log.e("jamie", ""); switch (mode) { case 2: GameDraw.gameSound(1); mode = 20; t = 10; getGift(id); break; } break; case KeyEvent.KEYCODE_HOME: Log.e("jamie", ""); break; case KeyEvent.KEYCODE_MENU: Log.e("jamie", ""); break; } } }
package org.apache.commons.lang; import java.lang.reflect.Array; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * <p>Operations on arrays, primitive arrays (like <code>int[]</code>) and * primitive wrapper arrays (like <code>Integer[]</code>).</p> * * <p>This class tries to handle <code>null</code> input gracefully. * An exception will not be thrown for a <code>null</code> * array input. However, an Object array that contains a <code>null</code> * element may throw an exception. Each method documents its behaviour.</p> * * @author Stephen Colebourne * @author Moritz Petersen * @author <a href="mailto:fredrik@westermarck.com">Fredrik Westermarck</a> * @author Nikolay Metchev * @author Matthew Hawthorne * @author Tim O'Brien * @author Pete Gieser * @author Gary Gregory * @author <a href="mailto:equinus100@hotmail.com">Ashwin S</a> * @author Fredrik Westermarck * @since 2.0 * @version $Id: ArrayUtils.java,v 1.34 2004/01/25 00:09:10 tobrien Exp $ */ public class ArrayUtils { /** * An empty immutable <code>Object</code> array. */ public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; /** * An empty immutable <code>Class</code> array. */ public static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; /** * An empty immutable <code>String</code> array. */ public static final String[] EMPTY_STRING_ARRAY = new String[0]; /** * An empty immutable <code>long</code> array. */ public static final long[] EMPTY_LONG_ARRAY = new long[0]; /** * An empty immutable <code>Long</code> array. */ public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0]; /** * An empty immutable <code>int</code> array. */ public static final int[] EMPTY_INT_ARRAY = new int[0]; /** * An empty immutable <code>Integer</code> array. */ public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0]; /** * An empty immutable <code>short</code> array. */ public static final short[] EMPTY_SHORT_ARRAY = new short[0]; /** * An empty immutable <code>Short</code> array. */ public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0]; /** * An empty immutable <code>byte</code> array. */ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** * An empty immutable <code>Byte</code> array. */ public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0]; /** * An empty immutable <code>double</code> array. */ public static final double[] EMPTY_DOUBLE_ARRAY = new double[0]; /** * An empty immutable <code>Double</code> array. */ public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0]; /** * An empty immutable <code>float</code> array. */ public static final float[] EMPTY_FLOAT_ARRAY = new float[0]; /** * An empty immutable <code>Float</code> array. */ public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0]; /** * An empty immutable <code>boolean</code> array. */ public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]; /** * An empty immutable <code>Boolean</code> array. */ public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0]; /** * An empty immutable <code>char</code> array. */ public static final char[] EMPTY_CHAR_ARRAY = new char[0]; /** * An empty immutable <code>Character</code> array. */ public static final Character[] EMPTY_CHARACTER_OBJECT_ARRAY = new Character[0]; /** * <p>ArrayUtils instances should NOT be constructed in standard programming. * Instead, the class should be used as <code>ArrayUtils.clone(new int[] {2})</code>.</p> * * <p>This constructor is public to permit tools that require a JavaBean instance * to operate.</p> */ public ArrayUtils() { } // Basic methods handling multi-dimensional arrays /** * <p>Outputs an array as a String, treating <code>null</code> as an empty array.</p> * * <p>Multi-dimensional arrays are handled correctly, including * multi-dimensional primitive arrays.</p> * * <p>The format is that of Java source code, for example <code>{a,b}</code>.</p> * * @param array the array to get a toString for, may be <code>null</code> * @return a String representation of the array, '{}' if null array input */ public static String toString(final Object array) { return toString(array, "{}"); } /** * <p>Outputs an array as a String handling <code>null</code>s.</p> * * <p>Multi-dimensional arrays are handled correctly, including * multi-dimensional primitive arrays.</p> * * <p>The format is that of Java source code, for example <code>{a,b}</code>.</p> * * @param array the array to get a toString for, may be <code>null</code> * @param stringIfNull the String to return if the array is <code>null</code> * @return a String representation of the array */ public static String toString(final Object array, final String stringIfNull) { if (array == null) { return stringIfNull; } return new ToStringBuilder(array, ToStringStyle.SIMPLE_STYLE).append(array).toString(); } /** * <p>Get a hashCode for an array handling multi-dimensional arrays correctly.</p> * * <p>Multi-dimensional primitive arrays are also handled correctly by this method.</p> * * @param array the array to get a hashCode for, may be <code>null</code> * @return a hashCode for the array, zero if null array input */ public static int hashCode(final Object array) { return new HashCodeBuilder().append(array).toHashCode(); } /** * <p>Compares two arrays, using equals(), handling multi-dimensional arrays * correctly.</p> * * <p>Multi-dimensional primitive arrays are also handled correctly by this method.</p> * * @param array1 the left hand array to compare, may be <code>null</code> * @param array2 the right hand array to compare, may be <code>null</code> * @return <code>true</code> if the arrays are equal */ public static boolean isEquals(final Object array1, final Object array2) { return new EqualsBuilder().append(array1, array2).isEquals(); } // To map public static Map toMap(final Object[] array) { if (array == null) { return null; } final Map map = new HashMap((int) (array.length * 1.5)); for (int i = 0; i < array.length; i++) { Object object = array[i]; if (object instanceof Map.Entry) { Map.Entry entry = (Map.Entry) object; map.put(entry.getKey(), entry.getValue()); } else if (object instanceof Object[]) { Object[] entry = (Object[]) object; if (entry.length < 2) { throw new IllegalArgumentException("Array element " + i + ", '" + object + "', has a length less than 2"); } map.put(entry[0], entry[1]); } else { throw new IllegalArgumentException("Array element " + i + ", '" + object + "', is neither of type Map.Entry nor an Array"); } } return map; } // Clone /** * <p>Shallow clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>The objects in the array are not cloned, thus there is no special * handling for multi-dimensional arrays.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array the array to shallow clone, may be <code>null</code> * @return the cloned array, <code>null</code> if <code>null</code> input */ public static Object[] clone(final Object[] array) { if (array == null) { return null; } return (Object[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, <code>null</code> if <code>null</code> input */ public static long[] clone(final long[] array) { if (array == null) { return null; } return (long[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, <code>null</code> if <code>null</code> input */ public static int[] clone(int[] array) { if (array == null) { return null; } return (int[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, <code>null</code> if <code>null</code> input */ public static short[] clone(final short[] array) { if (array == null) { return null; } return (short[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, <code>null</code> if <code>null</code> input */ public static char[] clone(final char[] array) { if (array == null) { return null; } return (char[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, <code>null</code> if <code>null</code> input */ public static byte[] clone(final byte[] array) { if (array == null) { return null; } return (byte[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, <code>null</code> if <code>null</code> input */ public static double[] clone(final double[] array) { if (array == null) { return null; } return (double[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, <code>null</code> if <code>null</code> input */ public static float[] clone(final float[] array) { if (array == null) { return null; } return (float[]) array.clone(); } /** * <p>Clones an array returning a typecast result and handling * <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array the array to clone, may be <code>null</code> * @return the cloned array, <code>null</code> if <code>null</code> input */ public static boolean[] clone(final boolean[] array) { if (array == null) { return null; } return (boolean[]) array.clone(); } // Subarrays /** * <p>Produces a new array containing the elements between * the start and end indices.</p> * * <p>The start index is inclusive, the end index exclusive. * Null array input produces null output.</p> * * <p>The component type of the subarray is always the same as * that of the input array. Thus, if the input is an array of type * <code>Date</code>, the following usage is envisaged:</p> * * <pre> * Date[] someDates = (Date[])ArrayUtils.subarray(allDates, 2, 5); * </pre> * * @param array the array * @param startIndexInclusive the starting index. Undervalue (&lt;0) * is promoted to 0, overvalue (&gt;array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (&lt; startIndex) produces * empty array, overvalue (&gt;array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. */ public static Object[] subarray(Object[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; Class type = array.getClass().getComponentType(); if (newSize <= 0) { return (Object[]) Array.newInstance(type, 0); } Object[] subarray = (Object[]) Array.newInstance(type, newSize); System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** * <p>Produces a new <code>long</code> array containing the elements * between the start and end indices.</p> * * <p>The start index is inclusive, the end index exclusive. * Null array input produces null output.</p> * * @param array the array * @param startIndexInclusive the starting index. Undervalue (&lt;0) * is promoted to 0, overvalue (&gt;array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (&lt; startIndex) produces * empty array, overvalue (&gt;array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. */ public static long[] subarray(long[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_LONG_ARRAY; } long[] subarray = new long[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** * <p>Produces a new <code>int</code> array containing the elements * between the start and end indices.</p> * * <p>The start index is inclusive, the end index exclusive. * Null array input produces null output.</p> * * @param array the array * @param startIndexInclusive the starting index. Undervalue (&lt;0) * is promoted to 0, overvalue (&gt;array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (&lt; startIndex) produces * empty array, overvalue (&gt;array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. */ public static int[] subarray(int[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_INT_ARRAY; } int[] subarray = new int[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** * <p>Produces a new <code>short</code> array containing the elements * between the start and end indices.</p> * * <p>The start index is inclusive, the end index exclusive. * Null array input produces null output.</p> * * @param array the array * @param startIndexInclusive the starting index. Undervalue (&lt;0) * is promoted to 0, overvalue (&gt;array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (&lt; startIndex) produces * empty array, overvalue (&gt;array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. */ public static short[] subarray(short[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_SHORT_ARRAY; } short[] subarray = new short[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** * <p>Produces a new <code>char</code> array containing the elements * between the start and end indices.</p> * * <p>The start index is inclusive, the end index exclusive. * Null array input produces null output.</p> * * @param array the array * @param startIndexInclusive the starting index. Undervalue (&lt;0) * is promoted to 0, overvalue (&gt;array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (&lt; startIndex) produces * empty array, overvalue (&gt;array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. */ public static char[] subarray(char[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_CHAR_ARRAY; } char[] subarray = new char[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** * <p>Produces a new <code>byte</code> array containing the elements * between the start and end indices.</p> * * <p>The start index is inclusive, the end index exclusive. * Null array input produces null output.</p> * * @param array the array * @param startIndexInclusive the starting index. Undervalue (&lt;0) * is promoted to 0, overvalue (&gt;array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (&lt; startIndex) produces * empty array, overvalue (&gt;array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. */ public static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_BYTE_ARRAY; } byte[] subarray = new byte[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** * <p>Produces a new <code>double</code> array containing the elements * between the start and end indices.</p> * * <p>The start index is inclusive, the end index exclusive. * Null array input produces null output.</p> * * @param array the array * @param startIndexInclusive the starting index. Undervalue (&lt;0) * is promoted to 0, overvalue (&gt;array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (&lt; startIndex) produces * empty array, overvalue (&gt;array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. */ public static double[] subarray(double[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_DOUBLE_ARRAY; } double[] subarray = new double[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** * <p>Produces a new <code>float</code> array containing the elements * between the start and end indices.</p> * * <p>The start index is inclusive, the end index exclusive. * Null array input produces null output.</p> * * @param array the array * @param startIndexInclusive the starting index. Undervalue (&lt;0) * is promoted to 0, overvalue (&gt;array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (&lt; startIndex) produces * empty array, overvalue (&gt;array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. */ public static float[] subarray(float[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_FLOAT_ARRAY; } float[] subarray = new float[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } /** * <p>Produces a new <code>boolean</code> array containing the elements * between the start and end indices.</p> * * <p>The start index is inclusive, the end index exclusive. * Null array input produces null output.</p> * * @param array the array * @param startIndexInclusive the starting index. Undervalue (&lt;0) * is promoted to 0, overvalue (&gt;array.length) results * in an empty array. * @param endIndexExclusive elements up to endIndex-1 are present in the * returned subarray. Undervalue (&lt; startIndex) produces * empty array, overvalue (&gt;array.length) is demoted to * array length. * @return a new array containing the elements between * the start and end indices. */ public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) { if (array == null) { return null; } if (startIndexInclusive < 0) { startIndexInclusive = 0; } if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_BOOLEAN_ARRAY; } boolean[] subarray = new boolean[newSize]; System.arraycopy(array, startIndexInclusive, subarray, 0, newSize); return subarray; } // Is same length /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>. * * <p>Any multi-dimensional aspects of the arrays are ignored.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(final Object[] array1, final Object[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(final long[] array1, final long[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(final int[] array1, final int[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(final short[] array1, final short[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(final char[] array1, final char[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(final byte[] array1, final byte[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(final double[] array1, final double[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(final float[] array1, final float[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } /** * <p>Checks whether two arrays are the same length, treating * <code>null</code> arrays as length <code>0</code>.</p> * * @param array1 the first array, may be <code>null</code> * @param array2 the second array, may be <code>null</code> * @return <code>true</code> if length of arrays matches, treating * <code>null</code> as an empty array */ public static boolean isSameLength(final boolean[] array1, final boolean[] array2) { if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) { return false; } return true; } public static boolean isSameType(final Object array1, final Object array2) { if (array1 == null || array2 == null) { throw new IllegalArgumentException("The Array must not be null"); } return array1.getClass().getName().equals(array2.getClass().getName()); } // Reverse /** * <p>Reverses the order of the given array.</p> * * <p>There is no special handling for multi-dimensional arrays.</p> * * <p>This method does nothing if <code>null</code> array input.</p> * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(final Object[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; Object tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j i++; } } /** * <p>Reverses the order of the given array.</p> * * <p>This method does nothing if <code>null</code> array input.</p> * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(final long[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; long tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j i++; } } /** * <p>Reverses the order of the given array.</p> * * <p>This method does nothing if <code>null</code> array input.</p> * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(final int[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; int tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j i++; } } /** * <p>Reverses the order of the given array.</p> * * <p>This method does nothing if <code>null</code> array input.</p> * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(final short[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; short tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j i++; } } /** * <p>Reverses the order of the given array.</p> * * <p>This method does nothing if <code>null</code> array input.</p> * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(final char[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; char tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j i++; } } /** * <p>Reverses the order of the given array.</p> * * <p>This method does nothing if <code>null</code> array input.</p> * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(final byte[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; byte tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j i++; } } /** * <p>Reverses the order of the given array.</p> * * <p>This method does nothing if <code>null</code> array input.</p> * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(final double[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; double tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j i++; } } /** * <p>Reverses the order of the given array.</p> * * <p>This method does nothing if <code>null</code> array input.</p> * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(final float[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; float tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j i++; } } /** * <p>Reverses the order of the given array.</p> * * <p>This method does nothing if <code>null</code> array input.</p> * * @param array the array to reverse, may be <code>null</code> */ public static void reverse(final boolean[] array) { if (array == null) { return; } int i = 0; int j = array.length - 1; boolean tmp; while (j > i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j i++; } } // IndexOf search // Object IndexOf /** * <p>Find the index of the given object in the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param objectToFind the object to find, may be <code>null</code> * @return the index of the object within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final Object[] array, final Object objectToFind) { return indexOf(array, objectToFind, 0); } /** * <p>Find the index of the given object in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex is treated as zero. A startIndex larger than the array * length will return <code>-1</code>.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param objectToFind the object to find, may be <code>null</code> * @param startIndex the index to start searching at * @return the index of the object within the array starting at the index, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final Object[] array, final Object objectToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { startIndex = 0; } if (objectToFind == null) { for (int i = startIndex; i < array.length; i++) { if (array[i] == null) { return i; } } } else { for (int i = startIndex; i < array.length; i++) { if (objectToFind.equals(array[i])) { return i; } } } return -1; } /** * <p>Find the last index of the given object within the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to travers backwords looking for the object, may be <code>null</code> * @param objectToFind the object to find, may be <code>null</code> * @return the last index of the object within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final Object[] array, final Object objectToFind) { return lastIndexOf(array, objectToFind, Integer.MAX_VALUE); } /** * <p>Find the last index of the given object in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex will return <code>-1</code>. A startIndex larger than * the array length will search from the end of the array.</p> * * @param array the array to traverse for looking for the object, may be <code>null</code> * @param objectToFind the object to find, may be <code>null</code> * @param startIndex the start index to travers backwards from * @return the last index of the object within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final Object[] array, final Object objectToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { return -1; } else if (startIndex >= array.length) { startIndex = array.length - 1; } if (objectToFind == null) { for (int i = startIndex; i >= 0; i if (array[i] == null) { return i; } } } else { for (int i = startIndex; i >= 0; i if (objectToFind.equals(array[i])) { return i; } } } return -1; } /** * <p>Checks if the object is in the given array.</p> * * <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p> * * @param array the array to search through * @param objectToFind the object to find * @return <code>true</code> if the array contains the object */ public static boolean contains(final Object[] array, final Object objectToFind) { return (indexOf(array, objectToFind) != -1); } // long IndexOf /** * <p>Find the index of the given value in the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final long[] array, final long valueToFind) { return indexOf(array, valueToFind, 0); } /** * <p>Find the index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex is treated as zero. A startIndex larger than the array * length will return -1.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final long[] array, final long valueToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Find the last index of the given value within the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to travers backwords looking for the object, may be <code>null</code> * @param valueToFind the object to find * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final long[] array, final long valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** * <p>Find the last index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex will return -1. A startIndex larger than the array * length will search from the end of the array.</p> * * @param array the array to traverse for looking for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final long[] array, final long valueToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { return -1; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Checks if the value is in the given array.</p> * * <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p> * * @param array the array to search through * @param valueToFind the value to find * @return <code>true</code> if the array contains the object */ public static boolean contains(final long[] array, final long valueToFind) { return (indexOf(array, valueToFind) != -1); } // int IndexOf /** * <p>Find the index of the given value in the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final int[] array, final int valueToFind) { return indexOf(array, valueToFind, 0); } /** * <p>Find the index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex is treated as zero. A startIndex larger than the array * length will return -1.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final int[] array, final int valueToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Find the last index of the given value within the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to travers backwords looking for the object, may be <code>null</code> * @param valueToFind the object to find * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final int[] array, final int valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** * <p>Find the last index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex will return -1. A startIndex larger than the array * length will search from the end of the array.</p> * * @param array the array to traverse for looking for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final int[] array, final int valueToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { return -1; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Checks if the value is in the given array.</p> * * <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p> * * @param array the array to search through * @param valueToFind the value to find * @return <code>true</code> if the array contains the object */ public static boolean contains(final int[] array, final int valueToFind) { return (indexOf(array, valueToFind) != -1); } // short IndexOf /** * <p>Find the index of the given value in the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final short[] array, final short valueToFind) { return indexOf(array, valueToFind, 0); } /** * <p>Find the index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex is treated as zero. A startIndex larger than the array * length will return -1.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final short[] array, final short valueToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Find the last index of the given value within the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to travers backwords looking for the object, may be <code>null</code> * @param valueToFind the object to find * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final short[] array, final short valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** * <p>Find the last index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex will return -1. A startIndex larger than the array * length will search from the end of the array.</p> * * @param array the array to traverse for looking for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final short[] array, final short valueToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { return -1; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Checks if the value is in the given array.</p> * * <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p> * * @param array the array to search through * @param valueToFind the value to find * @return <code>true</code> if the array contains the object */ public static boolean contains(final short[] array, final short valueToFind) { return (indexOf(array, valueToFind) != -1); } // byte IndexOf /** * <p>Find the index of the given value in the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final byte[] array, final byte valueToFind) { return indexOf(array, valueToFind, 0); } /** * <p>Find the index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex is treated as zero. A startIndex larger than the array * length will return -1.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final byte[] array, final byte valueToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Find the last index of the given value within the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to travers backwords looking for the object, may be <code>null</code> * @param valueToFind the object to find * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final byte[] array, final byte valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** * <p>Find the last index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex will return -1. A startIndex larger than the array * length will search from the end of the array.</p> * * @param array the array to traverse for looking for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final byte[] array, final byte valueToFind, int startIndex) { if (array == null) { return -1; } if (startIndex < 0) { return -1; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Checks if the value is in the given array.</p> * * <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p> * * @param array the array to search through * @param valueToFind the value to find * @return <code>true</code> if the array contains the object */ public static boolean contains(final byte[] array, final byte valueToFind) { return (indexOf(array, valueToFind) != -1); } // double IndexOf /** * <p>Find the index of the given value in the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final double[] array, final double valueToFind) { return indexOf(array, valueToFind, 0); } /** * <p>Find the index of the given value within a given tolerance in the array. * This method will return the index of the first value which falls between the region * defined by valueToFind - tolerance and valueToFind + tolerance.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @param tolerance tolerance of the search * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final double[] array, final double valueToFind, final double tolerance) { return indexOf(array, valueToFind, 0, tolerance); } /** * <p>Find the index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex is treated as zero. A startIndex larger than the array * length will return -1.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final double[] array, final double valueToFind, int startIndex) { if (ArrayUtils.isEmpty(array)) { return -1; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Find the index of the given value in the array starting at the given index. * This method will return the index of the first value which falls between the region * defined by valueToFind - tolerance and valueToFind + tolerance.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex is treated as zero. A startIndex larger than the array * length will return -1.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the index to start searching at * @param tolerance tolerance of the search * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final double[] array, final double valueToFind, int startIndex, double tolerance) { if (ArrayUtils.isEmpty(array)) { return -1; } if (startIndex < 0) { startIndex = 0; } double min = valueToFind - tolerance; double max = valueToFind + tolerance; for (int i = startIndex; i < array.length; i++) { if (array[i] >= min && array[i] <= max) { return i; } } return -1; } /** * <p>Find the last index of the given value within the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to travers backwords looking for the object, may be <code>null</code> * @param valueToFind the object to find * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final double[] array, final double valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** * <p>Find the last index of the given value within a given tolerance in the array. * This method will return the index of the last value which falls between the region * defined by valueToFind - tolerance and valueToFind + tolerance.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @param tolerance tolerance of the search * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final double[] array, final double valueToFind, final double tolerance) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE, tolerance); } /** * <p>Find the last index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex will return -1. A startIndex larger than the array * length will search from the end of the array.</p> * * @param array the array to traverse for looking for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex) { if (ArrayUtils.isEmpty(array)) { return -1; } if (startIndex < 0) { return -1; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Find the last index of the given value in the array starting at the given index. * This method will return the index of the last value which falls between the region * defined by valueToFind - tolerance and valueToFind + tolerance.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex will return -1. A startIndex larger than the array * length will search from the end of the array.</p> * * @param array the array to traverse for looking for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @param tolerance search for value within plus/minus this amount * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final double[] array, final double valueToFind, int startIndex, double tolerance) { if (ArrayUtils.isEmpty(array)) { return -1; } if (startIndex < 0) { return -1; } else if (startIndex >= array.length) { startIndex = array.length - 1; } double min = valueToFind - tolerance; double max = valueToFind + tolerance; for (int i = startIndex; i >= 0; i if (array[i] >= min && array[i] <= max) { return i; } } return -1; } /** * <p>Checks if the value is in the given array.</p> * * <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p> * * @param array the array to search through * @param valueToFind the value to find * @return <code>true</code> if the array contains the object */ public static boolean contains(final double[] array, final double valueToFind) { return (indexOf(array, valueToFind) != -1); } /** * <p>Checks if a value falling within the given tolerance is in the * given array. If the array contains a value within the inclusive range * defined by (value - tolerance) to (value + tolerance).</p> * * <p>The method returns <code>false</code> if a <code>null</code> array * is passed in.</p> * * @param array the array to search * @param valueToFind the value to find * @param tolerance the array contains the tolerance of the search * @return true if value falling within tolerance is in array */ public static boolean contains(final double[] array, final double valueToFind, final double tolerance) { return (indexOf(array, valueToFind, 0, tolerance) != -1); } // float IndexOf /** * <p>Find the index of the given value in the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final float[] array, final float valueToFind) { return indexOf(array, valueToFind, 0); } /** * <p>Find the index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex is treated as zero. A startIndex larger than the array * length will return -1.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final float[] array, final float valueToFind, int startIndex) { if (ArrayUtils.isEmpty(array)) { return -1; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Find the last index of the given value within the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to travers backwords looking for the object, may be <code>null</code> * @param valueToFind the object to find * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final float[] array, final float valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** * <p>Find the last index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex will return -1. A startIndex larger than the array * length will search from the end of the array.</p> * * @param array the array to traverse for looking for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final float[] array, final float valueToFind, int startIndex) { if (ArrayUtils.isEmpty(array)) { return -1; } if (startIndex < 0) { return -1; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Checks if the value is in the given array.</p> * * <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p> * * @param array the array to search through * @param valueToFind the value to find * @return <code>true</code> if the array contains the object */ public static boolean contains(final float[] array, final float valueToFind) { return (indexOf(array, valueToFind) != -1); } // boolean IndexOf /** * <p>Find the index of the given value in the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final boolean[] array, final boolean valueToFind) { return indexOf(array, valueToFind, 0); } /** * <p>Find the index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex is treated as zero. A startIndex larger than the array * length will return -1.</p> * * @param array the array to search through for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the index to start searching at * @return the index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int indexOf(final boolean[] array, final boolean valueToFind, int startIndex) { if (ArrayUtils.isEmpty(array)) { return -1; } if (startIndex < 0) { startIndex = 0; } for (int i = startIndex; i < array.length; i++) { if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Find the last index of the given value within the array.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * @param array the array to travers backwords looking for the object, may be <code>null</code> * @param valueToFind the object to find * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final boolean[] array, final boolean valueToFind) { return lastIndexOf(array, valueToFind, Integer.MAX_VALUE); } /** * <p>Find the last index of the given value in the array starting at the given index.</p> * * <p>This method returns <code>-1</code> if <code>null</code> array input.</p> * * <p>A negative startIndex will return -1. A startIndex larger than the array * length will search from the end of the array.</p> * * @param array the array to traverse for looking for the object, may be <code>null</code> * @param valueToFind the value to find * @param startIndex the start index to travers backwards from * @return the last index of the value within the array, * <code>-1</code> if not found or <code>null</code> array input */ public static int lastIndexOf(final boolean[] array, final boolean valueToFind, int startIndex) { if (ArrayUtils.isEmpty(array)) { return -1; } if (startIndex < 0) { return -1; } else if (startIndex >= array.length) { startIndex = array.length - 1; } for (int i = startIndex; i >= 0; i if (valueToFind == array[i]) { return i; } } return -1; } /** * <p>Checks if the value is in the given array.</p> * * <p>The method returns <code>false</code> if a <code>null</code> array is passed in.</p> * * @param array the array to search through * @param valueToFind the value to find * @return <code>true</code> if the array contains the object */ public static boolean contains(final boolean[] array, final boolean valueToFind) { return (indexOf(array, valueToFind) != -1); } // Primitive/Object array converters // Long array converters /** * <p>Converts an array of object Longs to primitives.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Long</code> array, may be <code>null</code> * @return a <code>long</code> array, <code>null</code> if null array input * @throws NullPointerException if array content is <code>null</code> */ public static long[] toPrimitive(final Long[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_LONG_ARRAY; } final long[] result = new long[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].longValue(); } return result; } /** * <p>Converts an array of object Long to primitives handling <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Long</code> array, may be <code>null</code> * @param valueForNull the value to insert if <code>null</code> found * @return a <code>long</code> array, <code>null</code> if null array input */ public static long[] toPrimitive(final Long[] array, final long valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_LONG_ARRAY; } final long[] result = new long[array.length]; for (int i = 0; i < array.length; i++) { Long b = array[i]; result[i] = (b == null ? valueForNull : b.longValue()); } return result; } /** * <p>Converts an array of primitive longs to objects.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>long</code> array * @return a <code>Long</code> array, <code>null</code> if null array input */ public static Long[] toObject(final long[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_LONG_OBJECT_ARRAY; } final Long[] result = new Long[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Long(array[i]); } return result; } // Int array converters /** * <p>Converts an array of object Integers to primitives.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Integer</code> array, may be <code>null</code> * @return an <code>int</code> array, <code>null</code> if null array input * @throws NullPointerException if array content is <code>null</code> */ public static int[] toPrimitive(final Integer[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_INT_ARRAY; } final int[] result = new int[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].intValue(); } return result; } /** * <p>Converts an array of object Integer to primitives handling <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Integer</code> array, may be <code>null</code> * @param valueForNull the value to insert if <code>null</code> found * @return an <code>int</code> array, <code>null</code> if null array input */ public static int[] toPrimitive(final Integer[] array, final int valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_INT_ARRAY; } final int[] result = new int[array.length]; for (int i = 0; i < array.length; i++) { Integer b = array[i]; result[i] = (b == null ? valueForNull : b.intValue()); } return result; } /** * <p>Converts an array of primitive ints to objects.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array an <code>int</code> array * @return an <code>Integer</code> array, <code>null</code> if null array input */ public static Integer[] toObject(final int[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_INTEGER_OBJECT_ARRAY; } final Integer[] result = new Integer[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Integer(array[i]); } return result; } // Short array converters /** * <p>Converts an array of object Shorts to primitives.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Short</code> array, may be <code>null</code> * @return a <code>byte</code> array, <code>null</code> if null array input * @throws NullPointerException if array content is <code>null</code> */ public static short[] toPrimitive(final Short[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_SHORT_ARRAY; } final short[] result = new short[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].shortValue(); } return result; } /** * <p>Converts an array of object Short to primitives handling <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Short</code> array, may be <code>null</code> * @param valueForNull the value to insert if <code>null</code> found * @return a <code>byte</code> array, <code>null</code> if null array input */ public static short[] toPrimitive(final Short[] array, final short valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_SHORT_ARRAY; } final short[] result = new short[array.length]; for (int i = 0; i < array.length; i++) { Short b = array[i]; result[i] = (b == null ? valueForNull : b.shortValue()); } return result; } /** * <p>Converts an array of primitive shorts to objects.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>short</code> array * @return a <code>Short</code> array, <code>null</code> if null array input */ public static Short[] toObject(final short[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_SHORT_OBJECT_ARRAY; } final Short[] result = new Short[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Short(array[i]); } return result; } // Byte array converters /** * <p>Converts an array of object Bytes to primitives.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Byte</code> array, may be <code>null</code> * @return a <code>byte</code> array, <code>null</code> if null array input * @throws NullPointerException if array content is <code>null</code> */ public static byte[] toPrimitive(final Byte[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BYTE_ARRAY; } final byte[] result = new byte[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].byteValue(); } return result; } /** * <p>Converts an array of object Bytes to primitives handling <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Byte</code> array, may be <code>null</code> * @param valueForNull the value to insert if <code>null</code> found * @return a <code>byte</code> array, <code>null</code> if null array input */ public static byte[] toPrimitive(final Byte[] array, final byte valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BYTE_ARRAY; } final byte[] result = new byte[array.length]; for (int i = 0; i < array.length; i++) { Byte b = array[i]; result[i] = (b == null ? valueForNull : b.byteValue()); } return result; } /** * <p>Converts an array of primitive bytes to objects.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>byte</code> array * @return a <code>Byte</code> array, <code>null</code> if null array input */ public static Byte[] toObject(final byte[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BYTE_OBJECT_ARRAY; } final Byte[] result = new Byte[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Byte(array[i]); } return result; } // Double array converters /** * <p>Converts an array of object Doubles to primitives.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Double</code> array, may be <code>null</code> * @return a <code>double</code> array, <code>null</code> if null array input * @throws NullPointerException if array content is <code>null</code> */ public static double[] toPrimitive(final Double[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_DOUBLE_ARRAY; } final double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].doubleValue(); } return result; } /** * <p>Converts an array of object Doubles to primitives handling <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Double</code> array, may be <code>null</code> * @param valueForNull the value to insert if <code>null</code> found * @return a <code>double</code> array, <code>null</code> if null array input */ public static double[] toPrimitive(final Double[] array, final double valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_DOUBLE_ARRAY; } final double[] result = new double[array.length]; for (int i = 0; i < array.length; i++) { Double b = array[i]; result[i] = (b == null ? valueForNull : b.doubleValue()); } return result; } /** * <p>Converts an array of primitive doubles to objects.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>double</code> array * @return a <code>Double</code> array, <code>null</code> if null array input */ public static Double[] toObject(final double[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_DOUBLE_OBJECT_ARRAY; } final Double[] result = new Double[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Double(array[i]); } return result; } // Float array converters /** * <p>Converts an array of object Floats to primitives.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Float</code> array, may be <code>null</code> * @return a <code>float</code> array, <code>null</code> if null array input * @throws NullPointerException if array content is <code>null</code> */ public static float[] toPrimitive(final Float[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_FLOAT_ARRAY; } final float[] result = new float[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].floatValue(); } return result; } /** * <p>Converts an array of object Floats to primitives handling <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Float</code> array, may be <code>null</code> * @param valueForNull the value to insert if <code>null</code> found * @return a <code>float</code> array, <code>null</code> if null array input */ public static float[] toPrimitive(final Float[] array, final float valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_FLOAT_ARRAY; } final float[] result = new float[array.length]; for (int i = 0; i < array.length; i++) { Float b = array[i]; result[i] = (b == null ? valueForNull : b.floatValue()); } return result; } /** * <p>Converts an array of primitive floats to objects.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>float</code> array * @return a <code>Float</code> array, <code>null</code> if null array input */ public static Float[] toObject(final float[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_FLOAT_OBJECT_ARRAY; } final Float[] result = new Float[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Float(array[i]); } return result; } // Boolean array converters /** * <p>Converts an array of object Booleans to primitives.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Boolean</code> array, may be <code>null</code> * @return a <code>boolean</code> array, <code>null</code> if null array input * @throws NullPointerException if array content is <code>null</code> */ public static boolean[] toPrimitive(final Boolean[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BOOLEAN_ARRAY; } final boolean[] result = new boolean[array.length]; for (int i = 0; i < array.length; i++) { result[i] = array[i].booleanValue(); } return result; } /** * <p>Converts an array of object Booleans to primitives handling <code>null</code>.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>Boolean</code> array, may be <code>null</code> * @param valueForNull the value to insert if <code>null</code> found * @return a <code>boolean</code> array, <code>null</code> if null array input */ public static boolean[] toPrimitive(final Boolean[] array, final boolean valueForNull) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BOOLEAN_ARRAY; } final boolean[] result = new boolean[array.length]; for (int i = 0; i < array.length; i++) { Boolean b = array[i]; result[i] = (b == null ? valueForNull : b.booleanValue()); } return result; } /** * <p>Converts an array of primitive booleans to objects.</p> * * <p>This method returns <code>null</code> if <code>null</code> array input.</p> * * @param array a <code>boolean</code> array * @return a <code>Boolean</code> array, <code>null</code> if null array input */ public static Boolean[] toObject(final boolean[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BOOLEAN_OBJECT_ARRAY; } final Boolean[] result = new Boolean[array.length]; for (int i = 0; i < array.length; i++) { result[i] = (array[i] ? Boolean.TRUE : Boolean.FALSE); } return result; } /** * <p>Checks if an array of Objects is empty or <code>null</code>.</p> * * @param array the array to test * @return <code>true</code> if the array is empty or <code>null</code> * @since 2.1 */ public static boolean isEmpty(final Object[] array) { if (array == null || array.length == 0) { return true; } return false; } /** * <p>Checks if an array of primitive longs is empty or <code>null</code>.</p> * * @param array the array to test * @return <code>true</code> if the array is empty or <code>null</code> * @since 2.1 */ public static boolean isEmpty(final long[] array) { if (array == null || array.length == 0) { return true; } return false; } /** * <p>Checks if an array of primitive ints is empty or <code>null</code>.</p> * * @param array the array to test * @return <code>true</code> if the array is empty or <code>null</code> * @since 2.1 */ public static boolean isEmpty(final int[] array) { if (array == null || array.length == 0) { return true; } return false; } /** * <p>Checks if an array of primitive shorts is empty or <code>null</code>.</p> * * @param array the array to test * @return <code>true</code> if the array is empty or <code>null</code> * @since 2.1 */ public static boolean isEmpty(final short[] array) { if (array == null || array.length == 0) { return true; } return false; } /** * <p>Checks if an array of primitive chars is empty or <code>null</code>.</p> * * @param array the array to test * @return <code>true</code> if the array is empty or <code>null</code> * @since 2.1 */ public static boolean isEmpty(final char[] array) { if (array == null || array.length == 0) { return true; } return false; } /** * <p>Checks if an array of primitive bytes is empty or <code>null</code>.</p> * * @param array the array to test * @return <code>true</code> if the array is empty or <code>null</code> * @since 2.1 */ public static boolean isEmpty(final byte[] array) { if (array == null || array.length == 0) { return true; } return false; } /** * <p>Checks if an array of primitive doubles is empty or <code>null</code>.</p> * * @param array the array to test * @return <code>true</code> if the array is empty or <code>null</code> * @since 2.1 */ public static boolean isEmpty(final double[] array) { if (array == null || array.length == 0) { return true; } return false; } /** * <p>Checks if an array of primitive floats is empty or <code>null</code>.</p> * * @param array the array to test * @return <code>true</code> if the array is empty or <code>null</code> * @since 2.1 */ public static boolean isEmpty(final float[] array) { if (array == null || array.length == 0) { return true; } return false; } /** * <p>Checks if an array of primitive booleans is empty or <code>null</code>.</p> * * @param array the array to test * @return <code>true</code> if the array is empty or <code>null</code> * @since 2.1 */ public static boolean isEmpty(final boolean[] array) { if (array == null || array.length == 0) { return true; } return false; } }
package innovimax.mixthem; import innovimax.mixthem.arguments.Rule; import innovimax.mixthem.exceptions.MixException; import java.io.*; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.logging.ConsoleHandler; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.theories.*; import org.junit.runner.RunWith; public class GenericTest { private static Logger LOGGER = Logger.getLogger(GenericTest.class.getName()); private static void setLogging() { System.setProperty("java.util.logging.SimpleFormatter.format", "[%4$s] MixThemUT: %5$s [%1$tc]%n"); String prop = System.getProperty("mixthem.logging"); if (prop == null || prop.equals("true")) { LOGGER.setLevel(Level.FINE); } else { LOGGER.setLevel(Level.OFF); } LOGGER.addHandler(new ConsoleHandler()); System.out.println("UT LOGGER NAME = "+LOGGER.getName()); System.out.println("UT LOGGER PARENT = "+LOGGER.getParent().getName()); } @Test public final void parameter() throws MixException, FileNotFoundException, IOException { setLogging(); int testId = 1; boolean result = true; RuleRuns ruleRuns = new RuleRuns(); while (true) { LOGGER.info("TEST N° " + testId); String prefix = "test" + String.format("%03d", testId) +"_"; URL url1 = getClass().getResource(prefix + "file1.txt"); URL url2 = getClass().getResource(prefix + "file2.txt"); LOGGER.fine("--> URL 1 (" + prefix + "file1.txt"+") : " + url1); LOGGER.fine("--> URL 2 (" + prefix + "file2.txt"+") : " + url2); if( url1 == null || url2 == null) break; for(Rule rule : Rule.values()) { String resource = prefix+"output-"+ rule.getExtension()+".txt"; URL url = getClass().getResource(resource); LOGGER.info(" RULE " + rule + " (" + (rule.isImplemented() ? "" : "NOT ") + "IMPLEMENTED)"); LOGGER.fine(" --> Resource (" + resource + ") : " + url); if (rule.isImplemented() && url != null) { List<RuleRun> runs = ruleRuns.getRuns(rule); for (RuleRun run : runs) { if (run.accept(testId)) { boolean res = check(new File(url1.getFile()), new File(url2.getFile()), new File(url.getFile()), rule, run.getParams()); LOGGER.info(" RUN " + (res ? "PASS" : "FAIL") + " WITH PARAMS " + run.getParams().toString()); result &= res; } } } } testId++; } Assert.assertTrue(result); } private final static boolean check(File file1, File file2, File expected, Rule rule, List<String> params) throws MixException, FileNotFoundException, IOException { ByteArrayOutputStream baos_rule = new ByteArrayOutputStream(); MixThem mixThem = new MixThem(file1, file2, baos_rule); mixThem.process(rule, params); //mixThem = new MixThem(file1, file2, System.out); //mixThem.process(rule, params); return checkFileEquals(expected, baos_rule.toByteArray()); } private static boolean checkFileEquals(File fileExpected, byte[] result) throws FileNotFoundException, IOException { FileInputStream fisExpected = new FileInputStream(fileExpected); int c; int offset = 0; while ((c = fisExpected.read()) != -1) { if (offset >= result.length) return false; int d = result[offset++]; if (c != d) return false; } if (offset > result.length) return false; return true; } }
package io.github.shark_app.shark; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import butterknife.BindView; import butterknife.ButterKnife; public class SignActivity extends AppCompatActivity { @BindView(R.id.scannedNameField) TextView scannedNameField; @BindView(R.id.scannedEmailField) TextView scannedEmailField; @BindView(R.id.scannedPublicKeyField) TextView scannedPublicKeyField; @BindView(R.id.signButton) Button signButton; private ProgressDialog progressDialog; private String getDataTaskOutput; private String scannedUserName; private String scannedUserEmail; private String scannedUserPublicKey; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign); ButterKnife.bind(this); Intent intent = getIntent(); String scannedUserEmail = intent.getStringExtra("qrCodeValue"); getScannedUserPublicData(scannedUserEmail); } private void getScannedUserPublicData(String email) { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { runGetDataTask(email); } else { makeSnackbar("ERROR : Retrieval failed due to network connection unavailability!"); } } private void makeSnackbar(String snackbarText) { Snackbar.make(getWindow().getDecorView().getRootView(), snackbarText, Snackbar.LENGTH_LONG) .setAction("Dismiss", new View.OnClickListener() { @Override public void onClick(View v) {} }) .show(); } private void runGetDataTask(String email) { GetDataTaskRunner getDataTaskRunner = new GetDataTaskRunner(); getDataTaskRunner.execute(email); } private class GetDataTaskRunner extends AsyncTask<String, Void, Integer> { String userName; String userEmail; String userPublicKey; @Override protected void onPreExecute() { progressDialog = new ProgressDialog(SignActivity.this, ProgressDialog.STYLE_SPINNER); progressDialog.setMessage("Verifying user"); progressDialog.setIndeterminate(true); progressDialog.setCancelable(false); progressDialog.show(); super.onPreExecute(); } @Override protected Integer doInBackground(String...params) { userEmail = params[0]; InputStream inputStream = null; try { String getUrl = "http://192.168.55.157:3000/email/userDetails" + "/" + userEmail; URL url = new URL(getUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(7000); httpURLConnection.setReadTimeout(5000); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setRequestProperty("Accept", "application/json"); httpURLConnection.setDoInput(true); httpURLConnection.connect(); inputStream = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); String line; String buffer = ""; while ((line = bufferedReader.readLine()) != null) { buffer += line; buffer += "\n"; } httpURLConnection.disconnect(); bufferedReader.close(); getDataTaskOutput = buffer; return 0; } catch (SocketTimeoutException e) { return 1; } catch (IOException e) { return 2; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { return 3; } } } } @Override protected void onPostExecute(Integer result) { progressDialog.dismiss(); getDataTaskComplete(result); } } private void getDataTaskComplete(int getDataTaskResult) { boolean proceed = false; switch (getDataTaskResult) { case 0: { try { JSONObject jsonObject = new JSONObject(getDataTaskOutput); scannedUserEmail = jsonObject.getString("email"); scannedUserName = jsonObject.getString("name"); scannedUserPublicKey = jsonObject.getString("publickey"); scannedEmailField.setText(scannedUserEmail); scannedNameField.setText(scannedUserName); scannedPublicKeyField.setText(scannedUserPublicKey); proceed = true; } catch (Exception e) {} break; } case 1: makeSnackbar("ERROR : Connection timed out!"); break; case 2: makeSnackbar("ERROR : Unable to retrieve data!"); break; case 3: makeSnackbar("ERROR : Unable to retrieve data!"); break; default: makeSnackbar("ERROR!"); break; } if (proceed) makeSnackbar("TIME TO SIGN!!!"); } @Override public void onBackPressed() { Intent intent = new Intent(this, ScanActivity.class); startActivity(intent); finish(); } }
package io.tetrapod.web; import static io.netty.handler.codec.http.HttpHeaders.*; import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import static io.tetrapod.protocol.core.Core.*; import static io.tetrapod.protocol.core.CoreContract.*; import java.io.IOException; import java.nio.charset.Charset; import java.util.*; import java.util.concurrent.TimeUnit; import io.netty.handler.codec.http.cors.*; import io.tetrapod.core.tasks.TaskContext; import org.slf4j.*; import com.codahale.metrics.Timer; import com.codahale.metrics.Timer.Context; import io.netty.buffer.*; import io.netty.channel.*; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.websocketx.*; import io.netty.util.*; import io.tetrapod.core.*; import io.tetrapod.core.json.*; import io.tetrapod.core.logging.CommsLogger; import io.tetrapod.core.rpc.*; import io.tetrapod.core.rpc.Error; import io.tetrapod.core.serialize.datasources.ByteBufDataSource; import io.tetrapod.core.utils.Util; import io.tetrapod.protocol.core.*; public class WebHttpSession extends WebSession { protected static final Logger logger = LoggerFactory.getLogger(WebHttpSession.class); public static final Timer requestTimes = Metrics.timer(WebHttpSession.class, "requests", "time"); private static final int FLOOD_TIME_PERIOD = 2000; private static final int FLOOD_WARN = 200; private static final int FLOOD_IGNORE = 300; private static final int FLOOD_KILL = 400; private volatile long floodPeriod; private int reqCounter = 0; private final String wsLocation; private WebSocketServerHandshaker handshaker; private Map<Integer, ChannelHandlerContext> contexts; private String httpReferrer = null; private String domain = null; private String build = null; public WebHttpSession(SocketChannel ch, Session.Helper helper, Map<String, WebRoot> roots, String wsLocation) { super(ch, helper); this.wsLocation = wsLocation; ch.pipeline().addLast("codec-http", new HttpServerCodec()); ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("cors", new CorsHandler(CorsConfigBuilder.forAnyOrigin().allowedRequestHeaders("Content-Type").build())); ch.pipeline().addLast("api", this); ch.pipeline().addLast("deflater", new HttpContentCompressor(6)); ch.pipeline().addLast("maintenance", new MaintenanceHandler(roots.get("tetrapod"))); ch.pipeline().addLast("files", new WebStaticFileHandler(roots)); } @Override public void checkHealth() { TaskContext taskContext = TaskContext.pushNew(); try { if (isConnected()) { timeoutPendingRequests(); } } finally { taskContext.pop(); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { TaskContext taskContext = TaskContext.pushNew(); try { if (msg instanceof FullHttpRequest) { handleHttpRequest(ctx, (FullHttpRequest) msg); } else if (msg instanceof WebSocketFrame) { handleWebSocketFrame(ctx, (WebSocketFrame) msg); } } finally { taskContext.pop(); } } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { TaskContext taskContext = TaskContext.pushNew(); try { fireSessionStartEvent(); scheduleHealthCheck(); } finally { taskContext.pop(); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { TaskContext taskContext = TaskContext.pushNew(); try { fireSessionStopEvent(); cancelAllPendingRequests(); } finally { taskContext.pop(); } } public synchronized boolean isWebSocket() { return handshaker != null; } public synchronized void initLongPoll() { if (contexts == null) { contexts = new HashMap<>(); } } private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), new CloseWebSocketFrame()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof PongWebSocketFrame) { return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } String request = ((TextWebSocketFrame) frame).text(); ReferenceCountUtil.release(frame); try { JSONObject jo = new JSONObject(request); WebContext webContext = new WebContext(jo); RequestHeader header = webContext.makeRequestHeader(this, null); readAndDispatchRequest(header, webContext.getRequestParams()); return; } catch (IOException e) { logger.error("error processing websocket request", e); ctx.channel().writeAndFlush(new TextWebSocketFrame("Illegal request: " + request)); } } private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception { if (logger.isTraceEnabled()) { synchronized (this) { logger.trace(String.format("%s REQUEST[%d] = %s : %s", this, ++reqCounter, ctx.channel().remoteAddress(), req.getUri())); } } // Set the http referrer for this request, if not already set if (Util.isEmpty(getHttpReferrer())) { setHttpReferrer(req.headers().get("Referer")); logger.debug("•••• Referer: {} ", getHttpReferrer()); } // Set the domain for this request, if not already set if (Util.isEmpty(getDomain())) { setDomain(req.headers().get("Host")); logger.debug("•••• Domain: {} ", getDomain()); } // see if we need to start a web socket session if (wsLocation != null && wsLocation.equals(req.getUri())) { if (Util.isProduction()) { String host = req.headers().get("Host"); String origin = req.headers().get("Origin"); if (origin != null && host != null) { if (!(origin.equals("http: logger.warn("origin [{}] doesn't match host [{}]", origin, host); sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED)); return; } } } WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(wsLocation, null, false); synchronized (this) { handshaker = wsFactory.newHandshaker(req); } if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } } else { final Context metricContext = requestTimes.time(); if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } // this handles long-polling calls when we fall back to long-polling for browsers with no websockets if (req.getUri().equals("/poll")) { handlePoll(ctx, req); return; } // check for web-route handler final WebRoute route = relayHandler.getWebRoutes().findRoute(req.getUri()); if (route != null) { handleWebRoute(ctx, req, route); } else { // pass request down the pipeline ctx.fireChannelRead(req); } metricContext.stop(); } } private String getContent(final FullHttpRequest req) { final ByteBuf contentBuf = req.content(); try { return contentBuf.toString(Charset.forName("UTF-8")); } finally { contentBuf.release(); } } private void handlePoll(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception { logger.debug("{} POLLER: {} keepAlive = {}", this, req.getUri(), HttpHeaders.isKeepAlive(req)); final JSONObject params = new JSONObject(getContent(req)); // authenticate this session, if needed if (params.has("_token")) { Integer clientId = LongPollToken.validateToken(params.getString("_token")); if (clientId != null) { setTheirEntityId(clientId); setTheirEntityType(Core.TYPE_CLIENT); LongPollQueue.getQueue(clientId, true); // init long poll queue } else { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } } initLongPoll(); if (params.has("_requestId")) { logger.debug("{} RPC: structId={}", this, params.getInt("_structId")); // dispatch a request final RequestHeader header = WebContext.makeRequestHeader(this, null, params); header.fromType = Core.TYPE_CLIENT; header.fromChildId = getTheirEntityId(); header.fromParentId = getMyEntityId(); synchronized (contexts) { contexts.put(header.requestId, ctx); } readAndDispatchRequest(header, params); } else if (getTheirEntityId() != 0) { getDispatcher().dispatch(() -> { final LongPollQueue messages = LongPollQueue.getQueue(getTheirEntityId(), false); final long startTime = System.currentTimeMillis(); // long poll -- wait until there are messages in queue, and return them assert messages != null; // we grab a lock so only one poll request processes at a time longPoll(25, messages, startTime, ctx, req); }); } } private void longPoll(final int millis, final LongPollQueue messages, final long startTime, final ChannelHandlerContext ctx, final FullHttpRequest req) { getDispatcher().dispatch(millis, TimeUnit.MILLISECONDS, () -> { if (messages.tryLock()) { try { if (messages.size() > 0) { final JSONArray arr = new JSONArray(); while (!messages.isEmpty()) { JSONObject jo = messages.poll(); if (jo != null) { arr.put(jo); } } logger.debug("{} long poll {} has {} items\n", this, messages.getEntityId(), messages.size()); ctx.writeAndFlush(makeFrame(new JSONObject().put("messages", arr), HttpHeaders.isKeepAlive(req))); } else { if (System.currentTimeMillis() - startTime > Util.ONE_SECOND * 10) { ctx.writeAndFlush(makeFrame(new JSONObject().put("messages", new JSONArray()), HttpHeaders.isKeepAlive(req))); } else { // wait a bit and check again longPoll(50, messages, startTime, ctx, req); } } messages.setLastDrain(System.currentTimeMillis()); } finally { messages.unlock(); } } else { ctx.writeAndFlush(makeFrame(new JSONObject().put("error", "locked"), HttpHeaders.isKeepAlive(req))); } }); } // handle a JSON API call private void handleWebRoute(final ChannelHandlerContext ctx, final FullHttpRequest req, final WebRoute route) throws Exception { final WebContext context = new WebContext(req, route.path); final RequestHeader header = context.makeRequestHeader(this, route); if (header != null) { //final long t0 = System.currentTimeMillis(); logger.debug("{} WEB API REQUEST: {} keepAlive = {}", this, req.getUri(), HttpHeaders.isKeepAlive(req)); header.requestId = requestCounter.incrementAndGet(); header.fromType = Core.TYPE_WEBAPI; header.fromParentId = getMyEntityId(); header.fromChildId = getTheirEntityId(); final ResponseHandler handler = new ResponseHandler() { @Override public void onResponse(Response res) { logger.info("{} WEB API RESPONSE: {} ", WebHttpSession.this, res); handleWebAPIResponse(ctx, req, res); } }; try { if (header.structId == WebAPIRequest.STRUCT_ID) { // @webapi() generic WebAPIRequest call String body = req.content().toString(CharsetUtil.UTF_8); if (body == null || body.trim().isEmpty()) { body = req.getUri(); } final WebAPIRequest request = new WebAPIRequest(route.path, getHeaders(req).toString(), context.getRequestParams().toString(), body, req.getUri()); final int toEntityId = relayHandler.getAvailableService(header.contractId); if (toEntityId != 0) { final Session ses = relayHandler.getRelaySession(toEntityId, header.contractId); if (ses != null) { header.contractId = Core.CONTRACT_ID; header.toId = toEntityId; logger.info("{} WEB API REQUEST ROUTING TO {} {}", this, toEntityId, header.dump()); relayRequest(header, request, ses, handler); } else { logger.debug("{} Could not find a relay session for {} {}", this, header.toId, header.contractId); handler.fireResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header); } } else { logger.debug("{} Could not find a service for {}", this, header.contractId); handler.fireResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header); } } else { // @web() specific Request mapping final Structure request = readRequest(header, context.getRequestParams()); if (request != null) { if (header.contractId == TetrapodContract.CONTRACT_ID && header.toId == 0) { header.toId = Core.DIRECT; } relayRequest(header, request, handler); } else { handler.fireResponse(new Error(ERROR_UNKNOWN_REQUEST), header); } } } finally { ReferenceCountUtil.release(req); } } else { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); } } private void handleWebAPIResponse(final ChannelHandlerContext ctx, final FullHttpRequest req, Response res) { final boolean keepAlive = HttpHeaders.isKeepAlive(req); try { ChannelFuture cf = null; if (res.isError()) { if (res.errorCode() == CoreContract.ERROR_TIMEOUT) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, REQUEST_TIMEOUT)); } else { JSONObject jo = new JSONObject(); jo.put("result", "ERROR"); jo.put("error", res.errorCode()); jo.put("message", Contract.getErrorCode(res.errorCode(), res.getContractId())); cf = ctx.writeAndFlush(makeFrame(jo, keepAlive)); } } else if (isGenericSuccess(res)) { // bad form to allow two types of non-error response but most calls will just want to return SUCCESS JSONObject jo = new JSONObject(); jo.put("result", "SUCCESS"); cf = ctx.writeAndFlush(makeFrame(jo, keepAlive)); } else if (res instanceof WebAPIResponse) { WebAPIResponse resp = (WebAPIResponse) res; if (resp.redirect != null && !resp.redirect.isEmpty()) { redirect(resp.redirect, ctx); } else { if (resp.json != null) { cf = ctx.writeAndFlush(makeFrame(new JSONObject(resp.json), keepAlive)); } else { logger.warn("{} WebAPIResponse JSON is null: {}", this, resp.dump()); } } } else { // a blank response ctx.writeAndFlush(makeFrame(new ResponseHeader(0, 0, 0, 0), res, ENVELOPE_RESPONSE)); } if (cf != null && !keepAlive) { cf.addListener(ChannelFutureListener.CLOSE); } } catch (Throwable e) { logger.error(e.getMessage(), e); } } private JSONObject getHeaders(FullHttpRequest req) { JSONObject jo = new JSONObject(); for (Map.Entry<String, String> e : req.headers()) { jo.put(e.getKey(), e.getValue()); } return jo; } protected void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); try { res.content().writeBytes(buf); } finally { buf.release(); } setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } } @Override protected Object makeFrame(JSONObject jo, boolean keepAlive) { if (isWebSocket()) { return new TextWebSocketFrame(jo.toString(3)); } else { String payload = jo.optString("__httpPayload", null); if (payload == null) { payload = jo.toStringWithout("__http"); } ByteBuf buf = WebContext.makeByteBufResult(payload + '\n'); HttpResponseStatus status = HttpResponseStatus.valueOf(jo.optInt("__httpStatus", OK.code())); FullHttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, status, buf); httpResponse.headers().set(CONTENT_TYPE, jo.optString("__httpMime", "application/json")); httpResponse.headers().set(CONTENT_LENGTH, httpResponse.content().readableBytes()); httpResponse.headers().set(CONNECTION, keepAlive ? HttpHeaders.Values.KEEP_ALIVE : HttpHeaders.Values.CLOSE); if (jo.has("__httpDisposition")) { httpResponse.headers().set("Content-Disposition", jo.optString("__httpDisposition")); } return httpResponse; } } private void relayRequest(RequestHeader header, Structure request, ResponseHandler handler) throws IOException { final Session ses = relayHandler.getRelaySession(header.toId, header.contractId); if (ses != null) { relayRequest(header, request, ses, handler); } else { logger.debug("{} Could not find a relay session for {} {}", this, header.toId, header.contractId); handler.fireResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header); } } protected Async relayRequest(RequestHeader header, Structure request, Session ses, ResponseHandler handler) throws IOException { final ByteBuf in = convertToByteBuf(request); try { return ses.sendRelayedRequest(header, in, this, handler); } finally { in.release(); } } protected ByteBuf convertToByteBuf(Structure struct) throws IOException { ByteBuf buffer = channel.alloc().buffer(32); ByteBufDataSource data = new ByteBufDataSource(buffer); struct.write(data); return buffer; } private void redirect(String newURL, ChannelHandlerContext ctx) { HttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND); response.headers().set(LOCATION, newURL); response.headers().set(CONNECTION, HttpHeaders.Values.CLOSE); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } protected void readAndDispatchRequest(RequestHeader header, JSONObject params) { long now = System.currentTimeMillis(); lastHeardFrom.set(now); if (floodCheck(now, header)) { // could move flood check after comms log just for the logging return; } try { final Structure request = readRequest(header, params); if (request != null) { if (header.toId == DIRECT || header.toId == myId) { if (request instanceof Request) { dispatchRequest(header, (Request) request); } else { logger.error("Asked to process a request I can't deserialize {}", header.dump()); sendResponse(new Error(ERROR_SERIALIZATION), header); } } else { relayRequest(header, request); } } else { sendResponse(new Error(ERROR_UNKNOWN_REQUEST), header); } } catch (IOException e) { logger.error("Error processing request {}", header.dump()); sendResponse(new Error(ERROR_UNKNOWN), header); } } private ChannelHandlerContext getContext(int requestId) { synchronized (contexts) { return contexts.remove(requestId); } } @Override public void sendResponse(Response res, RequestHeader reqHeader) { if (isWebSocket()) { super.sendResponse(res, reqHeader); } else { // HACK: for http responses we need to write to the response to the correct ChannelHandlerContext if (res != Response.PENDING) { final ResponseHeader header = new ResponseHeader(reqHeader.requestId, res.getContractId(), res.getStructId(), reqHeader.contextId); CommsLogger.append(this, true, header, res, reqHeader.structId); final Object buffer = makeFrame(header, res, ENVELOPE_RESPONSE); if (buffer != null && channel.isActive()) { ChannelHandlerContext ctx = getContext(reqHeader.requestId); if (ctx != null) { ctx.writeAndFlush(buffer); } else { logger.warn("{} Could not find context for {}", this, reqHeader.requestId); writeFrame(buffer); } } } } } @Override public void sendRelayedResponse(ResponseHeader header, Async async, ByteBuf payload) { if (isWebSocket()) { super.sendRelayedResponse(header, async, payload); } else { CommsLogger.append(this, true, header, payload, async.header.structId); // HACK: for http responses we need to write to the response to the correct ChannelHandlerContext ChannelHandlerContext ctx = getContext(header.requestId); final Object buffer = makeFrame(header, payload, ENVELOPE_RESPONSE); if (ctx != null) { ctx.writeAndFlush(buffer); } else { writeFrame(buffer); } } } private Async relayRequest(RequestHeader header, Structure request) throws IOException { final Session ses = relayHandler.getRelaySession(header.toId, header.contractId); if (ses != null) { return relayRequest(header, request, ses, null); } else { logger.debug("Could not find a relay session for {} {}", header.toId, header.contractId); sendResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header); return null; } } @Override public void sendRelayedMessage(MessageHeader header, ByteBuf payload, boolean broadcast) { if (isWebSocket()) { super.sendRelayedMessage(header, payload, broadcast); } else { // queue the message for long poller to retrieve later CommsLogger.append(this, true, header, payload); final LongPollQueue messages = LongPollQueue.getQueue(getTheirEntityId(), false); if (messages != null) { // FIXME: Need a sensible way to protect against memory gobbling if this queue isn't cleared fast enough messages.add(toJSON(header, payload, ENVELOPE_MESSAGE)); logger.debug("{} Queued {} messages for longPoller {}", this, messages.size(), messages.getEntityId()); } } } private boolean floodCheck(long now, RequestHeader header) { int reqs; long newFloodPeriod = now / FLOOD_TIME_PERIOD; if (newFloodPeriod != floodPeriod) { // race condition between read and write of floodPeriod. but is benign as it means we reset // request count to 0 an extra time floodPeriod = newFloodPeriod; requestCount.set(0); reqs = 0; } else { reqs = requestCount.incrementAndGet(); } if (reqs > FLOOD_KILL) { logger.warn("{} flood killing {}/{}", this, header.contractId, header.structId); close(); return true; } if (reqs > FLOOD_IGNORE) { // do nothing, send no response logger.warn("{} flood ignoring {}/{}", this, header.contractId, header.structId); return true; } if (reqs > FLOOD_WARN) { // respond with error so client can slow down logger.warn("{} flood warning {}/{}", this, header.contractId, header.structId); sendResponse(new Error(ERROR_FLOOD), header); return true; } return false; } private boolean isGenericSuccess(Response r) { Response s = Response.SUCCESS; return s.getContractId() == r.getContractId() && s.getStructId() == r.getStructId(); } public synchronized String getHttpReferrer() { return httpReferrer; } public synchronized void setHttpReferrer(String httpReferrer) { this.httpReferrer = httpReferrer; } public synchronized String getDomain() { return domain; } public synchronized void setDomain(String domain) { this.domain = domain; } public synchronized void setBuild(String build) { this.build = build; } public synchronized String getBuild() { return build; } }
package io.github.shark_app.shark; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.json.JSONObject; import org.spongycastle.bcpg.ArmoredOutputStream; import org.spongycastle.bcpg.BCPGOutputStream; import org.spongycastle.openpgp.PGPException; import org.spongycastle.openpgp.PGPPrivateKey; import org.spongycastle.openpgp.PGPPublicKey; import org.spongycastle.openpgp.PGPPublicKeyRing; import org.spongycastle.openpgp.PGPSecretKey; import org.spongycastle.openpgp.PGPSecretKeyRing; import org.spongycastle.openpgp.PGPSignature; import org.spongycastle.openpgp.PGPSignatureGenerator; import org.spongycastle.openpgp.PGPSignatureSubpacketGenerator; import org.spongycastle.openpgp.PGPSignatureSubpacketVector; import org.spongycastle.openpgp.PGPUtil; import org.spongycastle.openpgp.jcajce.JcaPGPPublicKeyRingCollection; import org.spongycastle.openpgp.jcajce.JcaPGPSecretKeyRingCollection; import org.spongycastle.openpgp.operator.jcajce.JcaKeyFingerprintCalculator; import org.spongycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder; import org.spongycastle.openpgp.operator.jcajce.JcePBESecretKeyDecryptorBuilder; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; 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.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.security.Security; import java.util.Iterator; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static io.github.shark_app.shark.MainActivity.PREFS_NAME; import static io.github.shark_app.shark.MainActivity.PREFS_USER_PRIVATE_KEY; public class SignActivity extends AppCompatActivity { static { Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); } @BindView(R.id.scannedNameField) TextView scannedNameField; @BindView(R.id.scannedEmailField) TextView scannedEmailField; @BindView(R.id.scannedPublicKeyField) TextView scannedPublicKeyField; @BindView(R.id.signButton) Button signButton; private ProgressDialog progressDialog; private String getDataTaskOutput; private String scannedUserName; private String scannedUserEmail; private String scannedUserPublicKey; private String currentUserPrivateKey; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign); ButterKnife.bind(this); signButton.setEnabled(false); SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); currentUserPrivateKey = settings.getString(PREFS_USER_PRIVATE_KEY, null); Intent intent = getIntent(); String scannedUserEmail = intent.getStringExtra("qrCodeValue"); getScannedUserPublicData(scannedUserEmail); } @OnClick(R.id.signButton) public void signKey(View view) { try { PGPPublicKey keyToBeSigned = getPublicKeyFromString(scannedUserPublicKey); PGPSecretKey secretKey = getSecretKeyFromString(currentUserPrivateKey); PGPPublicKeyRing signedRing = new PGPPublicKeyRing( new ByteArrayInputStream(signPublicKey(secretKey, "sahi", keyToBeSigned, "TEST", "true", true)), new JcaKeyFingerprintCalculator()); File sdcard = Environment.getExternalStorageDirectory(); File directory = new File(sdcard.getAbsolutePath() + "/Signed_Keys/"); directory.mkdir(); String filename = scannedUserName + ".asc"; File file = new File(directory, filename); ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(new FileOutputStream(file)); signedRing.encode(armoredOutputStream); armoredOutputStream.flush(); armoredOutputStream.close(); } catch (PGPException p) { makeAlertDialog("PGP error", "The application encountered an error. Please check the private key involved in signing and the private key passphrase that was entered. Press OK to scan again."); } catch (Exception e) { e.printStackTrace(); } } private void getScannedUserPublicData(String email) { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { runGetDataTask(email); } else { makeSnackbar("ERROR : Retrieval failed due to network connection unavailability!"); } } private void makeSnackbar(String snackbarText) { Snackbar.make(getWindow().getDecorView().getRootView(), snackbarText, Snackbar.LENGTH_LONG) .setAction("Dismiss", new View.OnClickListener() { @Override public void onClick(View v) {} }) .show(); } private void runGetDataTask(String email) { GetDataTaskRunner getDataTaskRunner = new GetDataTaskRunner(); getDataTaskRunner.execute(email); } private class GetDataTaskRunner extends AsyncTask<String, Void, Integer> { String userEmail; @Override protected void onPreExecute() { progressDialog = new ProgressDialog(SignActivity.this, ProgressDialog.STYLE_SPINNER); progressDialog.setMessage("Verifying user"); progressDialog.setIndeterminate(true); progressDialog.setCancelable(false); progressDialog.show(); super.onPreExecute(); } @Override protected Integer doInBackground(String...params) { userEmail = params[0]; InputStream inputStream = null; try { String getUrl = "http://192.168.55.157:3000/email/userDetails" + "/" + userEmail; URL url = new URL(getUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(7000); httpURLConnection.setReadTimeout(5000); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setRequestProperty("Accept", "application/json"); httpURLConnection.setDoInput(true); httpURLConnection.connect(); inputStream = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); String line; String buffer = ""; while ((line = bufferedReader.readLine()) != null) { buffer += line; buffer += "\n"; } httpURLConnection.disconnect(); bufferedReader.close(); getDataTaskOutput = buffer; return 0; } catch (SocketTimeoutException e) { return 1; } catch (IOException e) { return 2; } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { return 3; } } } } @Override protected void onPostExecute(Integer result) { progressDialog.dismiss(); getDataTaskComplete(result); } } private void getDataTaskComplete(int getDataTaskResult) { switch (getDataTaskResult) { case 0: { try { JSONObject jsonObject = new JSONObject(getDataTaskOutput); scannedUserEmail = jsonObject.getString("email"); scannedUserName = jsonObject.getString("name"); scannedUserPublicKey = jsonObject.getString("publickey"); scannedEmailField.setText(scannedUserEmail); scannedNameField.setText(scannedUserName); PGPPublicKey pgpPublicKey = getPublicKeyFromString(scannedUserPublicKey); scannedPublicKeyField.setText(String.valueOf(pgpPublicKey.getKeyID())); signButton.setEnabled(true); } catch (PGPException p) { makeAlertDialog("PGP error", "The application encountered an error. The public key returned by scanning is not valid. Press OK to scan again."); } catch (Exception e) { e.printStackTrace(); } break; } case 1: makeSnackbar("ERROR : Connection timed out!"); break; case 2: makeSnackbar("ERROR : Unable to retrieve data!"); break; case 3: makeSnackbar("ERROR : Unable to retrieve data!"); break; default: makeSnackbar("ERROR!"); break; } } public static PGPPublicKey getPublicKeyFromString(String str) throws Exception { InputStream inputStream = new ByteArrayInputStream(str.getBytes()); inputStream = org.spongycastle.openpgp.PGPUtil.getDecoderStream(inputStream); JcaPGPPublicKeyRingCollection jcaPGPPublicKeyRingCollection = new JcaPGPPublicKeyRingCollection(inputStream); inputStream.close(); PGPPublicKey pgpPublicKey = null; Iterator<PGPPublicKeyRing> iterator = jcaPGPPublicKeyRingCollection.getKeyRings(); while (pgpPublicKey == null && iterator.hasNext()) { PGPPublicKeyRing kRing = iterator.next(); Iterator<PGPPublicKey> iteratorKey = kRing.getPublicKeys(); while (pgpPublicKey == null && iteratorKey.hasNext()) { pgpPublicKey = iteratorKey.next(); } } return pgpPublicKey; } public static PGPSecretKey getSecretKeyFromString(String str) throws Exception{ InputStream inputStream = new ByteArrayInputStream(str.getBytes()); inputStream = org.spongycastle.openpgp.PGPUtil.getDecoderStream(inputStream); JcaPGPSecretKeyRingCollection jcaPGPSecretKeyRingCollection = new JcaPGPSecretKeyRingCollection(inputStream); inputStream.close(); PGPSecretKey pgpSecretKey = null; Iterator<PGPSecretKeyRing> iterator = jcaPGPSecretKeyRingCollection.getKeyRings(); while (pgpSecretKey == null && iterator.hasNext()) { PGPSecretKeyRing kRing = iterator.next(); Iterator<PGPSecretKey> iteratorKey = kRing.getSecretKeys(); while (pgpSecretKey == null && iteratorKey.hasNext()) { pgpSecretKey = iteratorKey.next(); } } return pgpSecretKey; } private static byte[] signPublicKey(PGPSecretKey secretKey, String secretKeyPass, PGPPublicKey keyToBeSigned, String notationName, String notationValue, boolean armor) throws Exception { OutputStream outputStream = new ByteArrayOutputStream(); if (armor) { outputStream = new ArmoredOutputStream(outputStream); } PGPPrivateKey pgpPrivateKey = secretKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("SC").build(secretKeyPass.toCharArray())); PGPSignatureGenerator pgpSignatureGenerator = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1).setProvider("SC")); pgpSignatureGenerator.init(PGPSignature.DIRECT_KEY, pgpPrivateKey); BCPGOutputStream bcpgOutputStream = new BCPGOutputStream(outputStream); pgpSignatureGenerator.generateOnePassVersion(false).encode(bcpgOutputStream); PGPSignatureSubpacketGenerator pgpSignatureSubpacketGenerator = new PGPSignatureSubpacketGenerator(); pgpSignatureSubpacketGenerator.setNotationData(true, true, notationName, notationValue); PGPSignatureSubpacketVector packetVector = pgpSignatureSubpacketGenerator.generate(); pgpSignatureGenerator.setHashedSubpackets(packetVector); bcpgOutputStream.flush(); if (armor) { outputStream.close(); } return PGPPublicKey.addCertification(keyToBeSigned, pgpSignatureGenerator.generate()).getEncoded(); } private void makeAlertDialog(String title, String message) { final Intent intent = new Intent(this, ScanActivity.class); AlertDialog.Builder builder = new AlertDialog.Builder(SignActivity.this) .setTitle(title) .setMessage(message) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); startActivity(intent); finish(); } }); builder.show(); } @Override public void onBackPressed() { Intent intent = new Intent(this, ScanActivity.class); startActivity(intent); finish(); } }
package org.apache.log4j.rule; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; /** * An abstract Rule class that provides the PropertyChange support plumbing. * * @author Paul Smith <psmith@apache.org> * @author Scott Deboy <sdeboy@apache.org> */ public abstract class AbstractRule implements Rule, Serializable { static final long serialVersionUID = -2844288145563025172L; private PropertyChangeSupport propertySupport = new PropertyChangeSupport(this); public void addPropertyChangeListener(PropertyChangeListener l) { propertySupport.addPropertyChangeListener(l); } public void removePropertyChangeListener(PropertyChangeListener l) { propertySupport.removePropertyChangeListener(l); } protected void firePropertyChange( String propertyName, Object oldVal, Object newVal) { propertySupport.firePropertyChange(propertyName, oldVal, newVal); } /** * @param evt */ public void firePropertyChange(PropertyChangeEvent evt) { propertySupport.firePropertyChange(evt); } }
package org.cojen.tupl; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.junit.*; import static org.junit.Assert.*; import org.cojen.tupl.ext.RecoveryHandler; import static org.cojen.tupl.TestUtils.*; /** * Tests for the Transaction.prepare method. * * @author Brian S O'Neill */ public class TxnPrepareTest { public static void main(String[] args) throws Exception { org.junit.runner.JUnitCore.main(TxnPrepareTest.class.getName()); } @After public void teardown() throws Exception { deleteTempDatabases(getClass()); } protected DatabaseConfig newConfig(RecoveryHandler handler) { return new DatabaseConfig() .recoveryHandler(handler) .directPageAccess(false) .lockTimeout(1000, TimeUnit.MILLISECONDS) .checkpointRate(-1, null); } protected Database newTempDatabase(DatabaseConfig config) throws Exception { return TestUtils.newTempDatabase(getClass(), config); } @Test public void noHandler() throws Exception { Database db = newTempDatabase(newConfig(null)); Transaction txn = db.newTransaction(); try { txn.prepare(); fail(); } catch (IllegalStateException e) { } } @Test public void noRedo() throws Exception { try { Transaction.BOGUS.prepare(); fail(); } catch (IllegalStateException e) { } RecoveryHandler handler = new RecoveryHandler() { public void init(Database db) {} public void recover(Transaction txn) {} }; Database db = newTempDatabase(newConfig(handler)); Transaction txn = db.newTransaction(); txn.durabilityMode(DurabilityMode.NO_REDO); try { txn.prepare(); fail(); } catch (IllegalStateException e) { } } // Test transaction recovery from just the redo log... @Test public void basicRedoRecoveryNoAction() throws Exception { basicRecovery("redo", "none"); } @Test public void basicRedoRecoveryReset() throws Exception { basicRecovery("redo", "reset"); } @Test public void basicRedoRecoveryModifyReset() throws Exception { basicRecovery("redo", "modify-reset"); } @Test public void basicRedoRecoveryCommit() throws Exception { basicRecovery("redo", "commit"); } @Test public void basicRedoRecoveryModifyCommit() throws Exception { basicRecovery("redo", "modify-commit"); } @Test public void basicRedoRecoverySticky() throws Exception { basicRecovery("redo", "sticky"); } // Test transaction recovery from just the undo log... @Test public void basicUndoRecoveryNoAction() throws Exception { basicRecovery("undo", "none"); } @Test public void basicUndoRecoveryReset() throws Exception { basicRecovery("undo", "reset"); } @Test public void basicUndoRecoveryModifyReset() throws Exception { basicRecovery("undo", "modify-reset"); } @Test public void basicUndoRecoveryCommit() throws Exception { basicRecovery("undo", "commit"); } @Test public void basicUndoRecoveryModifyCommit() throws Exception { basicRecovery("undo", "modify-commit"); } @Test public void basicUndoRecoverySticky() throws Exception { basicRecovery("undo", "sticky"); } // Test transaction recovery from the redo and undo logs... @Test public void basicRedoUndoRecoveryNoAction() throws Exception { basicRecovery("redo-undo", "none"); } @Test public void basicRedoUndoRecoveryReset() throws Exception { basicRecovery("redo-undo", "reset"); } @Test public void basicRedoUndoRecoveryModifyReset() throws Exception { basicRecovery("redo-undo", "modify-reset"); } @Test public void basicRedoUndoRecoveryCommit() throws Exception { basicRecovery("redo-undo", "commit"); } @Test public void basicRedoUndoRecoveryModifyCommit() throws Exception { basicRecovery("redo-undo", "modify-commit"); } @Test public void basicRedoUndoRecoverySticky() throws Exception { basicRecovery("redo-undo", "sticky"); } private void basicRecovery(String recoveryType, String recoveryAction) throws Exception { byte[] key1 = "key-1".getBytes(); byte[] key2 = "key-2".getBytes(); class Recovered { final long mTxnId; final Transaction mTxn; Recovered(Transaction txn) { // Capture the transaction id before the transaction is reset. mTxnId = txn.getId(); mTxn = txn; } } BlockingQueue<Recovered> recoveredQueue = new LinkedBlockingQueue<>(); RecoveryHandler handler = new RecoveryHandler() { private Database db; @Override public void init(Database db) { this.db = db; } @Override public void recover(Transaction txn) throws IOException { recoveredQueue.add(new Recovered(txn)); switch (recoveryAction) { default: // Leak the transaction and keep the locks. break; case "modify-reset": db.findIndex("test1").store(txn, key1, "modified-1".getBytes()); db.findIndex("test2").store(txn, key2, "modified-2".getBytes()); // Fallthrough to the next case to reset. case "reset": txn.reset(); break; case "modify-commit": db.findIndex("test1").store(txn, key1, "modified-1".getBytes()); db.findIndex("test2").store(txn, key2, "modified-2".getBytes()); // Fallthrough to the next case to commit. case "commit": txn.commit(); break; } } }; DatabaseConfig config = newConfig(handler); Database db = newTempDatabase(config); long txnId; { Index ix1 = db.openIndex("test1"); Index ix2 = db.openIndex("test2"); ix1.store(null, key1, "v1".getBytes()); ix2.store(null, key2, "v2".getBytes()); Transaction txn = db.newTransaction(); ix1.store(txn, key1, "value-1".getBytes()); if ("redo-undo".equals(recoveryType)) { db.checkpoint(); // Suppress later assertion. recoveryType = "redo"; } ix2.store(txn, key2, "value-2".getBytes()); if ("undo".equals(recoveryType)) { db.checkpoint(); } else if (!"redo".equals(recoveryType)) { fail("Unknown recovery type: " + recoveryType); } txnId = txn.getId(); txn.prepare(); } for (int i=0; i<3; i++) { db = reopenTempDatabase(getClass(), db, config); Recovered recovered = recoveredQueue.take(); assertEquals(txnId, recovered.mTxnId); assertTrue(recoveredQueue.isEmpty()); Index ix1 = db.openIndex("test1"); Index ix2 = db.openIndex("test2"); switch (recoveryAction) { default: fail("Unknown recovery action: " + recoveryAction); break; case "none": case "sticky": // Locks are retained. try { ix1.load(null, key1); fail(); } catch (LockTimeoutException e) { // Expected. } try { ix2.load(null, key2); fail(); } catch (LockTimeoutException e) { // Expected. } if ("sticky".equals(recoveryAction)) { break; } recovered.mTxn.reset(); // Fallthrough to the next case and verify rollback. case "reset": case "modify-reset": // Everything was rolled back. fastAssertArrayEquals("v1".getBytes(), ix1.load(null, key1)); fastAssertArrayEquals("v2".getBytes(), ix2.load(null, key2)); break; case "modify-commit": // Everything was modified and committed. fastAssertArrayEquals("modified-1".getBytes(), ix1.load(null, key1)); fastAssertArrayEquals("modified-2".getBytes(), ix2.load(null, key2)); break; case "commit": // Everything was committed. fastAssertArrayEquals("value-1".getBytes(), ix1.load(null, key1)); fastAssertArrayEquals("value-2".getBytes(), ix2.load(null, key2)); break; } if (!"sticky".equals(recoveryAction)) { break; } // Transaction should stick around each time the database is reopened. } } @Test public void basicMix() throws Exception { // Test that unprepared transactions don't get passed to the recover handler, testing // also with multiple recovered transactions. BlockingQueue<Transaction> recovered = new LinkedBlockingQueue<>(); RecoveryHandler handler = new RecoveryHandler() { @Override public void init(Database db) { } @Override public void recover(Transaction txn) { recovered.add(txn); } }; DatabaseConfig config = newConfig(handler); Database db = newTempDatabase(config); Index ix = db.openIndex("test"); // Should rollback and not be passed to the handler. Transaction txn1 = db.newTransaction(); ix.store(txn1, "key-1".getBytes(), "value-1".getBytes()); // Should be passed to the handler. Transaction txn2 = db.newTransaction(); ix.store(txn2, "key-2".getBytes(), "value-2".getBytes()); txn2.prepare(); // Should be passed to the handler. Transaction txn3 = db.newTransaction(); ix.store(txn3, "key-3".getBytes(), "value-3".getBytes()); txn3.prepare(); // Should rollback and not be passed to the handler. Transaction txn4 = db.newTransaction(); ix.store(txn4, "key-4".getBytes(), "value-4".getBytes()); // Should commit and not be passed to the handler. Transaction txn5 = db.newTransaction(); ix.store(txn5, "key-5".getBytes(), "value-5".getBytes()); txn5.prepare(); txn5.commit(); // Should rollback and not be passed to the handler. Transaction txn6 = db.newTransaction(); ix.store(txn6, "key-6".getBytes(), "value-6".getBytes()); txn6.prepare(); txn6.exit(); db = reopenTempDatabase(getClass(), db, config); ix = db.openIndex("test"); Transaction t1 = recovered.take(); Transaction t2 = recovered.take(); assertTrue(recovered.isEmpty()); // Transactions can be recovered in any order. if (t1.getId() == txn2.getId()) { assertEquals(t2.getId(), txn3.getId()); } else { assertEquals(t1.getId(), txn3.getId()); assertEquals(t2.getId(), txn2.getId()); } // Rollback of txn1, txn4, and txn6. assertNull(ix.load(null, "key-1".getBytes())); assertNull(ix.load(null, "key-4".getBytes())); assertNull(ix.load(null, "key-6".getBytes())); // Commit of txn5. fastAssertArrayEquals("value-5".getBytes(), ix.load(null, "key-5".getBytes())); // Recovered transactions are still locked. try { ix.load(null, "key-2".getBytes()); fail(); } catch (LockTimeoutException e) { } try { ix.load(null, "key-3".getBytes()); fail(); } catch (LockTimeoutException e) { } } @Test public void reopenNoHandler() throws Exception { // When database is reopened without a recovery handler, the recovered transactions // aren't lost. RecoveryHandler handler = new RecoveryHandler() { @Override public void init(Database db) { } @Override public void recover(Transaction txn) throws IOException { txn.commit(); } }; DatabaseConfig config = newConfig(handler); Database db = newTempDatabase(config); Index ix = db.openIndex("test"); Transaction txn = db.newTransaction(); byte[] key = "hello".getBytes(); ix.store(txn, key, "world".getBytes()); txn.prepare(); // Reopen without the handler. config.recoveryHandler(null); db = reopenTempDatabase(getClass(), db, config); // Still locked. ix = db.openIndex("test"); txn = db.newTransaction(); assertEquals(LockResult.TIMED_OUT_LOCK, ix.tryLockShared(txn, key, 0)); txn.reset(); // Reopen with the handler installed. config.recoveryHandler(handler); db = reopenTempDatabase(getClass(), db, config); // Verify that the handler has committed the recovereed transaction. ix = db.openIndex("test"); fastAssertArrayEquals("world".getBytes(), ix.load(null, key)); } }
package io.ichi_go.ichigo; import android.content.Intent; import android.support.v4.app.NavUtils; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import io.ichi_go.ichigo.data.model.Event; public class DisplayEventActivity extends ActionBarActivity { private Event currentEvent; private static final String TAG = "ViewEventActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_event); Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar); toolbar.setTitle("View an Event"); setSupportActionBar(toolbar); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Intent i = getIntent(); currentEvent = (Event) i.getParcelableExtra("currentEvent"); TextView displayName = (TextView) findViewById(R.id.display_event_name); TextView displayDescription = (TextView) findViewById(R.id.display_description); displayName.setText(currentEvent.getName()); displayDescription.setText(currentEvent.getDescription()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_new_event, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } if (id == android.R.id.home) { NavUtils.navigateUpFromSameTask(this); } return super.onOptionsItemSelected(item); } public void editEvent(View v) { if (v == findViewById(R.id.edit_event_button)) { Log.d(TAG, "Participant wants to edit the event"); } } public void deleteEvent(View v) { if (v == findViewById(R.id.delete_event_button)) { Log.d(TAG, "Participant wants to delete the event"); } } }
package org.ethereum.net; import static org.junit.Assert.*; import java.math.BigInteger; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import org.ethereum.core.Block; import org.ethereum.core.Transaction; import org.ethereum.crypto.ECKey; import org.ethereum.crypto.HashUtil; import org.ethereum.net.client.PeerData; import org.ethereum.net.message.BlocksMessage; import org.ethereum.net.message.DisconnectMessage; import org.ethereum.net.message.GetChainMessage; import org.ethereum.net.message.HelloMessage; import org.ethereum.net.message.NotInChainMessage; import org.ethereum.net.message.PeersMessage; import org.ethereum.net.message.ReasonCode; import org.ethereum.net.message.TransactionsMessage; import org.ethereum.util.ByteUtil; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import org.junit.Test; import org.spongycastle.util.encoders.Hex; public class MessagesTest { /* HELLO_MESSAGE */ @Test /* HelloMessage 1 */ public void test_1(){ String helloMessageRaw = "F8 77 80 0C 80 AD 45 74 " + "68 65 72 65 75 6D 28 2B 2B 29 2F 5A 65 72 6F 47 " + "6F 78 2F 76 30 2E 35 2E 31 2F 6E 63 75 72 73 65 " + "73 2F 4C 69 6E 75 78 2F 67 2B 2B 07 82 76 5F B8 " + "40 D8 83 3B 83 56 0E 0B 12 17 0E 91 69 DC 43 78 " + "42 23 A5 98 42 DE 23 59 E6 D0 3D B3 4C 30 A9 66 " + "C2 DE 3B 4B 25 52 FB 0D 75 95 A1 85 D5 58 F2 E6 " + "69 B5 95 67 4F 52 17 C9 96 EE 14 88 84 82 8B E0 FD"; byte[] payload = Hex.decode(helloMessageRaw); RLPList rlpList = RLP.decode2(payload); HelloMessage helloMessage = new HelloMessage(rlpList); helloMessage.parseRLP(); System.out.println(helloMessage); assertEquals(12, helloMessage.getProtocolVersion()); assertEquals(0, helloMessage.getNetworkId()); assertEquals("Ethereum(++)/ZeroGox/v0.5.1/ncurses/Linux/g++", helloMessage.getClientId()); assertEquals(7, helloMessage.getCapabilities()); assertEquals(30303, helloMessage.getPeerPort()); assertEquals( "D8833B83560E0B12170E9169DC43784223A59842DE2359E6D03DB34C30A966C2DE3B4B2552FB0D7595A185D558F2E669B595674F5217C996EE148884828BE0FD", Hex.toHexString(helloMessage.getPeerId()).toUpperCase() ); } @Test /* HelloMessage 2 */ public void test_2() { String helloMessageRaw = "F87F800B80B5457468657265756D282B2B292F76302E342E332F4554485F4255494C445F545950452F4554485F4255494C445F504C4154464F524D0782765FB840E02B18FBA6B887FB9258469C3AF8E445CC9AE2B5386CAC5F60C4170F822086224E3876555C745A7EC8AC181C7F9701776D94A779604EA12651DE5F4A748D29E1"; byte[] payload = Hex.decode(helloMessageRaw); RLPList rlpList = RLP.decode2(payload); HelloMessage helloMessage = new HelloMessage(rlpList); helloMessage.parseRLP(); System.out.println(helloMessage); assertEquals(11, helloMessage.getProtocolVersion()); assertEquals(0, helloMessage.getNetworkId()); assertEquals("Ethereum(++)/v0.4.3/ETH_BUILD_TYPE/ETH_BUILD_PLATFORM", helloMessage.getClientId()); assertEquals(7, helloMessage.getCapabilities()); assertEquals(30303, helloMessage.getPeerPort()); assertEquals( "E02B18FBA6B887FB9258469C3AF8E445CC9AE2B5386CAC5F60C4170F822086224E3876555C745A7EC8AC181C7F9701776D94A779604EA12651DE5F4A748D29E1", Hex.toHexString(helloMessage.getPeerId()).toUpperCase() ); } /* DISCONNECT_MESSAGE */ @Test /* DisconnectMessage 1 */ public void test_3(){ String disconnectMessageRaw = "C20100"; byte[] payload = Hex.decode(disconnectMessageRaw); RLPList rlpList = RLP.decode2(payload); DisconnectMessage disconnectMessage = new DisconnectMessage(rlpList); System.out.println(disconnectMessage); assertEquals(disconnectMessage.getReason(), ReasonCode.DISCONNECT_REQUESTED); } @Test /* DisconnectMessage 2 */ public void test_4(){ String disconnectMessageRaw = "C20101"; byte[] payload = Hex.decode(disconnectMessageRaw); RLPList rlpList = RLP.decode2(payload); DisconnectMessage disconnectMessage = new DisconnectMessage(rlpList); System.out.println(disconnectMessage); assertEquals(disconnectMessage.getReason(), ReasonCode.TCP_ERROR); } /* PEERS */ @Test /* PeersMessage 1*/ public void test_5(){ String peersMessageRaw = "F902BC11F84CC65381AC81E24F82765FB84033F506917503D16ECA1574F73D427BB6BC8725BED28542151E966C71FF5E9EE2EB0B09A8A6D7F6BC9E3F58F407F3DEDF174C4B6D6426973FB874E18F9ACB2BB6F84DC781C87681AB81BE82765FB840370A33EE6716C22E8AB13FF666C2389BDF0947F2FD8C15F3ABA5D545A0B78F7A8ABB95FD575073BE596D237038149A3B71E3A8F30B55AE70ED0189803FD62F24F84CC66A81A80E81F982765FB84052C1D33B5635C25504AD3985A79BEE3FF26CA5A17D351B8775E7ACEBAB1365624C9EE3CDFF843AFD07B235D8569196C781115E8DCAEF93E0383B20CFA64766D0F84AC455417E2D82765FB84082A8A5831D3B4FB76CF130CDC8A2B162A85D005D82A1DCC9B73239035EADE6347EDE2FFC86571ABE348EA38699CE886AA3D425FE58182C433434AB4CFD7B5B88F84CC6443081AD81A3827A51B840A5FD77C0D432FBFA3317084914C2E8A8821E4BA1DCBA44961FF7480E6DB608789CAB6291416360EA8CDC26B0D2F0877C50E89A70C1BCF5D6DD8B182E0A9E37D3F84AC436481F3782765FB840CE73660A06626C1B3FDA7B18EF7BA3CE17B6BF604F9541D3C6C654B7AE88B239407F659C78F419025D785727ED017B6ADD21952D7E12007373E321DBC31824BAF84AC455417E2D82765FB840CE73F1F1F1F16C1B3FDA7B18EF7BA3CE17B6F1F1F1F141D3C6C654B7AE88B239407FF1F1F1F119025D785727ED017B6ADD21F1F1F1F1000001E321DBC31824BAF84CC66B81AA3981F782765FB840E02B18FBA6B887FB9258469C3AF8E445CC9AE2B5386CAC5F60C4170F822086224E3876555C745A7EC8AC181C7F9701776D94A779604EA12651DE5F4A748D29E1F84EC881BF81B181D1819F82765FB840EFDFAE4BC66C2FBAAA70FEC4E764552256D3E15B143FA8F9EF278A5E042221BA0D4E8688DD4BA9582ABAC97D81B9418E50391204E9335E8E37CD16B7D95193A7"; byte[] payload = Hex.decode(peersMessageRaw); RLPList rlpList = RLP.decode2(payload); PeersMessage peersMessage= new PeersMessage(rlpList); System.out.println(peersMessage); assertEquals(9, peersMessage.getPeers().size()); PeerData peerData = peersMessage.getPeers().get(3); assertEquals("/85.65.126.45", peerData.getInetAddress().toString()); assertEquals(30303, peerData.getPort()); assertEquals("82A8A5831D3B4FB76CF130CDC8A2B162A85D005D82A1DCC9B73239035EADE6347EDE2FFC86571ABE348EA38699CE886AA3D425FE58182C433434AB4CFD7B5B88", Hex.toHexString( peerData.getPeerId() ).toUpperCase()); } @Test /* PeersMessage 2 */ public void test_6(){ String peersMessageRaw = "F9175011F84CC681836881FC0482765FB840077E537A8B3673E8F1B625DBCC902EA7D4CED9402E4664E873679512CC2360698E53425652A04624FCF78CDBA1A3233087A919A34D11AEDACEEEB7D833FCBF26F84CC66381E75881AF82765FB8400AB2CDE83A098403DDC2EA5414740D8A0193E449C96E112419967ABC62EB17CDCED77AE0AB075E04F7DDDCD43FB9048BE53206A040620BDE26CB743FA312319FF84BC545818F165582765FB84015D678DBB6C9F241133DD2F5EAC96B1B8308C556037D83F63A3729DDE4C3F84ED8491C7C645827DC54CE32AB8A759EE04EA079F2703F352BBA24ED6249B47CA5F84EC881BF81B181D1819F82765FB84019549FBE60B8A8D8188C9F1741325C92A5CE2226F23B40053FB68D90ED4DD551C891952ABDB9A894713EE9A7B037D06822F8EBC68F53326D9559BFE8277BE4E9F84DC781CF81DB45819A82765FB84019C33DA7031CFF177EFA842FAA3D31BD83E1764EC610F236944A9F8A21C1C51A04F47F6B5FC3EFE65CAF369443635AFC58D8F5D4E2F12AF9EEEC3C6E30BF0A2BF84CC6443081AD81A382765FB8401E59C282081294808497AE7A7E976798C42B8BCCE13C9D8B0ECF8AFECDB5DFD4EFA8770FC0D1F7DE63C91640E7E8B4358C9E3ED0F3D6C98620AD7EA42418C9ECF84BC51F12819E4882765FB8401F68C075C1D87BC04765430FDFB1E5D00F1B784ED6BE721E4CAFF7BEB57B4B217B95DA19B5EC66045868B39AAC2E0876CF80F0B68D0FA20BDB9036BEAA7061EAF84CC681BF81EA393782765FB84021780C55B47DB4B11467B5F55B0B555E0887CE36FBD975E224B1C70EAC7AB8E8C2DB37F0A48B90FFDD5A379ADA99B6A0F6429C4A53C25558191A682636AEF4F2F84CC6443081AD81A382765FB8402315CB7CF49B8EAB212C5A45790B50797739738F5F733439B190119737EE8C09BC723794712AA82F2670BC581AB0757EF23137AC0FDF0F8C8965E7DD6BA79F8CF84AC455417E2D82765FB8402A38EA5D9A7EFD7FFFC0A81D8EA7ED28311C4012BBAB1407C8DAD2685129E042172734A328E8907F9054B8225FE77041D8A486A97976D2837242AB6C8C5905E4F84CC681836881FC0482765FB840324DD936384D8C0DDEFDE04BA7402998ABBD63D79C0BF8586B3DD2C7DBF6C91EB80A7B6DE8F16A50044F149C7B39AAFB9C3AD7F2CAA40355AAB09888186FCCA2F84CC65381AC81E24F82765FB84033F506917503D16ECA1574F73D427BB6BC8725BED28542151E966C71FF5E9EE2EB0B09A8A6D7F6BC9E3F58F407F3DEDF174C4B6D6426973FB874E18F9ACB2BB6F84DC781C87681AB81BE82765FB840370A33EE6716C22E8AB13FF666C2389BDF0947F2FD8C15F3ABA5D545A0B78F7A8ABB95FD575073BE596D237038149A3B71E3A8F30B55AE70ED0189803FD62F24F84CC6443081AD81A382765FB840394245C0991633ED060BAFB9646853D344188B804FE37E25A5BCAC44ED443A84A68B3AAF155EFE4861E84B4B515F9A5DECDBD7DAE98192D7A320A792C7D4DFAFF84DC75681B781E781CD82765FB840398650F67B2292939DE34C0EAEB9141F9484A0FB173FA33F81A1F7315D0EB77BDE3A76C38636FAE66FA14BF2AFDFD63E60ABD40E29B02A914E65DE5789983FD4F84CC64481B981EA4082765FB8403A15587A1C3ADABF0291B307F71B2C04D198AAE36B834995D3305DFF42F1AB86F483AE129E9203FBC6EF2187C8621EDD18F61D53EAA5B587FFDEA4D926489038F84DC781CF81DB45819A82765FB8403B1462040EA778E3F75E65CE2453418A662E6212C9F65B02EAB58D22B287E45053BDE5EBF060960CBFA0D9DC85BF51BA7AA1F2CAA2C13682D93277641D60DBEBF84CC66A81A80E81F982765FB8403ECC97AB15D22F7B9EDF19C04CE3B6095FA2504214002B35989C6F81EE4B961CC2A899C49415C914E313908340047D1D3B25D74F5B9C85A06AFA2659A539992EF84BC52E0481C10982765FB840407C22003F3BBAA6CBEB8E4B0AB7073073FEAB85182B405525F8BD283255043D713518F74748D92C43FBB99ECC7C3FBAB95D598006513AA8E59C48041C8B41C2F84BC5327E5681C282765FB840408C9324203BD8262FCE6506BA59DCDD567089B0EB9A5BB183477BABBF6163914ACDC7F495F8964D8AC12FE2401887B8CD8D97C0C9DCCFADDBB20A3C3147A789F84AC4266C4F6882765FB840423E4004DA2FA7500BC012C0674AA6571502C53AA4D91EFA6E2B5CB1E468C462CA3114A2E2EB0965B7044F9C9575965B47E47A41F13F1ADC03A2A4B342D7128DF84BC54081E7082D82765FB84042839375272C2F3DEADB28085D06055E353135C6C8D896097A1BC480C4884FD1604518CBDF731AC18F0984B7F02148E88290D13C224D82464314E2B5962E3F89F84BC581CB22640282765FB84043BFC2EBC291825D9EC00C636330235DCEDF3A623F4F08E49BCC1504D8E9B165F0A0FE976C1881455BB3051C7B604F64AC45C117C275C636F1A36ABFB11544FBF84DC73281AA81D881C882765FB84044CF19446CA465018E4DE6C60FC0DF529EBA250292EF7441E1DB59841C69F022F6092810C9A5A7F274F2F97C4BD6C76EADC064C7D6597CAEB17ED87CB257735FF84BC532819C5A5382765FB840461C9B54E91953C5BBC31C6712A917382BE67D60F75EB7F50651BEA3E594D0D19C2229D8F66ADB3F203F600038E7CC934DC92787FAC4392B9BFA7CBC786FD05BF84BC58186647D2982765FB84048353A0058E26448D94E59336CCA9D28A9374120DEF76C4BCCFEE18B0123E59192393A2EE3044D80E0EECBB09476BE62FDE1E874F93D05EA5C4A9A45C06E8FE1F84BC54E080581BB82765FB84048E8950949D4C00BCDBBE939C5BF078F2CBFF10884AF1660B1C322B9CAA3BA357BB4157FC6B0039AF9438DFE51EC278A47FCD3B726FA0A087D4C3C01A62F335EF84AC6584581C681C607B8404A0255FA4673FAA30FC5ABFD3C550BFDBC0D3C973D35F726463AF81C54A03281CFFF22C5F5965B38AC630152987757A31782478549C36F7C84CB4436BA79D6D9F84BC54081E7082D82765FB8404C7547AB4D541E10164CD3741F3476ED194B0AB9A136DFCAC3943F97358C9B0514142736CA2F170F125229057B473244A6230BF5471AD168188524B2B5CD8B7BF84CC6443081AD81A382765FB8404D5E4875D60EB4EEAFB6B2A7D3936ED3C9BC58ACAADE6A7F3C5F25598C20B364F12BEA2FB1DB3B2C2EF64785A47D6B6B5B103427CBAC0C88B18FE92A9F5393F8F84BC5520C81E35482765FB8404FD898627574D3E86B3F5A65C3EDC2E5DA84535926E4A28820B0038B19636E07DB5EB004D791F8041A006E33E108E4EC535499D128D8D9C5CAF6BBDC2204F76AF84CC66A81A80E81F982765FB84052C1D33B5635C25504AD3985A79BEE3FF26CA5A17D351B8775E7ACEBAB1365624C9EE3CDFF843AFD07B235D8569196C781115E8DCAEF93E0383B20CFA64766D0F84BC581B4202B0882765FB84053CCF25AB59409ECBB903D2EC3A9AA2EB39D7CC4C7DB7E6F68FD711A7CEBC606216DE737826DA42093E3E6521EE4770EB2D669DC4BF3546CC757C34012696EAEF84AC44C67374782765FB840600A77FB14E792C0C70DC4ADE382ED604362B978B19B94C4ED188338A1795D2DB45F7F223B66BAEBA391C59B5588B44EBAF71C7EB39755C27229C7FDE641BECEF84BC545818F165582765FB840634C1D314F4D0AE98A0A57D406091FC055E023F8A02800E93273BA34928D063877B7D5E7301ACBBEDA7BD4A7DFA3C3DBC840BB443E8863A6C514B82F2273A2DDF84BC56D2B819A4282765FB84069DD445F67C3BEF394F9549FDAE1623DBC20884A62FD5616DDBB49F84BA87E147CB8A50BA971D730C4621D0EB65133494E94FA5EA2E69C661F6B12E7ED2A8D4EF84BC518093D819B82765FB8406B5D4C35FFD1F5A198038A90834D29A1B88BE0D5EFCA08BC8A2D5881180B0B416BE00629AABE450A50828B8D1EE82D98F5528187EE67ED6E073BCEEFCDFB2BC9F84AC455417E2D82765FB8406CBB1ED536DC3858C1F063429BD3952A5D32EF8E11526CDFE72F41FEA1ACE960187C9975ABBC23783511C00F2698354747F905AAAC11DCD2B7478B3EAF327AC6F84BC54081E7082D82765FB8406EA28F64EA1CC3B6572544FD5BF743B0EAABE017F514730C897DA3C77F03C516F1E5F31D793B4BCE3CAA1DED56356D20B2EBB55A7066F41C25B7C3D56614E06BF84AC455417E2D82765FB84072532408E8BE6D5E2C9F650FB9C9F99650CC1FA062A4A4F2CFE4E6AE69CDD2E8B23ED14AFE66955C23FA048F3A976E3CE8169E505B6A89CC53D4FAC20C2A11BFF84DC77481FB81DD81FB82765FB84077B92DC86BC2599EEF46CAF2E84338165AE58971256A92CF0B802B6B510D9F690D1C0DA48A74C1A7C5FFFF46A267F5E3AB501D6F5E81E32EFCBB4EA4EC103CF3F84CC65281D94881A982765FB8407AEEA43360B9368B30E7F48286613FD1E3B0207FB71F0308D50412114463E77AB83027C0D40CADAAB8BBF612FC5B6967FA1C407329D47EC61FB0DC3DA1086832F84CC681A68193534F82765FB8407B3CDDE058D5B45D8DB2243660CFEA02E074EC213114C251D7C0C32D0403BB7AB47713D2492FF6C881CFC2AAC3F52CB269768C8968F3B6B18BAC9722D05331F6F84CC681B43881A23C82765FB840817219171552FE8DCF019EDDB90187FB0DE6A471456809698AB5251E6F498D8DF15C34CF1D86F4320689E458483657F04FA651407AFDBB2B2A91D5FBFCAD4FD6F84AC455417E2D82765FB84082A8A5831D3B4FB76CF130CDC8A2B162A85D005D82A1DCC9B73239035EADE6347EDE2FFC86571ABE348EA38699CE886AA3D425FE58182C433434AB4CFD7B5B88F84CC66A81A80E81F982765FB84087AB581BB97C212A2DA7EF0D6E105E41B55E4E42CBB6A1AF9A761A01CA8C65069AB4B5827E322CF2C5F59E7F592BE2A817C45AB641F5A9DD368963C73F9EE688F84CC65281D94881A982765FB8408C660DBC6D3DB0186AD10F05FD4F2F0643778EC514E8452A7550C630DA21171A29B1BB67C2E8E101EA1DB39743F3E78C4D2676A13D15515121515FC38B048F37F84CC66381E75881AF82765FB84094FE3D52A2894CEDC6B15424156EB8738A8441DD74BA9CED6664ED30A332A95B574D89262EA367FA900AE9706FB81A408287BDDEF3A9DD9FF44E3A41BC090FDCF84CC64D81B781903782765FB840951FAFCB6F521F0AA23BC58AF19CC40D6795124D89DC8E0CAF23369B67726A1BF6A7B4EF59CD983059B6A67C15F409903C96577CEDDACD89C7423A103C134E08F84DC781D5818181E60A82765FB840952114F110E8AC00DFEA5F050D955E764C7CBA8FB207C05A7AA5AE849168640A2B4E314391FC3A76795B3827055462639CFF4AE2D64AB80E95274428313E366AF84CC6584581C681C682765FB84096F347B096ED1630F474B97623E45E8D471B1D43C22F599607C8B2E3ED0D7B7905D8554AD399DBD739C76126404424D8DB0DC7D2B047C1A328AE27D40906C583F84CC681836881FC0482765FB8409A22C8FB1BD8BBD02F0E74ED9D3D55B0F5B09672BC43A2D47B1ED04238C1C32B6A657426525B15518236E9789B546A4A072A605E1373FE5B996BAEDC30359428F84BC5520C81E35482765FB8409B1A3A8D771B3D949CA394A88EB5DC29A953B02C81F017361FFC0AFE09ABCE3069171A87D474523687FCC9A9D32CC02CFAB4132256FEAABFE05F7AC747194E88F84BC54281D7781C82765FB8409FA7E55B2D98F1D744C76232E4FDA242FE9FD3D5743D16D3CAD2E548A07CB5AF06FE60EBAEB8C6095028179234DCDDD3CDCF1FCFE6EDAA2A53307FD103DA4AF0F84AC455417E2D82765FB840A01F834E9D1A613C3C747E561CAC19CB12D879C1A57420A49C23652B8F51288C8B111AA3888998B05E327F47A235C6A4A377F888E3005A2D4B03ECB7268608D3F84CC6443081AD81A3827A51B840A5FD77C0D432FBFA3317084914C2E8A8821E4BA1DCBA44961FF7480E6DB608789CAB6291416360EA8CDC26B0D2F0877C50E89A70C1BCF5D6DD8B182E0A9E37D3F84DC7818881A081983182765FB840AE31BD0254EE7D10B80FC90E74BA06BA761187DF3138A9799DE5828D0163524C44BAC7D2A9B5C41BE5BE8289A172361F0BA90410C94F579BF7EBD28F18AAA1CDF84AC455417E2D82765FB840BA3D216772CDC74558D2545624A2D62DCBCFD272305730C74643C7A7E819AFA6CDD82223E2B5501EB6D4EAE5DBF21E558C768ACAEC2C1CA10E74C4C87A574B53F84AC455417E2D82765FB840BDB49C01872D91BD1EA990BD2EDF16C48171A6067F9A6F7F48BFB194630B5AE9031B5DC263F59C66ADA444CB4E6F9DF62B3017CE612CAB7B53DA08D356F78D30F84CC66381E75881AF82765FB840C12BA91F95044D78EED1D3A9535EBD6471524418135EEB46AD5D5C6ECC2F5168B4AB3A062BB0742AEA65FFEA767FAB8DCC21783CB29BF32E2CD6222209FA71FDF84CC6443081AD81A3827A51B840C2E269E64AA8C9BE2D41812A48AFA2346BD41A1AB2E4646241AE3B8D0CCD41F2D682B15A025F759C0D955A6071D4E8EA7D4DE397D6E052230920113B6EB74C09F84AC44A4F177782765FB840C303B83F6A161F996736344480AE9D88FDC1D9C675BFACA888F70F24897265628209DA53741E03C0F65921F68F602DC9F334A3C45BCB92AF8544A6FB119BD887F84BC50C81FA611A82765FB840C76E7C157B7735511153D1F95081A144E088A989171F3D432CC5D8293ECE9CFAA483C032155D7B53656A6E33A3D75CD0624E09A2F949C156093DBAA83F1111F2F84BC5520C81E35482765FB840C7D5A3691A59599DE333489CBF8A47A7433E92C72706E13D94ED211296D35C97D8357D7E07B3858564D7268ED7AA097F37589C27770F90DD0B07635BE3F53364F84CC64E09819281B282765FB840C88197A82B0ACF0A872494D1DFAC9DE846DAA7DE08B240647A96BA72FBE08FD52B55C6C94514A47EC51BA49A975489EBC9383B48F5E240939068CE5836FF24F1F84BC581B4202B0882765FB840C9E039D8A8B9E435BEF2F45FC7CB7E788716E8C7AFC1BACC64E1246D2AB506D36073792AE696E41AD6BA0C8ABD2EC0D545B0757F94A9F3538280E56DB5F5D8ECF84BC54E6881A35182765FB840CA27683702A8E9BF3201656FF84A60D5B1DD814273993CF1A025B054454E40D53092F48518EE05BEAD4F18021F4F540C0B7C7D26EBA50EA4890B9E5E49A76C5FF84AC436481F3782765FB840CE73660A06626C1B3FDA7B18EF7BA3CE17B6BF604F9541D3C6C654B7AE88B239407F659C78F419025D785727ED017B6ADD21952D7E12007373E321DBC31824BAF84AC455417E2D82765FB840CE73F1F1F1F16C1B3FDA7B18EF7BA3CE17B6F1F1F1F141D3C6C654B7AE88B239407FF1F1F1F119025D785727ED017B6ADD21F1F1F1F1000001E321DBC31824BAF84BC549310781F382765FB840D553D2596461568CC7365D53F92F387FD39F10C4A9AC388EBFA1F59761F2DF215669B1C4A255DCC33E271573A01CBD1E12F0DF40C3DDC609C59F3E9A6E346EE1F84CC66B81AA3981F782765FB840E02B18FBA6B887FB9258469C3AF8E445CC9AE2B5386CAC5F60C4170F822086224E3876555C745A7EC8AC181C7F9701776D94A779604EA12651DE5F4A748D29E1F84CC64081E70A81D082765FB840E31115A76FA7FB2EFD3CFAF46AD00B05FC3498E1BAF1785DFFE6CA69913D256531D180564235FD3D3C10409CD11FC259CF7CFDA9B6BB253340412D82878F3BD3F84BC5415E31819782765FB840E5E8D8C2D762D21CA1E9BCEE8ADC53600F2D894097542666D6B5F41B23584B07F60901AB409DDF91E0CD2562DAFFF2CB0F221EB9F1156F781A5D9931A02A2E07F84CC65D818681C24982765FB840ECF3D13E7843E1B2537B742FA689912F7CFFB5D75E2CDD6732AAD1A3088F06066B435C0FA6D95C82A948AE0A1A0067D11A15668F70974299FD0F52CCD87D67DDF84EC881BF81B181D1819F82765FB840EFDFAE4BC66C2FBAAA70FEC4E764552256D3E15B143FA8F9EF278A5E042221BA0D4E8688DD4BA9582ABAC97D81B9418E50391204E9335E8E37CD16B7D95193A7F84BC5567C5281FE82765FB840F6155F1A60143B7D9D5D1A440D7D52FE6809F69E0C6F1E0024457E0D71DD88ADE3B13AAA940C89AC0610952B48BD832C42E343A13E61FFDB06010CFFC345E053F84CC66381E75881AF82765FB840FA568561B7D5288DF7A506C9BC1C9512AB396E68C46F0E62C21DC1AA584B844A8A7E944F6971303665FD37B138D9A5F637E672EDB98969664C4E7FD1C4126DEF"; byte[] payload = Hex.decode(peersMessageRaw); RLPList rlpList = RLP.decode2(payload); PeersMessage peersMessage= new PeersMessage(rlpList); System.out.println(peersMessage); assertEquals(77, peersMessage.getPeers().size()); PeerData peerData = peersMessage.getPeers().get(7); assertEquals("/191.234.57.55", peerData.getInetAddress().toString()); assertEquals(30303, peerData.getPort()); assertEquals("21780C55B47DB4B11467B5F55B0B555E0887CE36FBD975E224B1C70EAC7AB8E8C2DB37F0A48B90FFDD5A379ADA99B6A0F6429C4A53C25558191A682636AEF4F2", Hex.toHexString( peerData.getPeerId() ).toUpperCase()); peerData = peersMessage.getPeers().get(75); assertEquals("/86.124.82.254", peerData.getInetAddress().toString()); assertEquals(30303, peerData.getPort()); assertEquals("F6155F1A60143B7D9D5D1A440D7D52FE6809F69E0C6F1E0024457E0D71DD88ADE3B13AAA940C89AC0610952B48BD832C42E343A13E61FFDB06010CFFC345E053", Hex.toHexString( peerData.getPeerId() ).toUpperCase()); } @Test /* Peers msg parsing performance*/ public void test_7() throws UnknownHostException { long time1 = System.currentTimeMillis(); for (int i = 0; i < 20000; ++i){ String peersPacketRaw = "F9152E11F84CC681836881FC0482765FB840077E537A8B3673E8F1B625DBCC902EA7D4CED9402E4664E873679512CC2360698E53425652A04624FCF78CDBA1A3233087A919A34D11AEDACEEEB7D833FCBF26F84CC66381E75881AF82765FB8400AB2CDE83A098403DDC2EA5414740D8A0193E449C96E112419967ABC62EB17CDCED77AE0AB075E04F7DDDCD43FB9048BE53206A040620BDE26CB743FA312319FF84BC545818F165582765FB84015D678DBB6C9F241133DD2F5EAC96B1B8308C556037D83F63A3729DDE4C3F84ED8491C7C645827DC54CE32AB8A759EE04EA079F2703F352BBA24ED6249B47CA5F84DC781CF81DB45819A82765FB84019C33DA7031CFF177EFA842FAA3D31BD83E1764EC610F236944A9F8A21C1C51A04F47F6B5FC3EFE65CAF369443635AFC58D8F5D4E2F12AF9EEEC3C6E30BF0A2BF84CC6443081AD81A382765FB8401E59C282081294808497AE7A7E976798C42B8BCCE13C9D8B0ECF8AFECDB5DFD4EFA8770FC0D1F7DE63C91640E7E8B4358C9E3ED0F3D6C98620AD7EA42418C9ECF84BC51F12819E4882765FB8401F68C075C1D87BC04765430FDFB1E5D00F1B784ED6BE721E4CAFF7BEB57B4B217B95DA19B5EC66045868B39AAC2E0876CF80F0B68D0FA20BDB9036BEAA7061EAF84CC681BF81EA393782765FB84021780C55B47DB4B11467B5F55B0B555E0887CE36FBD975E224B1C70EAC7AB8E8C2DB37F0A48B90FFDD5A379ADA99B6A0F6429C4A53C25558191A682636AEF4F2F84CC6443081AD81A382765FB8402315CB7CF49B8EAB212C5A45790B50797739738F5F733439B190119737EE8C09BC723794712AA82F2670BC581AB0757EF23137AC0FDF0F8C8965E7DD6BA79F8CF84EC881BF81B181D1819F82765FB840249A3641E5A8D08E41A5CFC8DAE11F1761254F4FD47D9B13338DB8E6E3729E6F2AC9EC097A5C809684D62A41E6DFC2FFF72DC3DBD97EA26132BB97640565BB0CF84AC455417E2D82765FB8402A38EA5D9A7EFD7FFFC0A81D8EA7ED28311C4012BBAB1407C8DAD2685129E042172734A328E8907F9054B8225FE77041D8A486A97976D2837242AB6C8C5905E4F84CC66A81A80E81F982765FB8402CB30D5314ECE47E5B43DBD27A12CAD9A55CF57DD6EFB467151FEE95B9217B8BE2AB6214E07EFD9535660AE9C4FB932D2947ED6EDCD54F11081BA0FF7F30CE42F84CC681836881FC0482765FB840324DD936384D8C0DDEFDE04BA7402998ABBD63D79C0BF8586B3DD2C7DBF6C91EB80A7B6DE8F16A50044F149C7B39AAFB9C3AD7F2CAA40355AAB09888186FCCA2F84CC6443081AD81A382765FB840394245C0991633ED060BAFB9646853D344188B804FE37E25A5BCAC44ED443A84A68B3AAF155EFE4861E84B4B515F9A5DECDBD7DAE98192D7A320A792C7D4DFAFF84DC75681B781E781CD82765FB840398650F67B2292939DE34C0EAEB9141F9484A0FB173FA33F81A1F7315D0EB77BDE3A76C38636FAE66FA14BF2AFDFD63E60ABD40E29B02A914E65DE5789983FD4F84CC64481B981EA4082765FB8403A15587A1C3ADABF0291B307F71B2C04D198AAE36B834995D3305DFF42F1AB86F483AE129E9203FBC6EF2187C8621EDD18F61D53EAA5B587FFDEA4D926489038F84DC781CF81DB45819A82765FB8403B1462040EA778E3F75E65CE2453418A662E6212C9F65B02EAB58D22B287E45053BDE5EBF060960CBFA0D9DC85BF51BA7AA1F2CAA2C13682D93277641D60DBEBF84CC66A81A80E81F982765FB8403ECC97AB15D22F7B9EDF19C04CE3B6095FA2504214002B35989C6F81EE4B961CC2A899C49415C914E313908340047D1D3B25D74F5B9C85A06AFA2659A539992EF84BC52E0481C10982765FB840407C22003F3BBAA6CBEB8E4B0AB7073073FEAB85182B405525F8BD283255043D713518F74748D92C43FBB99ECC7C3FBAB95D598006513AA8E59C48041C8B41C2F84BC5327E5681C282765FB840408C9324203BD8262FCE6506BA59DCDD567089B0EB9A5BB183477BABBF6163914ACDC7F495F8964D8AC12FE2401887B8CD8D97C0C9DCCFADDBB20A3C3147A789F84AC4266C4F6882765FB840423E4004DA2FA7500BC012C0674AA6571502C53AA4D91EFA6E2B5CB1E468C462CA3114A2E2EB0965B7044F9C9575965B47E47A41F13F1ADC03A2A4B342D7128DF84BC54081E7082D82765FB84042839375272C2F3DEADB28085D06055E353135C6C8D896097A1BC480C4884FD1604518CBDF731AC18F0984B7F02148E88290D13C224D82464314E2B5962E3F89F84DC73281AA81D881C882765FB84044CF19446CA465018E4DE6C60FC0DF529EBA250292EF7441E1DB59841C69F022F6092810C9A5A7F274F2F97C4BD6C76EADC064C7D6597CAEB17ED87CB257735FF84BC532819C5A5382765FB840461C9B54E91953C5BBC31C6712A917382BE67D60F75EB7F50651BEA3E594D0D19C2229D8F66ADB3F203F600038E7CC934DC92787FAC4392B9BFA7CBC786FD05BF84BC58186647D2982765FB84048353A0058E26448D94E59336CCA9D28A9374120DEF76C4BCCFEE18B0123E59192393A2EE3044D80E0EECBB09476BE62FDE1E874F93D05EA5C4A9A45C06E8FE1F84BC54E080581BB82765FB84048E8950949D4C00BCDBBE939C5BF078F2CBFF10884AF1660B1C322B9CAA3BA357BB4157FC6B0039AF9438DFE51EC278A47FCD3B726FA0A087D4C3C01A62F335EF84AC6584581C681C607B8404A0255FA4673FAA30FC5ABFD3C550BFDBC0D3C973D35F726463AF81C54A03281CFFF22C5F5965B38AC630152987757A31782478549C36F7C84CB4436BA79D6D9F84BC54081E7082D82765FB8404C7547AB4D541E10164CD3741F3476ED194B0AB9A136DFCAC3943F97358C9B0514142736CA2F170F125229057B473244A6230BF5471AD168188524B2B5CD8B7BF84CC6443081AD81A382765FB8404D5E4875D60EB4EEAFB6B2A7D3936ED3C9BC58ACAADE6A7F3C5F25598C20B364F12BEA2FB1DB3B2C2EF64785A47D6B6B5B103427CBAC0C88B18FE92A9F5393F8F84BC5520C81E35482765FB8404FD898627574D3E86B3F5A65C3EDC2E5DA84535926E4A28820B0038B19636E07DB5EB004D791F8041A006E33E108E4EC535499D128D8D9C5CAF6BBDC2204F76AF84BC581B4202B0882765FB84053CCF25AB59409ECBB903D2EC3A9AA2EB39D7CC4C7DB7E6F68FD711A7CEBC606216DE737826DA42093E3E6521EE4770EB2D669DC4BF3546CC757C34012696EAEF84AC44C67374782765FB840600A77FB14E792C0C70DC4ADE382ED604362B978B19B94C4ED188338A1795D2DB45F7F223B66BAEBA391C59B5588B44EBAF71C7EB39755C27229C7FDE641BECEF84BC56D2B819A4282765FB84069DD445F67C3BEF394F9549FDAE1623DBC20884A62FD5616DDBB49F84BA87E147CB8A50BA971D730C4621D0EB65133494E94FA5EA2E69C661F6B12E7ED2A8D4EF84BC518093D819B82765FB8406B5D4C35FFD1F5A198038A90834D29A1B88BE0D5EFCA08BC8A2D5881180B0B416BE00629AABE450A50828B8D1EE82D98F5528187EE67ED6E073BCEEFCDFB2BC9F84AC455417E2D82765FB8406CBB1ED536DC3858C1F063429BD3952A5D32EF8E11526CDFE72F41FEA1ACE960187C9975ABBC23783511C00F2698354747F905AAAC11DCD2B7478B3EAF327AC6F84BC54081E7082D82765FB8406EA28F64EA1CC3B6572544FD5BF743B0EAABE017F514730C897DA3C77F03C516F1E5F31D793B4BCE3CAA1DED56356D20B2EBB55A7066F41C25B7C3D56614E06BF84AC455417E2D82765FB84072532408E8BE6D5E2C9F650FB9C9F99650CC1FA062A4A4F2CFE4E6AE69CDD2E8B23ED14AFE66955C23FA048F3A976E3CE8169E505B6A89CC53D4FAC20C2A11BFF84CC65281D94881A982765FB8407AEEA43360B9368B30E7F48286613FD1E3B0207FB71F0308D50412114463E77AB83027C0D40CADAAB8BBF612FC5B6967FA1C407329D47EC61FB0DC3DA1086832F84CC681A68193534F82765FB8407B3CDDE058D5B45D8DB2243660CFEA02E074EC213114C251D7C0C32D0403BB7AB47713D2492FF6C881CFC2AAC3F52CB269768C8968F3B6B18BAC9722D05331F6F84CC66A81A80E81F982765FB84087AB581BB97C212A2DA7EF0D6E105E41B55E4E42CBB6A1AF9A761A01CA8C65069AB4B5827E322CF2C5F59E7F592BE2A817C45AB641F5A9DD368963C73F9EE688F84CC65281D94881A982765FB8408C660DBC6D3DB0186AD10F05FD4F2F0643778EC514E8452A7550C630DA21171A29B1BB67C2E8E101EA1DB39743F3E78C4D2676A13D15515121515FC38B048F37F84CC66381E75881AF82765FB84094FE3D52A2894CEDC6B15424156EB8738A8441DD74BA9CED6664ED30A332A95B574D89262EA367FA900AE9706FB81A408287BDDEF3A9DD9FF44E3A41BC090FDCF84CC64D81B781903782765FB840951FAFCB6F521F0AA23BC58AF19CC40D6795124D89DC8E0CAF23369B67726A1BF6A7B4EF59CD983059B6A67C15F409903C96577CEDDACD89C7423A103C134E08F84DC781D5818181E60A82765FB840952114F110E8AC00DFEA5F050D955E764C7CBA8FB207C05A7AA5AE849168640A2B4E314391FC3A76795B3827055462639CFF4AE2D64AB80E95274428313E366AF84CC6584581C681C682765FB84096F347B096ED1630F474B97623E45E8D471B1D43C22F599607C8B2E3ED0D7B7905D8554AD399DBD739C76126404424D8DB0DC7D2B047C1A328AE27D40906C583F84CC681836881FC0482765FB8409A22C8FB1BD8BBD02F0E74ED9D3D55B0F5B09672BC43A2D47B1ED04238C1C32B6A657426525B15518236E9789B546A4A072A605E1373FE5B996BAEDC30359428F84BC5520C81E35482765FB8409B1A3A8D771B3D949CA394A88EB5DC29A953B02C81F017361FFC0AFE09ABCE3069171A87D474523687FCC9A9D32CC02CFAB4132256FEAABFE05F7AC747194E88F84BC54281D7781C82765FB8409FA7E55B2D98F1D744C76232E4FDA242FE9FD3D5743D16D3CAD2E548A07CB5AF06FE60EBAEB8C6095028179234DCDDD3CDCF1FCFE6EDAA2A53307FD103DA4AF0F84AC455417E2D82765FB840A01F834E9D1A613C3C747E561CAC19CB12D879C1A57420A49C23652B8F51288C8B111AA3888998B05E327F47A235C6A4A377F888E3005A2D4B03ECB7268608D3F84CC6443081AD81A3827A51B840A5FD77C0D432FBFA3317084914C2E8A8821E4BA1DCBA44961FF7480E6DB608789CAB6291416360EA8CDC26B0D2F0877C50E89A70C1BCF5D6DD8B182E0A9E37D3F84DC7818881A081983182765FB840AE31BD0254EE7D10B80FC90E74BA06BA761187DF3138A9799DE5828D0163524C44BAC7D2A9B5C41BE5BE8289A172361F0BA90410C94F579BF7EBD28F18AAA1CDF84CC681D95B81FC3D82765FB840B1D3B2BB241F3297CC1003E5907DD187B9FF3147F816B068D257222629F5AB9EF2AEAF7965F366AF72A299131D23F7A1ECD4A098D7D37D6F52F3A8C0037C52E0F84AC455417E2D82765FB840BA3D216772CDC74558D2545624A2D62DCBCFD272305730C74643C7A7E819AFA6CDD82223E2B5501EB6D4EAE5DBF21E558C768ACAEC2C1CA10E74C4C87A574B53F84AC455417E2D82765FB840BDB49C01872D91BD1EA990BD2EDF16C48171A6067F9A6F7F48BFB194630B5AE9031B5DC263F59C66ADA444CB4E6F9DF62B3017CE612CAB7B53DA08D356F78D30F84CC66381E75881AF82765FB840C12BA91F95044D78EED1D3A9535EBD6471524418135EEB46AD5D5C6ECC2F5168B4AB3A062BB0742AEA65FFEA767FAB8DCC21783CB29BF32E2CD6222209FA71FDF84CC6443081AD81A3827A51B840C2E269E64AA8C9BE2D41812A48AFA2346BD41A1AB2E4646241AE3B8D0CCD41F2D682B15A025F759C0D955A6071D4E8EA7D4DE397D6E052230920113B6EB74C09F84AC44A4F177782765FB840C303B83F6A161F996736344480AE9D88FDC1D9C675BFACA888F70F24897265628209DA53741E03C0F65921F68F602DC9F334A3C45BCB92AF8544A6FB119BD887F84BC50C81FA611A82765FB840C76E7C157B7735511153D1F95081A144E088A989171F3D432CC5D8293ECE9CFAA483C032155D7B53656A6E33A3D75CD0624E09A2F949C156093DBAA83F1111F2F84BC5520C81E35482765FB840C7D5A3691A59599DE333489CBF8A47A7433E92C72706E13D94ED211296D35C97D8357D7E07B3858564D7268ED7AA097F37589C27770F90DD0B07635BE3F53364F84CC64E09819281B282765FB840C88197A82B0ACF0A872494D1DFAC9DE846DAA7DE08B240647A96BA72FBE08FD52B55C6C94514A47EC51BA49A975489EBC9383B48F5E240939068CE5836FF24F1F84BC581B4202B0882765FB840C9E039D8A8B9E435BEF2F45FC7CB7E788716E8C7AFC1BACC64E1246D2AB506D36073792AE696E41AD6BA0C8ABD2EC0D545B0757F94A9F3538280E56DB5F5D8ECF84BC54E6881A35182765FB840CA27683702A8E9BF3201656FF84A60D5B1DD814273993CF1A025B054454E40D53092F48518EE05BEAD4F18021F4F540C0B7C7D26EBA50EA4890B9E5E49A76C5FF84CC681BF81EA393782765FB840CB78D224C1F5F1319EE9FD058050D24F40234570EAA5941046C7F967D8ADD06484776EB60C3BB11ED9E3562D259B9941585FDAD2D5F236564B8253A565483F89F84BC55C4B81D24C82765FB840CD9699760740E99DB8ED79311B80AFDACD6AA937AB1816B42BD3F465814152F3D9973DF578BE4D8C77FBB19416BDE414140AF3289356512F1BFEB54DD2679A94F84AC436481F3782765FB840CE73660A06626C1B3FDA7B18EF7BA3CE17B6BF604F9541D3C6C654B7AE88B239407F659C78F419025D785727ED017B6ADD21952D7E12007373E321DBC31824BAF84AC455417E2D82765FB840CE73F1F1F1F16C1B3FDA7B18EF7BA3CE17B6F1F1F1F141D3C6C654B7AE88B239407FF1F1F1F119025D785727ED017B6ADD21F1F1F1F1000001E321DBC31824BAF84CC66B81AA3981F782765FB840E02B18FBA6B887FB9258469C3AF8E445CC9AE2B5386CAC5F60C4170F822086224E3876555C745A7EC8AC181C7F9701776D94A779604EA12651DE5F4A748D29E1F84CC64081E70A81D082765FB840E31115A76FA7FB2EFD3CFAF46AD00B05FC3498E1BAF1785DFFE6CA69913D256531D180564235FD3D3C10409CD11FC259CF7CFDA9B6BB253340412D82878F3BD3F84BC5415E31819782765FB840E5E8D8C2D762D21CA1E9BCEE8ADC53600F2D894097542666D6B5F41B23584B07F60901AB409DDF91E0CD2562DAFFF2CB0F221EB9F1156F781A5D9931A02A2E07F84BC5567C5281FE82765FB840F6155F1A60143B7D9D5D1A440D7D52FE6809F69E0C6F1E0024457E0D71DD88ADE3B13AAA940C89AC0610952B48BD832C42E343A13E61FFDB06010CFFC345E053F84CC66381E75881AF82765FB840FA568561B7D5288DF7A506C9BC1C9512AB396E68C46F0E62C21DC1AA584B844A8A7E944F6971303665FD37B138D9A5F637E672EDB98969664C4E7FD1C4126DEF"; byte[] payload = Hex.decode(peersPacketRaw); RLPList rlpList = RLP.decode2(payload); PeersMessage peersMessage = new PeersMessage(rlpList); peersMessage.parseRLP(); } long time2 = System.currentTimeMillis(); System.out.println("20,000 PEERS packets parsing: " + (time2 - time1) + "(msec)"); } /* TRANSACTIONS */ @Test /* Transactions message 1 */ public void test_8() { String txsPacketRaw = "f86e12f86b04648609184e72a00094cd2a3d9f938e13cd947ec05abc7fe734df8dd826" + "881bc16d674ec80000801ba05c89ebf2b77eeab88251e553f6f9d53badc1d800" + "bbac02d830801c2aa94a4c9fa00b7907532b1f29c79942b75fff98822293bf5f" + "daa3653a8d9f424c6a3265f06c"; byte[] payload = Hex.decode(txsPacketRaw); RLPList rlpList = RLP.decode2(payload); TransactionsMessage transactionsMessage = new TransactionsMessage(rlpList); System.out.println(transactionsMessage); assertEquals(1, transactionsMessage.getTransactions().size()); Transaction tx = transactionsMessage.getTransactions().get(0); assertEquals("5d2aee0490a9228024158433d650335116b4af5a30b8abb10e9b7f9f7e090fd8", Hex.toHexString(tx.getHash())); assertEquals("04", Hex.toHexString(tx.getNonce())); assertEquals("1bc16d674ec80000", Hex.toHexString(tx.getValue())); assertEquals("cd2a3d9f938e13cd947ec05abc7fe734df8dd826", Hex.toHexString(tx.getReceiveAddress())); assertEquals("64", Hex.toHexString(tx.getGasPrice())); assertEquals("09184e72a000", Hex.toHexString(tx.getGasLimit())); assertEquals("null", ByteUtil.toHexString(tx.getData())); assertEquals("1b", Hex.toHexString(new byte[] { tx.getSignature().v })); assertEquals("5c89ebf2b77eeab88251e553f6f9d53badc1d800bbac02d830801c2aa94a4c9f", Hex.toHexString(tx.getSignature().r.toByteArray())); assertEquals("0b7907532b1f29c79942b75fff98822293bf5fdaa3653a8d9f424c6a3265f06c", Hex.toHexString(tx.getSignature().s.toByteArray())); } @Test /* Transactions message 2 */ public void test_9(){ String txsPacketRaw = "f9025012f89d8080940000000000000000000000000000000000000000860918" + "4e72a000822710b3606956330c0d630000003359366000530a0d630000003359" + "602060005301356000533557604060005301600054630000000c588433606957" + "1ca07f6eb94576346488c6253197bde6a7e59ddc36f2773672c849402aa9c402" + "c3c4a06d254e662bf7450dd8d835160cbb053463fed0b53f2cdd7f3ea8731919" + "c8e8ccf901050180940000000000000000000000000000000000000000860918" + "4e72a000822710b85336630000002e59606956330c0d63000000155933ff3356" + "0d63000000275960003356576000335700630000005358600035560d63000000" + "3a590033560d63000000485960003356573360003557600035335700b84a7f4e" + "616d655265670000000000000000000000000000000000000000000000000030" + "57307f4e616d6552656700000000000000000000000000000000000000000000" + "00000057336069571ba04af15a0ec494aeac5b243c8a2690833faa74c0f73db1" + "f439d521c49c381513e9a05802e64939be5a1f9d4d614038fbd5479538c48795" + "614ef9c551477ecbdb49d2f8a6028094ccdeac59d35627b7de09332e819d5159" + "e7bb72508609184e72a000822710b84000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000002d0aceee" + "7e5ab874e22ccf8d1a649f59106d74e81ba0d05887574456c6de8f7a0d172342" + "c2cbdd4cf7afe15d9dbb8b75b748ba6791c9a01e87172a861f6c37b5a9e3a5d0" + "d7393152a7fbe41530e5bb8ac8f35433e5931b"; byte[] payload = Hex.decode(txsPacketRaw); RLPList rlpList = RLP.decode2(payload); TransactionsMessage transactionsMessage = new TransactionsMessage(rlpList); System.out.println(transactionsMessage); assertEquals(3, transactionsMessage.getTransactions().size()); Transaction tx = transactionsMessage.getTransactions().get(0); assertEquals("4b7d9670a92bf120d5b43400543b69304a14d767cf836a7f6abff4edde092895", Hex.toHexString( tx.getHash() )); assertEquals("null", Hex.toHexString( tx.getNonce() )); assertEquals("NULL", Hex.toHexString( tx.getValue() )); assertEquals("0000000000000000000000000000000000000000", Hex.toHexString( tx.getReceiveAddress() )); assertEquals("09184e72a000", Hex.toHexString( tx.getGasPrice() )); assertEquals("2710", Hex.toHexString( tx.getGasLimit() )); assertEquals("606956330c0d630000003359366000530a0d630000003359602060005301356000533557604060005301600054630000000c58", Hex.toHexString( tx.getData() )); assertEquals("1c", Hex.toHexString( new byte[] {tx.getSignature().v} )); assertEquals("7f6eb94576346488c6253197bde6a7e59ddc36f2773672c849402aa9c402c3c4", Hex.toHexString( tx.getSignature().r.toByteArray() )); assertEquals("6d254e662bf7450dd8d835160cbb053463fed0b53f2cdd7f3ea8731919c8e8cc", Hex.toHexString( tx.getSignature().s.toByteArray() )); tx = transactionsMessage.getTransactions().get(2); assertEquals("b0251a1bb20b44459db5b5444ab53edd9e12c46d0ba07fa401a797beb967d53c", Hex.toHexString( tx.getHash() )); assertEquals("02", Hex.toHexString( tx.getNonce() )); assertEquals("null", Hex.toHexString( tx.getValue() )); assertEquals("ccdeac59d35627b7de09332e819d5159e7bb7250", Hex.toHexString( tx.getReceiveAddress() )); assertEquals("09184e72a000", Hex.toHexString( tx.getGasPrice() )); assertEquals("2710", Hex.toHexString( tx.getGasLimit() )); assertEquals("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000002d0aceee7e5ab874e22ccf8d1a649f59106d74e8", Hex.toHexString( tx.getData() )); assertEquals("1b", Hex.toHexString( new byte[] {tx.getSignature().v} )); assertEquals("d05887574456c6de8f7a0d172342c2cbdd4cf7afe15d9dbb8b75b748ba6791c9", Hex.toHexString( tx.getSignature().r.toByteArray() )); assertEquals("1e87172a861f6c37b5a9e3a5d0d7393152a7fbe41530e5bb8ac8f35433e5931b", Hex.toHexString(tx.getSignature().s.toByteArray())); } /* BLOCKS */ @Test /* BlocksMessage parsing 1*/ public void test_10(){ // BlockData [ hash=36a24b56c6104e5a5c0e70b0553f1a4d6109d065d718d7443a6a475ec8c83905 parentHash=372d8e5c6e32335fb86fa7a6ae1b35165745346e1c786eacd42df85f8da12b3d, unclesHash=1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347, coinbase=1a4d98707ba8dd3d36d16e8c165c272645695cea, stateHash=5e2d2cc0b42b38b5b18c9d65734f9877c035dd390b9c12c48624f2243668a268, txListHash=1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347, difficulty=02471a26, timestamp=1398260220, extraData=null, nonce=0000000000000000000000000000000000000000000000006f4cd02da011a235] // String blocksRaw = "F8CC13F8C9F8C5A0372D8E5C6E32335FB86FA7A6AE1B35165745346E1C786EACD42DF85F8DA12B3DA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347941A4D98707BA8DD3D36D16E8C165C272645695CEAA05E2D2CC0B42B38B5B18C9D65734F9877C035DD390B9C12C48624F2243668A268A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D493478402471A26845357C1FC80A00000000000000000000000000000000000000000000000006F4CD02DA011A235C0C0"; /* parentHash: 00000000000000000000000000000000000000000000000000000000000000000 unclesHash: 1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347 coinbase: 0000000000000000000000000000000000000000 stateRoot: 2f4399b08efe68945c1cf90ffe85bbe3ce978959da753f9e649f034015b8817d txsTrieRoot: 00000000000000000000000000000000000000000000000000000000000000000 difficulty: 400000 number: <<empty string>> mixGasPrice: <<empty string>> gasLimit: 0f4240 gasUsed: <<empty string>> timestamp: <<empty string>> extraData: <<empty string>> nonce: 04994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829 transaction: <<empty string>> uncles: <<empty string>> */ // Genesis block String blocksRaw = "f8cbf8c7a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a02f4399b08efe68945c1cf90ffe85bbe3ce978959da753f9e649f034015b8817da00000000000000000000000000000000000000000000000000000000000000000834000008080830f4240808080a004994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829c0c0"; byte[] payload = Hex.decode(blocksRaw); RLPList rlpList = RLP.decode2(payload); BlocksMessage blocksMessage = new BlocksMessage(rlpList); List<Block> list = blocksMessage.getBlockDataList(); System.out.println(blocksMessage); assertEquals(1, list.size()); Block block = list.get(0); assertEquals("69a7356a245f9dc5b865475ada5ee4e89b18f93c06503a9db3b3630e88e9fb4e", Hex.toHexString(block.getHash())); assertEquals("00000000000000000000000000000000000000000000000000000000000000000", Hex.toHexString(block.getParentHash())); assertEquals("1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", Hex.toHexString(block.getUnclesHash())); assertEquals("0000000000000000000000000000000000000000", Hex.toHexString(block.getCoinbase())); assertEquals("2f4399b08efe68945c1cf90ffe85bbe3ce978959da753f9e649f034015b8817d", Hex.toHexString(block.getStateRoot())); assertEquals("00000000000000000000000000000000000000000000000000000000000000000", Hex.toHexString(block.getTxTrieRoot())); assertEquals("400000", Hex.toHexString(block.getDifficulty())); assertEquals(0, block.getTimestamp()); assertNull(block.getExtraData()); assertEquals("04994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829", Hex.toHexString(block.getNonce())); } @Test /* BlocksMessage really big message parsing */ public void test11(){ String blocksRaw = "F91C1C13F90150F8C4A07DF3D35D4DF0A56FCF1D6344D5315CB56B9BF83BB96AD17C7B96A9CD14133C5DA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A064AFB6284FA35F26D7B2C5A26AFAA5483072FBCB575221B34CE002A991B7A223A04A8ABE6D802797DC80B497584F898C2D4FD561CC185828CFA1B92F6F38EE348E833FBFE484533F201C80A000000000000000000000000000000000000000000000000000CFCCB5CFD4667CF887F8850380942D0ACEEE7E5AB874E22CCF8D1A649F59106D74E88609184E72A000822710A047617600000000000000000000000000000000000000000000000000000000001CA08691AB40E258DE3C4F55C868C0C34E780E747158A1D96CA50186DFD3305ABD78A042269C981D048A7B791AAFC8F4E644232740C1A1CCEB5B6D05568827A64C0664C0F8C8F8C4A0637C8A6CDB907FAC6F752334AB79065BCC4E46CD4F4358DBC2A653544A20EB31A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A022A36C1A1E807E6AFC22E6BB53A31111F56E7EE7DBB2EE571CEFB152B514DB4DA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FCFD784533F1CF980A0000000000000000000000000000000000000000000000000E153D743FA040B18C0C0F8C8F8C4A07B2536237CBF114A043B0F9B27C76F84AC160EA5B87B53E42C7E76148964D450A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A07A3BE0EE10ECE4B03097BF74AABAC628AA0FAE617377D30AB1B97376EE31F41AA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FBFE884533F1CE880A0000000000000000000000000000000000000000000000000F3DEEA84969B6E95C0C0F8C8F8C4A0D2AE3F5DD931926DE428D99611980E7CDD7C1B838273E43FCAD1B94DA987CFB8A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A00B5B11FCF4EE12C6812F9D01CF0DFF07C72CD7E02E48B35682F67C595407BE14A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FAFFD84533F1CE280A00000000000000000000000000000000000000000000000005FCBC97B2EB8FFB3C0C0F8C8F8C4A094D615D3CB4B306D20985028C78F0C8413D509A75E8BB84EDA95F734DEBAD2A0A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A04B8FD1B98CF5758BD303FF86393EB6D944C1058124BDDCE5D4E04B5395254D5EA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FBFEC84533F1C7680A000000000000000000000000000000000000000000000000079FE3710116B32AAC0C0F8C8F8C4A09424A07A0E4C05BB872906C40844A75B76F6517467B79C12FA9CC6D79AE09934A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A02DBE9FF9CBBC4C5A6FF26971F75B405891141F4E9BCE3C2DC4200A305138E584A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FCFDF84533F1C3B80A0000000000000000000000000000000000000000000000000E0A6F8CF1D56031BC0C0F8C8F8C4A009AABEA60CF7EAA9DF4AFDF4E1B5F3E684DAB34FC9A9180A050085A4131CEEDFA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A0436DA067F9683029E717EDF92DA46C3443E8C342974F47A563302A0678EFE702A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FDFD684533F1BFC80A00000000000000000000000000000000000000000000000005BC88C041662FFDAC0C0F8C8F8C4A0F8B104093483B7C0182E1BBA2CE3340D14469D3A3EE7646821223A676C680AC1A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A0D482E71CDE61190A33CA5AEB88B6B06276984E5A14253A98DF232E8767167221A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FEFD184533F1BCE80A00000000000000000000000000000000000000000000000004AEB31823F6A1950C0C0F8C8F8C4A0DD1F0ABA02C2BB3B5A2B6CB1CC907EA70912BD46DC7A78577F2CAE6CDBCBE5F3A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A058AB6DF33D7CBEB6A735A7E4CCF4F28143E6A1742E45DDA8F8CF48AF43CB66C0A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FFFD084533F1B9F80A0000000000000000000000000000000000000000000000000577042B0858B510BC0C0F8C8F8C4A0A287BB7DA30F04344976ABE569BD719F69C1CBEA65533E5311CA5862E6EAA504A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A07E0537009C23CB1152CAF84A52272431F74B6140866B15805622B7BCB607CD42A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934783400FD384533F1B6180A000000000000000000000000000000000000000000000000083D31378A0993E1AC0C0F8C8F8C4A063483CFF8FBD489E6CE273326D8DC1D54A31C67F936CA84BF500E5419D3E9805A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A07737D08564819D51F8F834A6EE4278C23A0C2F29A3F485B21002C1F24F04D8E4A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FFFD484533F1B5780A0000000000000000000000000000000000000000000000000BB586FE6DE016E14C0C0F8C8F8C4A0975C8ED0C9197B7C018E02E1C95F315ACF82B25E4A812140F4515E8BC827650CA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A0AD51229ABEAD59E93C80DB5BA160F0939BC49DCEE65D1C081F6EB040FF1F571FA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FEFD984533F1B4E80A0000000000000000000000000000000000000000000000000548F02C6CEB26FD4C0C0F8C8F8C4A05844082E41F7C1F34485C7902AFA0AA0979A6A849100FC553CD946F4A663929CA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A01BC726443437C4C062BE18D052278E4EF735B8FE84387C8A4FC85FB70D5078E0A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FFFD884533F1B1080A0000000000000000000000000000000000000000000000000CC1E528F54F22BDAC0C0F8C8F8C4A0BA06BA81C93FAAF98EA2D83CBDC0788958D938B29A9EB2A92FFBD4A628B3D52EA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A05053BFE1C0F1F0DD341C6DF35E5A659989BE041E8521027CC90F7605EB15FBB9A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FEFDD84533F1B0380A0000000000000000000000000000000000000000000000000BCF9DF2FEC615ECAC0C0F8C8F8C4A083732D997DB15109E90464C24B7C959A78881D827C55A0D668A66A2736BE5D87A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A054F4012CBA33A2B80B0DCA9DD52F56B2C588133BD71700863F8CB95127176634A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FFFDC84533F1A4680A00000000000000000000000000000000000000000000000006920A1DC9D915D0EC0C0F8C8F8C4A052E2FBA761C2D0643170EF041C017391E781190FE715AE87CDAE8EEE1D45D95BA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A0EE2C82F77D7AFD1F8DBE4F791DF8477496C23E5504B9D66814172077F65F81F2A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FEFE184533F1A3880A0000000000000000000000000000000000000000000000000AE86DA9012398FC4C0C0F8C8F8C4A055703BA09544F386966B6D63BFC31033B761A4D1A6BB86B0CF49B4BB0526744EA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A01684C03A675B53786F0077D1651C3D169A009B13A6EE2B5047BE6DBBE6D957FFA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FDFEA84533F1A2F80A00000000000000000000000000000000000000000000000003247320D0EB639DFC0C0F8C8F8C4A05109A79B33D81F4EE4814B550FB0002F03368D67570F6D4E6105FCE2874D8B72A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A0AE72E8C60A3DCFD53DEECDB2790D18F0CC710F77CF2C1ED76E7DA829BDE619DCA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FCFF784533F1A1D80A000000000000000000000000000000000000000000000000040E0BC9BC9BCF295C0C0F8C8F8C4A03961E4BBBA5C95FAD3DB0CFFA3A16B9106F9EA3E8957993EAB576B683C22F416A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A0E9C6CF457BBE64D6BDA67852A276CDBADB4F384A36D496E81801A496CFD9B7B5A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FDFEE84533F19DF80A0000000000000000000000000000000000000000000000000DBB3FD6C816776D8C0C0F8C8F8C4A06B8265A357CB3AD744E19F04EB15377F660C10C900CC352D24F9B09073A363D6A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A07BA07E1BC6A20FFA44AE6080D30982B9FAA148FAF6B1EC15E32D89AC853AC291A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FEFE984533F198D80A00000000000000000000000000000000000000000000000005171325B6A2F17F1C0C0F8C8F8C4A0DCDC0347BB87CE72D49AC2E4E11F89069509B129A2536BF3D57C6BCA30894032A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A0CA24447AA0CEDB4B561C7810461EEF19B16A827C27352E5E01F914E9D7C78247A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FFFE884533F194680A0000000000000000000000000000000000000000000000000DA4714CFED9D8BBCC0C0F8C8F8C4A047F2DD6C15EA4082B3E11E5CF6B925B27E51D9DE68051A093E52EF465CFFBB8CA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A05A7206EDDDF50FCFEEAA97348A7112FC6EDD0B5EACB44CF43D6A6C6B6609B459A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FEFED84533F193E80A0000000000000000000000000000000000000000000000000FFAFBA4BF8DC944EC0C0F8C8F8C4A04D5AD6D860772145872F6660ECEFCB0B0B2056E0AA3509A48BF4C175459E5121A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A00F4659D09BB2CED56E7FD9C4D3D90DACA8B4F471307B7C4385FD34A41016B0B2A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FDFF684533F192580A000000000000000000000000000000000000000000000000090620E5E59A39FE5C0C0F8C8F8C4A0C1725C58D1BF023AF468E0088DB3CF642AE097CF2C58C2ECE2FC746980ACC7E6A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A0BE19A182EA1584050DEB0A79ABDC11BE896CE8D00A282BCFAF9FFCD65FD64D6AA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FEFF184533F189080A000000000000000000000000000000000000000000000000076F17F4199BCCD12C0C0F8C8F8C4A0BD521A20A18CA6CA7115065065A1AA20067EE580FB11E2963D1E3A681E8302AFA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A011BE45633350E39475A1A07712BA72DE4602D9EEBF639CCD5422A389095CCAF1A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FDFFA84533F187B80A00000000000000000000000000000000000000000000000000C71B81C4A4CB82CC0C0F8C8F8C4A07C6D2D56E9C87F1553E4D06705AF61A7C19A6046D2C39F8ED1417988783D3B1DA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A012F5F0668063509E33A45A64EB6A072B2D84AA19F430F49F159BE5008A786B2EA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FD00684533F186080A0000000000000000000000000000000000000000000000000B3F962892CFEC9E6C0C0F8C8F8C4A07154F0F8ECC7F791D22EEC06EC86D87A44B2704F015B3D2CFF3571A3D01AE0F6A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A079536ABF8E163CF8AA97F0D52866D04363902D591FD7C36AA35FC983D45FEFD6A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FDFFD84533F182F80A0000000000000000000000000000000000000000000000000736716E42499890FC0C0F8C8F8C4A0BF2FB1EE988AC4E17EAE221A24176649774333FAB25B6FC96C6081527FB6F121A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A041578DAAE7BCCCD4976340AEB19E4132D2FE4193A0D92F87744C82BFE113502FA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FD00984533F182B80A00000000000000000000000000000000000000000000000001C62FA76645942C6C0C0F8C8F8C4A07F84873E2679D40458B9DDA9900478A78871044E08F6B47DAD659B9B60FF8D48A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A0597D3F4160770C0492333F90BAD739DC05117D0E478A91F09573742E432904E8A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FE00184533F17F680A0000000000000000000000000000000000000000000000000E24D8B1140FB34D5C0C0F8C8F8C4A0FD77BD13A8CDE1766537FEBE751A27A2A31310A04638A1AFCD5E8AD3C5485453A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A0473B2B248D91010BA9AEC2696FFC93C11C415ED132832BE0FD0578F184862E13A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FEFFC84533F17CA80A0000000000000000000000000000000000000000000000000FB5B65BAC3F0D947C0C0F8C8F8C4A0518916DFB79C390BD7BFF75712174512C2F96BEC42A3F573355507AD1588CE0CA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A08599D2EC9E95EC62F41A4975B655D8445D6767035F94EB235ED5EBEA976FB9EAA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347833FE00484533F17B880A0000000000000000000000000000000000000000000000000BC27F4B8A201476BC0C0F90319F8C4A0AB6B9A5613970FAA771B12D449B2E9BB925AB7A369F0A4B86B286E9D540099CFA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347943854AAF203BA5F8D49B1EC221329C7AEBCF050D3A0990DC3B5ACBEE04124361D958FE51ACB582593613FC290683940A0769549D3EDA09BFE4817D274EA3EB8672E9FE848C3885B53BBBD1D7C26E6039F90FB96B942B0833FF00084533F16B780A000000000000000000000000000000000000000000000000077377ADFF6C227DBF9024FF89D80809400000000000000000000000000000000000000008609184E72A000822710B3606956330C0D630000003359366000530A0D630000003359602060005301356000533557604060005301600054630000000C5884336069571CA07F6EB94576346488C6253197BDE6A7E59DDC36F2773672C849402AA9C402C3C4A06D254E662BF7450DD8D835160CBB053463FED0B53F2CDD7F3EA8731919C8E8CCF9010501809400000000000000000000000000000000000000008609184E72A000822710B85336630000002E59606956330C0D63000000155933FF33560D63000000275960003356576000335700630000005358600035560D630000003A590033560D63000000485960003356573360003557600035335700B84A7F4E616D65526567000000000000000000000000000000000000000000000000003057307F4E616D655265670000000000000000000000000000000000000000000000000057336069571BA04AF15A0EC494AEAC5B243C8A2690833FAA74C0F73DB1F439D521C49C381513E9A05802E64939BE5A1F9D4D614038FBD5479538C48795614EF9C551477ECBDB49D2F8A6028094CCDEAC59D35627B7DE09332E819D5159E7BB72508609184E72A000822710B84000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002D0ACEEE7E5AB874E22CCF8D1A649F59106D74E81BA0D05887574456C6DE8F7A0D172342C2CBDD4CF7AFE15D9DBB8B75B748BA6791C9A01E87172A861F6C37B5A9E3A5D0D7393152A7FBE41530E5BB8AC8F35433E5931BC0"; byte[] payload = Hex.decode(blocksRaw); RLPList rlpList = RLP.decode2(payload); BlocksMessage blocksMessage = new BlocksMessage(rlpList); List<Block> list = blocksMessage.getBlockDataList(); System.out.println(blocksMessage); assertEquals(32, list.size()); Block block = list.get(31); assertEquals("518916DFB79C390BD7BFF75712174512C2F96BEC42A3F573355507AD1588CE0C", Hex.toHexString(block.getHash()).toUpperCase()); assertEquals("AB6B9A5613970FAA771B12D449B2E9BB925AB7A369F0A4B86B286E9D540099CF", Hex.toHexString(block.getParentHash()).toUpperCase()); assertEquals("1DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D49347", Hex.toHexString(block.getUnclesHash()).toUpperCase()); assertEquals("3854AAF203BA5F8D49B1EC221329C7AEBCF050D3", Hex.toHexString(block.getCoinbase()).toUpperCase()); assertEquals("990DC3B5ACBEE04124361D958FE51ACB582593613FC290683940A0769549D3ED", Hex.toHexString(block.getStateRoot()).toUpperCase()); assertEquals("9BFE4817D274EA3EB8672E9FE848C3885B53BBBD1D7C26E6039F90FB96B942B0", Hex.toHexString(block.getTxTrieRoot()).toUpperCase()); assertEquals("3FF000", Hex.toHexString(block.getDifficulty()).toUpperCase()); assertEquals(1396643511, block.getTimestamp()); assertNull(block.getExtraData()); assertEquals("00000000000000000000000000000000000000000000000077377ADFF6C227DB", Hex.toHexString(block.getNonce()).toUpperCase()); System.out.println(blocksMessage); } /* GET_CHAIN */ @Test /* GET_CHAIN message parsing*/ public void test_12(){ String getChainRaw = "F9042414A09F7A910147A6C99AB7EEEAC1ADC7B1B9B0D7D9DD83FD7FC125561016F19B624DA024B519ED5F71207330C1F450B7A4C7445C589B5F9AE73E9BBA09E0A8CB15D845A01EF7B03C7E58E65068D71F68E168C0CC0438808C32FB3E46E402D078B2020E0DA06A0F152620F606E134679D22A86156F9DDEB56FACD62C3106CC66AE030234483A001A3E918F9C2F74BD144505CF70650EF30BE806C533BA5AE3C983F55615EE98EA0E5E441F0877116011CCDECE2501A50B40C40418377037E16D0282B2B5E347138A0C55035BC5BDA25A8C6A2EFF4CCF5386CFFF3E7EE1DC9168B00AABF1074FEB1E2A060AC4D0C12C4CBF552440E659FE4E54C38EF7D05EF98965BA0E0248379CB78DFA0E1620BF60A735DDEA7CB434143E7EF663D043420F017360289FF78046948A77AA0DA8BC25F6571AB0EDE9C3DEF34FFF996575ADFCC1F8009A0388CE0A63AD9FC57A0E153CD998421E4F6BAC6A8329AE90BDA70D5D0F46A7EC02B88BDF5D3CAA8384FA0D3F00977D766A5CAF8F07EF8D15B1DADBBFD57B60BBE6CA54B2F9C2446F614EFA08687EC7AE1A541B13CDA57DCF387DEA3EA35A35AC3D5A9381376EAFBC7BA2CF5A08814AC8660E776A3FCA432D2E9A3533AFFEAEC783ECBB5DAD495B44E04EF1F98A07F2E67F508830BF18E8A432BAB9B957FA2BCDE57BE6C766C13871F833C27B9A5A021EE1E6602530EF711F6C8022799108E1AFB546E7B5FF3E3CBB4DA66C054868DA02940A17DD5C1D1911FFDA7DFAE3E5FAF8E1808CBD11F3248C18B8777B4A5D256A07E5D2F25D9750665ADBFF9C36820AD67CC55850D7D798DAB512343AB0C4E58B3A06674BD13B1051852413031BAA885448E50917D7F1D5EFB7DBA397ED4E5C36D72A06AA7A7D18B07BE0222DA47A8EE6923BAD522DBF5D0650D64CA0F2AD4C606D0CCA07F877735FCC29F804926AACEDBF7AD4896E330DCCE57F257A7D5C81F5CC03188A0FF6B7749526281A5E6A845B8ACC7DC03D2CAAEAFF0CEBF78659FDE1007AD9C05A054D6375CF54B0246FB45787206BA70115DED577354942A9219BC9E761A7E0CBCA0809384946576FB15A8F827B30045D18203A90BE662863D5F205B868DF882472AA05A6EA58D02A2823BA693AC11C21D3C4D66AFFFDB9F1475EA86A461912C2F3187A003AF21F3939C29C231200B1F790F16421A8923254CBF2A90455B9B8F28BE4562A036FDFB3E05936CAA1ABBDCFBBACD9000F86FBCAE2228E77346533CEF17073767A0D3CE8B71E129020F3356A09946F9BC4C18E61D9516E74F6F912461A438F1E006A01D8203A8E23F50D70188ED3099E50645B92959C2216EA7A74719C159B4978BDBA03812A8FC4A5BB6EF0832EBF5058FAF65A46187CEE568C94915AE1850069775F3A0687DDEF8750F606637B3F5F23D286053671081A1AD224B35A624DE7392193951A0E6A8E1D4417292E20F9698A3464CEEABC6476A57521FF79D994DE22C55DADEAD820100"; byte[] payload = Hex.decode(getChainRaw); RLPList rlpList = RLP.decode2(payload); GetChainMessage getChainMessage = new GetChainMessage(rlpList); getChainMessage.parseRLP(); System.out.println(getChainMessage); assertEquals(32, getChainMessage.getBlockHashList().size()); assertEquals("E5E441F0877116011CCDECE2501A50B40C40418377037E16D0282B2B5E347138", Hex.toHexString( getChainMessage.getBlockHashList().get(5) ).toUpperCase()); assertEquals("6AA7A7D18B07BE0222DA47A8EE6923BAD522DBF5D0650D64CA0F2AD4C606D0CC", Hex.toHexString( getChainMessage.getBlockHashList().get(19) ).toUpperCase()); assertEquals("03AF21F3939C29C231200B1F790F16421A8923254CBF2A90455B9B8F28BE4562", Hex.toHexString( getChainMessage.getBlockHashList().get(25) ).toUpperCase()); } /* NOT_IN_CHAIN */ @Test /* NotInChainMessage parsing 1 */ public void test_13(){ String getChainRaw = "E015A0E5E441F0877116011CCDECE2501A50B40C40418377037E16D0282B2B5E347138"; byte[] payload = Hex.decode(getChainRaw); RLPList rlpList = RLP.decode2(payload); NotInChainMessage notInChainMessage = new NotInChainMessage(rlpList); System.out.println(notInChainMessage); assertEquals("E5E441F0877116011CCDECE2501A50B40C40418377037E16D0282B2B5E347138", Hex.toHexString(notInChainMessage.getHash()).toUpperCase()); } @Test /* BlocksMessage POC-5 real msg*/ public void test12(){ String blocksRaw = "F8D813F8D5F8D1A0085F6A51A63D1FBA43D6E5FE166A47BED64A8B93A99012537D50F3279D4CEA52A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794D8758B101609A9F2A881A017BA86CBE6B7F0581DA068472689EA736CFC6B18FCAE9BA7454BADF9C65333A0317DFEFAE1D4AFFF6F90A000000000000000000000000000000000000000000000000000000000000000008401EDF1A18222778609184E72A0008080845373B0B180A0000000000000000000000000000000000000000000000000D1C0D8BC6D744943C0C0"; byte[] payload = Hex.decode(blocksRaw); RLPList rlpList = RLP.decode2(payload); BlocksMessage blocksMessage = new BlocksMessage(rlpList); List<Block> list = blocksMessage.getBlockDataList(); System.out.println(blocksMessage); Block block = list.get(0); } @Test /* BlocksMessage POC-5 real big msg*/ public void test13(){ String blocksRaw = "F91BB313F8D5F8D1A0241A2A72372AD63C40704C93CD380A51FEE174EB59501D731A009F51372E5205A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0DA5AB2C34F600525393C29D492AE1ED9140919DDB53E9498F2DEE502CF587EC9A000000000000000000000000000000000000000000000000000000000000000008341C5E1208609184E72A000830EC9F48084536AD0E180A0000000000000000000000000000000000000000000000000D441E9FE9406E474C0C0F8D5F8D1A0E963653D860F35E27A5572CFEECE1BB518C42BB97DEAC0978FA788F6DCB45CF7A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0501FE35864E5FE87049925663356E746D89B7341EAB64DF182B38590EE792B5FA000000000000000000000000000000000000000000000000000000000000000008341B5741F8609184E72A000830ECDA88084536AD0DA80A00000000000000000000000000000000000000000000000007828A9BAAB6A7ECFC0C0F8D5F8D1A003D0110B5137559C8A7F5776C4AB2FD7556E972B2398802E9284B0E530C4E836A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0D6237F3F6440A41F87C210428913C9D382ADCE25934CBB78C8D2E8309EE0F954A000000000000000000000000000000000000000000000000000000000000000008341A50B1E8609184E72A000830ED15D8084536AD0CB80A00000000000000000000000000000000000000000000000001EFCD54BEDDF3380C0C0F8D5F8D1A0B2F12064C028E457DF19DBDEA79DBC02477E1BD2C9B9E44A7260B89E24EEB672A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA09622DCD321E343D62708AF4D0F02C06F0424FAAA615B06CC561BA4BD6B9A9059A00000000000000000000000000000000000000000000000000000000000000000834194A61D8609184E72A000830ED5138084536AD0C980A0000000000000000000000000000000000000000000000000B5438A51AD0D626EC0C0F8D5F8D1A088740C3D1B992EE40221C8099E503543669C0DB48317B48C746A133F9C3D22B7A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA01CE096A03FB4F29111158043646FAC7FBD1CA29253DF2A9B64DAAD41E00D8D93A00000000000000000000000000000000000000000000000000000000000000000834184451C8609184E72A000830ED8CA8084536AD0C880A0000000000000000000000000000000000000000000000000B617267976C0ED9DC0C0F8D5F8D1A0BD600487C95AE3BF9923188C7E86260EFD21758E452A42EDD4E62F75F7599A0BA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA05E7419539879A254A59E4E8054C230C19EE588DC6E7D1D9398486AF01C522CF0A00000000000000000000000000000000000000000000000000000000000000000834173E91B8609184E72A000830EDC828084536AD0B580A0000000000000000000000000000000000000000000000000224668B25482A4FDC0C0F8D5F8D1A06CF575AE2D8D4E636BDB05D27F14E91FFBADE677F23068EDA5AFB1DDCF387838A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA05EA0F8C08233E9A867BA5989EE74ED825AB0FF3C52EE0BCA2297D71A52DF6F13A00000000000000000000000000000000000000000000000000000000000000000834163911A8609184E72A000830EE03B8084536AD0AA80A000000000000000000000000000000000000000000000000015FA4CACFA1CE96CC0C0F8D5F8D1A021745CD12304E2B55FCE61E49B929BC4D0DA9B7C989D5E789AD6373E8CA4DFA1A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0D1546B182CFA9776D91695400B0AE4BE474A051F964D886CC761B1476BC52747A000000000000000000000000000000000000000000000000000000000000000008341533D198609184E72A000830EE3F48084536AD0A680A0000000000000000000000000000000000000000000000000910666C71F0C6015C0C0F8D5F8D1A0B94798F50873CCE252A237BC347879E96CB95CB89E8C2FF1CEAA4FC20671D7A1A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0B28C842A75C674D7FECE960B3CC7E48319262D393647C1E37EAB1B7A738AC7F5A00000000000000000000000000000000000000000000000000000000000000000834142ED188609184E72A000830EE7AE8084536AD0A680A000000000000000000000000000000000000000000000000098993C3F1D7DD302C0C0F8D5F8D1A0E9F0C11A4DADEAA7DA131639CC78A65897568A178020BFF71C0A895A62B94126A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0473283BCF366E648963BFC15C006D92D2F73FD8B8A9A5CF0715A306102AF0471A00000000000000000000000000000000000000000000000000000000000000000834132A1178609184E72A000830EEB698084536AD0A280A0000000000000000000000000000000000000000000000000EF3D442D4F180BE8C0C0F8D5F8D1A052D3DEF715BE4DCC7BF26774CF2F46220E1E6139428190D99386B50478A328E6A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0874BF4FB3B5433222701895A14E5FDE926DAA419ABE5BFEDF41DD53D9C3B7716A0000000000000000000000000000000000000000000000000000000000000000083412259168609184E72A000830EEF258084536AD0A080A0000000000000000000000000000000000000000000000000AC63BB35461C7E23C0C0F8D5F8D1A09DF048629BD8AC4740FA437AD0BDA26D92853C2483B6E0DA8ED790C5E068EDA1A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA018B3624F1E0CE3D46CCAB5AA5C9CE16E91740704C81CD342F712F9A3B6B14B72A0000000000000000000000000000000000000000000000000000000000000000083411215158609184E72A000830EF2E28084536AD07880A0000000000000000000000000000000000000000000000000E1E40B4CCB7A7650C0C0F8D5F8D1A09D9DE4728A55A7A26CF9B2942235CD10E89443B71A63C4C2CD68016106228BF5A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA08C4405BF700474CB2081DCDC433DD68E0BAEB6376278EF9F31C51B8AD729D584A00000000000000000000000000000000000000000000000000000000000000000834101D5148609184E72A000830EF6A08084536AD06580A00000000000000000000000000000000000000000000000007530D22D42044BAEC0C0F8D5F8D1A09B2D93A9228E373687E106B8B3F33007F18D3AD098784FBB710AFC86A483D99AA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0F1EA4E93A025A5BFF907CBE330F961593A00E79692423B411DCC449AC9DBD3C9A000000000000000000000000000000000000000000000000000000000000000008340F199138609184E72A000830EFA5F8084536AD04480A0000000000000000000000000000000000000000000000000C1072BD480F8546CC0C0F8D5F8D1A0AD8F6F3AED4784805B4B18E1EEF971BE8E196C7245B0717B8065CEA7E6CC7E02A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0BF1CB953D6541CB7FCF49552C2C96767F76A62A117E41E572F21BC9FDBA8EC16A000000000000000000000000000000000000000000000000000000000000000008340E161128609184E72A000830EFE1F8084536AD04180A00000000000000000000000000000000000000000000000009D15DE72AD78E877C0C0F8D5F8D1A01CBFAE447EF444E8BE711C7DF471FFEDBB7E3317175BD25F5AF2A65342E2B373A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA010F6479D5F790546140EFCA7675DD2256ABFECC0A86AD551BCDBE59FD9475AF3A000000000000000000000000000000000000000000000000000000000000000008340D12D118609184E72A000830F01E08084536AD03080A00000000000000000000000000000000000000000000000007E01A25F73936D1DC0C0F8D5F8D1A027E9B34ACA511576C05DEB919053C1EEA958FF532FEEA1F952BAE699E40FB5D2A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0ADDE0B5F2471D97EC743253952910B8C7F56F413F4564049077ECD93BB298E61A000000000000000000000000000000000000000000000000000000000000000008340C0FD108609184E72A000830F05A28084536AD02D80A00000000000000000000000000000000000000000000000002A05A1CE710E5009C0C0F8D5F8D1A0C32F01ACBCB01E6381F60C118F291090946CCC0AA961489D404335FFFB81DF71A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0FE5383F13A0FDE496E6737D1E5B55323E0416FAEE0983FBE399D336F7B58A191A000000000000000000000000000000000000000000000000000000000000000008340B0D10F8609184E72A000830F09658084536AD02780A00000000000000000000000000000000000000000000000000CD0D5909EC1996AC0C0F8D5F8D1A0D4D3BC8A0CE547D9E2EC49475F0BDC092F9744F04900D388EEBE7A99A733BB17A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0397EE5E3270CD4521E05048CC7D777C0F5D7592F438BC95CBCE7FCAED9DAA9B8A000000000000000000000000000000000000000000000000000000000000000008340A0A90E8609184E72A000830F0D298084536AD02480A000000000000000000000000000000000000000000000000037AA51DB21383761C0C0F8D5F8D1A0D7B98EAB92E9B4BE7447DA779B91528F7C64E904BEC37E2118CFE9BCAF742455A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0423459C9544507C7CFBE879A9980709213F3BABF3EDA6366137AB75C0B571287A000000000000000000000000000000000000000000000000000000000000000008340B0D50D8609184E72A000830F10EE8084536ACFE880A0000000000000000000000000000000000000000000000000433536CC4254685CC0C0F8D5F8D1A00786B6D216BA1504ADB1BE9A2A5641E2D29C7E5B76A7499FDE0AC3AFAE9C430EA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0F572DC64264D572D306A158A988A1E59D3B1239CBA5A7B41BD1EAA5CFF34EF17A000000000000000000000000000000000000000000000000000000000000000008340A0AD0C8609184E72A000830F14B48084536ACFE180A00000000000000000000000000000000000000000000000003292DD4BF23421C9C0C0F8D5F8D1A02D8D2E0E39972F1C3312C69E31F234FD3815629CF99054609FABEAE535003F16A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA08E759E25A406E0D8DCF0A208911B6BBA014F857219BD7AD9AD9C2FE7DBC3955FA00000000000000000000000000000000000000000000000000000000000000000834090890B8609184E72A000830F187B8084536ACFDE80A00000000000000000000000000000000000000000000000004285B36769517C59C0C0F8D5F8D1A04EE80D4C2C076A8EEE49AF40EBA6BD1B9C8BCC260A21538E50300886EE95DB2DA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0B2EA0D776870D3ED426C7FE68B202F213C064499E7EF237E0B93422F515A1D79A00000000000000000000000000000000000000000000000000000000000000000834080690A8609184E72A000830F1C438084536ACFD080A0000000000000000000000000000000000000000000000000DA58C863E0B19CDFC0C0F8D5F8D1A0E1EBC899ECF44D7BD08B2B9F2A80CF60CDA30049724EA20C6BCFF45563C59660A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0FA4013D37280A1F36BDF799163D8010019C093EEB6B3726F607D815D62E459F8A000000000000000000000000000000000000000000000000000000000000000008340704D098609184E72A000830F200C8084536ACFCA80A000000000000000000000000000000000000000000000000085C4CB652CFFA8F3C0C0F8D5F8D1A0D7B79F0B2D4B17DD969B991770CF0B3EFE29EE2DF2C55C710D94DFF4F74CE3A8A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0CE6C714D1DFB5ECDFEC5D1E7AF7986477FB9D87C3835200ED74B0F255BA40BE5A0000000000000000000000000000000000000000000000000000000000000000083406035088609184E72A000830F23D58084536ACFC480A0000000000000000000000000000000000000000000000000300B0B1CA608281DC0C0F8D5F8D1A0A92337792EDFB865166C93E433BE2DDA63F0CE37004925BF4AAEDA46B83A7B52A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA08B25F5CED570811E1792ABA151E7ED17D535F3A4DF1B86BB8B7BBDF9D7F6470AA0000000000000000000000000000000000000000000000000000000000000000083405021078609184E72A000830F279F8084536ACFBC80A0000000000000000000000000000000000000000000000000298151B815223E6BC0C0F8D5F8D1A0B8F5577B1BC38653F52A09BECF04A44A68474395519E4E91A6B371D62F49902FA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0DF793DF3C3008B4463BFA1C94F1046D68AB41A69F18B88CF41533F4FD0D85EF1A0000000000000000000000000000000000000000000000000000000000000000083404011068609184E72A000830F2B6A8084536ACFB780A00000000000000000000000000000000000000000000000008ABD522341166C97C0C0F901A6F8D3A0736E8F8996B0636061EB452EBEC32202FA5A9913C8351CAB7B01AE55FA44A74CA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA068032D387A18C14BBDCF66238E6407C91A5A0B4FEC928A0C09BC4C32DA379DE6A04B14550E0BAF8AF001834D206CED5B38A52F5152BF4D528B29A53AACB4B7136783403005058609184E72A000830F2F3582033484536ACFA680A0000000000000000000000000000000000000000000000000A7743302CFE78170F8CEF8CCF8A6808609184E72A0008227109491A10664D0CD489085A7A018BEB5245D4F2272F180B840000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011CA0C2604BD6EECA76AFCE4E7775D87960E3D4ED3B69235A3F94D6F1497C9831B50CA0664124A6B323350DD57A650434DC6BF8DDF37CD1A2686FEE377E512AA12F1214A0C84F20B2DF6ABD635BABD7AF64CD76756CD4E39C0CCB87EAAAAD609F21D1FE51820334C0F8D5F8D1A05B94E79DF6CB0B7E0843D04ABB84C4DE9BC2ECA8C83E36FEB8207B70534E016FA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0170C9F783B7417E30A163B1D99E69E4A9F39A290F8A0E0B256A2A1FE47A3763BA0000000000000000000000000000000000000000000000000000000000000000083401FFE048609184E72A000830F33028084536ACF9980A0000000000000000000000000000000000000000000000000DCBF8185EA378113C0C0F8D5F8D1A0473555DAAA9009B63CE3B73EB97896BE9855ECC29747F9052653F963989D9D73A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA0EDFAF013D7013A9C8F3BD558DC75CEB843EF5C61BA3500DD6907C90F1BE14ECCA0000000000000000000000000000000000000000000000000000000000000000083400FFB038609184E72A000830F36D08084536ACF8C80A0000000000000000000000000000000000000000000000000168588EFEC6C48D6C0C0F8D5F8D1A0A4F0DC5F3FB71FA985DC2918583309AF09EFA63913CC688B3399B30BE1C45903A01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA037918898EBCFF51F2E982E7FBAB00868DF4A5F7BDE877FCFF7E8CA4CDE3730A9A00000000000000000000000000000000000000000000000000000000000000000833FFFFC028609184E72A000830F3A9F8084536ACF8980A00000000000000000000000000000000000000000000000004D34A8977127054CC0C0F8D5F8D1A069A7356A245F9DC5B865475ADA5EE4E89B18F93C06503A9DB3B3630E88E9FB4EA01DCC4DE8DEC75D7AAB85B567B6CCD41AD312451B948A7413F0A142FD40D4934794202EFA7E3C2AADE2504A7C38E94AB6FEBCAFF43DA04EE90524267FAAAD6DCA5B718572765ABD84530EABC3286261C12031154B270EA00000000000000000000000000000000000000000000000000000000000000000833FF000018609184E72A000830F3E6F8084536ACF6E80A0000000000000000000000000000000000000000000000000754782FD1D03E7ADC0C0"; byte[] payload = Hex.decode(blocksRaw); RLPList rlpList = RLP.decode2(payload); BlocksMessage blocksMessage = new BlocksMessage(rlpList); List<Block> list = blocksMessage.getBlockDataList(); System.out.println(blocksMessage); Block block = list.get(0); } @Test /* GetChain encode */ public void test14(){ String expected = "F86514A0B4986B41E57B351FD037775A4D439443B4BDE859D061D772117AFA855BFDE18EA0241A2A72372AD63C40704C93CD380A51FEE174EB59501D731A009F51372E5205A0E963653D860F35E27A5572CFEECE1BB518C42BB97DEAC0978FA788F6DCB45CF764"; String hash1 = "B4986B41E57B351FD037775A4D439443B4BDE859D061D772117AFA855BFDE18E"; String hash2 = "241A2A72372AD63C40704C93CD380A51FEE174EB59501D731A009F51372E5205"; String hash3 = "E963653D860F35E27A5572CFEECE1BB518C42BB97DEAC0978FA788F6DCB45CF7"; GetChainMessage getChainMessage = new GetChainMessage((byte)100, Hex.decode(hash1), Hex.decode(hash2), Hex.decode(hash3)); assertEquals(expected, Hex.toHexString(getChainMessage.getPayload()).toUpperCase()); byte[] size = ByteUtil.calcPacketLength( getChainMessage.getPayload()); assertEquals("00000067", Hex.toHexString(size)); } @Test /* Transactions msg encode */ public void test15() throws Exception { String expected = "f87312f870808b00d3c21bcecceda10000009479b08ad8787060333663d19704909ee7b1903e588609184e72a000824255801ca00f410a70e42b2c9854a8421d32c87c370a2b9fff0a27f9f031bb4443681d73b5a018a7dc4c4f9dee9f3dc35cb96ca15859aa27e219a8e4a8547be6bd3206979858"; BigInteger value = new BigInteger("1000000000000000000000000"); byte[] privKey = HashUtil.sha3("cat".getBytes()); ECKey ecKey = ECKey.fromPrivate(privKey); byte[] gasPrice= Hex.decode("09184e72a000"); byte[] gas = Hex.decode("4255"); Transaction tx = new Transaction(null, value.toByteArray(), ecKey.getAddress(), gasPrice, gas, null); tx.sign(privKey); tx.getEncoded(); List<Transaction> txList = new ArrayList<Transaction>(); txList.add(tx); TransactionsMessage transactionsMessage = new TransactionsMessage(txList); assertEquals(expected, Hex.toHexString( transactionsMessage.getPayload()) ); } }
package org.jsonj; import static org.jsonj.tools.JsonBuilder.array; import static org.jsonj.tools.JsonBuilder.nullValue; import static org.jsonj.tools.JsonBuilder.object; import static org.jsonj.tools.JsonBuilder.primitive; import static org.jsonj.tools.JsonSerializer.serialize; import static org.jsonj.tools.JsonSerializer.write; import static org.testng.Assert.assertTrue; import java.io.IOException; import java.util.LinkedHashMap; import java.util.LinkedList; import org.jsonj.tools.JsonParser; import org.testng.annotations.Test; /** * Not really a test but a nice place to show off some how to use this. */ @Test public class ShowOffTheFramework { /** this could be a singleton or a spring injected object, threadsafe of course. */ private final JsonParser jsonParser = new JsonParser();; public void whatCanThisBabyDo() throws IOException { JsonObject object = object() .put("its", "just a hash map") .put("and", array( primitive("adding"), primitive("stuff"), object().put("is", "easy").get(), array("another array"))) .put("numbers", 42) .put("including_this_one", 42.0) .put("booleanstoo", true) .put("nulls_if_you_insist", nullValue()) .put("a", object().put("b", object().put("c", true).put("d", 42).put("e", "hi!").get()).get()) .put("array", array("1", "2", "etc", "varargs are nice")).get(); assertTrue(object instanceof LinkedHashMap, "JsonObject actually extends LinkedHashMap"); // get with varargs, a natural evolution for Map assertTrue(object.get("a","b","c").asPrimitive().asBoolean(), "extract stuff from a nested object"); assertTrue(object.getBoolean("a","b","c"), "or like this"); assertTrue(object.getInt("a","b","d") == 42, "or an integer"); assertTrue(object.getString("a","b","e").equals("hi!"), "or a string"); assertTrue(object.getArray("array").isArray(), "works for arrays as well"); assertTrue(object.getObject("a","b").isObject(), "and objects"); // builders are nice, but still feels kind of repetitive JsonObject anotherObject = object.getOrCreateObject("1","2","3","4"); anotherObject.put("5", "xxx"); assertTrue(object.getString("1","2","3","4","5").equals("xxx"),"yep, we just added a string value 5 levels deep"); JsonArray anotherArray = object.getOrCreateArray("5","4","3","2","1"); anotherArray.add("xxx"); assertTrue(object.getArray("5","4","3","2","1").contains("xxx"),"naturally works for arrays too"); // Lets do some other stuff assertTrue(object.equals(object), "equals is implemented as a deep equals"); assertTrue(array("a", "b").equals(array("b", "a")), "mostly you shouldn't care about the order of stuff in json"); assertTrue( object().put("a", 1).put("b", 2).get() .equals( object().put("b", 2).put("a", 1).get()), "true for objects as well"); // Arrays are lists JsonArray array = array("foo", "bar"); assertTrue(array instanceof LinkedList, "JsonArray extends LinkedList"); assertTrue(array.get(1) == array.get("bar"), "returns the same object"); assertTrue(array.contains("foo"), "obviously"); assertTrue(array.contains(primitive("foo")), "but this works as well"); // serialize like this String serialized = serialize(object); // parse it JsonElement json = jsonParser.parse(serialized); // and write it straight to some stream write(System.out, json, false); // or pretty print it like this System.out.println("\n" + serialize(json, true)); } }
package jmetest.TutorialGuide; import java.net.MalformedURLException; import java.net.URL; import java.util.Random; import com.jme.app.SimpleGame; import com.jme.bounding.BoundingSphere; import com.jme.image.Texture; import com.jme.input.KeyInput; import com.jme.input.action.AbstractInputAction; import com.jme.intersection.Intersection; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.scene.Controller; import com.jme.scene.Skybox; import com.jme.scene.Text; import com.jme.scene.TriMesh; import com.jme.scene.shape.Sphere; import com.jme.scene.state.MaterialState; import com.jme.scene.state.TextureState; import com.jme.sound.SoundAPIController; import com.jme.util.TextureManager; import com.jme.sound.SoundPool; import com.jme.sound.scene.ProgrammableSound; import com.jme.sound.scene.SoundNode; public class HelloIntersection extends SimpleGame { /** Material for my bullet */ MaterialState bulletMaterial; /** Target you're trying to hit */ Sphere target; /** Location of laser sound */ URL laserURL; /** Location of hit sound */ URL hitURL; /** Used to move target location on a hit */ Random r = new Random(); /** A sky box for our scene. */ Skybox sb; /** * The programmable sound that will be in charge of maintaining our sound * effects. */ ProgrammableSound programSound; /** The node where attached sounds will be propagated from */ SoundNode snode; /** * The ID of our laser shooting sound effect. The value is not important. It * should just be unique in our game to this sound. */ private int laserEventID = 1; private int hitEventID = 2; public static void main(String[] args) { HelloIntersection app = new HelloIntersection(); app.setDialogBehaviour(SimpleGame.ALWAYS_SHOW_PROPS_DIALOG); app.start(); } protected void simpleInitGame() { setupSound(); /** Create a + for the middle of the screen */ Text cross = new Text("Crosshairs", "+"); // 8 is half the width of a font char /** Move the + to the middle */ cross.setLocalTranslation(new Vector3f(display.getWidth() / 2f - 8f, display.getHeight() / 2f - 8f, 0)); fpsNode.attachChild(cross); target = new Sphere("my sphere", 15, 15, 1); target.setModelBound(new BoundingSphere()); target.updateModelBound(); rootNode.attachChild(target); /** Create a skybox to suround our world */ sb = new Skybox("skybox", 200, 200, 200); URL monkeyLoc = HelloIntersection.class.getClassLoader().getResource( "jmetest/data/texture/clouds.png"); TextureState ts = display.getRenderer().getTextureState(); ts.setTexture(TextureManager.loadTexture(monkeyLoc, Texture.MM_LINEAR, Texture.FM_LINEAR, true)); sb.setRenderState(ts); // Attach the skybox to our root node, and force the rootnode to show // so that the skybox will always show rootNode.attachChild(sb); rootNode.setForceView(true); /** * Set the action called "firebullet", bound to KEY_F, to performAction * FireBullet */ input.addKeyboardAction("firebullet", KeyInput.KEY_F, new FireBullet()); /** Make bullet material */ bulletMaterial = display.getRenderer().getMaterialState(); bulletMaterial.setEmissive(ColorRGBA.green); /** Make target material */ MaterialState redMaterial = display.getRenderer().getMaterialState(); redMaterial.setDiffuse(ColorRGBA.red); target.setRenderState(redMaterial); } private void setupSound() { /** init sound API acording to the rendering enviroment you're using */ SoundAPIController.getSoundSystem(properties.getRenderer()); /** Set the 'ears' for the sound API */ SoundAPIController.getRenderer().setCamera(cam); snode = new SoundNode(); /** Create program sound */ programSound = new ProgrammableSound(); /** Make the sound softer */ programSound.setGain(1f); programSound.setLooping(false); programSound.setPosition(cam.getLocation()); /** locate laser and register it with the prog sound. */ laserURL = HelloIntersection.class.getClassLoader().getResource( "jmetest/data/sound/laser.ogg"); hitURL = HelloIntersection.class.getClassLoader().getResource( "jmetest/data/sound/explosion.wav"); // Ask the system for a program id for this resource int programid = SoundPool.compile(new URL[] { laserURL }); int hitid = SoundPool.compile(new URL[] { hitURL }); // Then we bind the programid we received to our laser event id. programSound.bindEvent(laserEventID, programid); programSound.bindEvent(hitEventID, hitid); // programSound.setNextProgram(programid); snode.attachChild(programSound); //... repeat above 3 lines to register other sounds. } class FireBullet extends AbstractInputAction { int numBullets; FireBullet() { setAllowsRepeats(false); } public void performAction(float time) { System.out.println("BANG"); /** Create bullet */ Sphere bullet = new Sphere("bullet" + numBullets++, 8, 8, .25f); bullet.setModelBound(new BoundingSphere()); bullet.updateModelBound(); /** Move bullet to the camera location */ bullet.setLocalTranslation(new Vector3f(cam.getLocation())); bullet.setRenderState(bulletMaterial); /** * Update the new world locaion for the bullet before I add a * controller */ bullet.updateGeometricState(0, true); /** * Add a movement controller to the bullet going in the camera's * direction */ bullet.addController(new BulletMover(bullet, new Vector3f(cam .getDirection()))); rootNode.attachChild(bullet); bullet.updateRenderState(); /** Signal our sound to play laser during rendering */ snode.onEvent(laserEventID); } } class BulletMover extends Controller { /** Bullet that's moving */ TriMesh bullet; /** Direciton of bullet */ Vector3f direction; /** speed of bullet */ float speed = 10; /** Seconds it will last before going away */ float lifeTime = 5; BulletMover(TriMesh bullet, Vector3f direction) { this.bullet = bullet; this.direction = direction; this.direction.normalizeLocal(); } public void update(float time) { lifeTime -= time; /** If life is gone, remove it */ if (lifeTime < 0) { rootNode.detachChild(bullet); bullet.removeController(this); return; } /** Move bullet */ Vector3f bulletPos = bullet.getLocalTranslation(); bulletPos.addLocal(direction.mult(time * speed)); bullet.setLocalTranslation(bulletPos); /** Does the bullet intersect with target? */ if (Intersection.intersection(bullet.getWorldBound(), target .getWorldBound())) { System.out.println("OWCH!!!"); target.setLocalTranslation(new Vector3f(r.nextFloat() * 10, r .nextFloat() * 10, r.nextFloat() * 10)); lifeTime = 0; snode.onEvent(hitEventID); } } } /** * Called every frame for rendering */ protected void simpleRender() { // Give control to the sound in case sound changes are needed. SoundAPIController.getRenderer().draw(snode); } /** * Called every frame for updating */ protected void simpleUpdate() { // Let the programmable sound update itself. snode.updateGeometricState(tpf, true); } }
package org.jsoup.select; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.junit.Test; import static org.junit.Assert.*; /** Tests that the selector selects correctly. @author Jonathan Hedley, jonathan@hedley.net */ public class SelectorTest { @Test public void testByTag() { Elements els = Jsoup.parse("<div id=1><div id=2><p>Hello</p></div></div><div id=3>").select("div"); assertEquals(3, els.size()); assertEquals("1", els.get(0).id()); assertEquals("2", els.get(1).id()); assertEquals("3", els.get(2).id()); Elements none = Jsoup.parse("<div id=1><div id=2><p>Hello</p></div></div><div id=3>").select("span"); assertEquals(0, none.size()); } @Test public void testById() { Elements els = Jsoup.parse("<div><p id=foo>Hello</p><p id=foo>Foo two!</p></div>").select("#foo"); assertEquals(1, els.size()); assertEquals("Hello", els.get(0).text()); Elements none = Jsoup.parse("<div id=1></div>").select("#foo"); assertEquals(0, none.size()); } @Test public void testByClass() { Elements els = Jsoup.parse("<p id=0 class='one two'><p id=1 class='one'><p id=2 class='two'>").select(".one"); assertEquals(2, els.size()); assertEquals("0", els.get(0).id()); assertEquals("1", els.get(1).id()); Elements none = Jsoup.parse("<div class='one'></div>").select(".foo"); assertEquals(0, none.size()); Elements els2 = Jsoup.parse("<div class='one-two'></div>").select(".one-two"); assertEquals(1, els2.size()); } @Test public void testByAttribute() { String h = "<div Title=Foo /><div Title=Bar /><div Style=Qux /><div title=Bam /><div title=SLAM /><div />"; Document doc = Jsoup.parse(h); Elements withTitle = doc.select("[title]"); assertEquals(4, withTitle.size()); Elements foo = doc.select("[title=foo]"); assertEquals(1, foo.size()); Elements not = doc.select("div[title!=bar]"); assertEquals(5, not.size()); assertEquals("Foo", not.first().attr("title")); Elements starts = doc.select("[title^=ba]"); assertEquals(2, starts.size()); assertEquals("Bar", starts.first().attr("title")); assertEquals("Bam", starts.last().attr("title")); Elements ends = doc.select("[title$=am]"); assertEquals(2, ends.size()); assertEquals("Bam", ends.first().attr("title")); assertEquals("SLAM", ends.last().attr("title")); Elements contains = doc.select("[title*=a]"); assertEquals(3, contains.size()); assertEquals("Bar", contains.first().attr("title")); assertEquals("SLAM", contains.last().attr("title")); } @Test public void testAllElements() { String h = "<div><p>Hello</p><p><b>there</b></p></div>"; Document doc = Jsoup.parse(h); Elements allDoc = doc.select("*"); Elements allUnderDiv = doc.select("div *"); assertEquals(8, allDoc.size()); assertEquals(3, allUnderDiv.size()); assertEquals("p", allUnderDiv.first().tagName()); } @Test public void testAllWithClass() { String h = "<p class=first>One<p class=first>Two<p>Three"; Document doc = Jsoup.parse(h); Elements ps = doc.select("*.first"); assertEquals(2, ps.size()); } @Test public void testGroupOr() { String h = "<div title=foo /><div title=bar /><div /><p></p><img /><span title=qux>"; Document doc = Jsoup.parse(h); Elements els = doc.select("p,div,[title]"); assertEquals(5, els.size()); assertEquals("p", els.get(0).tagName()); assertEquals("div", els.get(1).tagName()); assertEquals("foo", els.get(1).attr("title")); assertEquals("div", els.get(2).tagName()); assertEquals("bar", els.get(2).attr("title")); assertEquals("div", els.get(3).tagName()); assertTrue(els.get(3).attr("title").isEmpty()); // missing attributes come back as empty string assertFalse(els.get(3).hasAttr("title")); assertEquals("span", els.get(4).tagName()); } @Test public void testGroupOrAttribute() { String h = "<div id=1 /><div id=2 /><div title=foo /><div title=bar />"; Elements els = Jsoup.parse(h).select("[id],[title=foo]"); assertEquals(3, els.size()); assertEquals("1", els.get(0).id()); assertEquals("2", els.get(1).id()); assertEquals("foo", els.get(2).attr("title")); } @Test public void descendant() { String h = "<div class=head><p class=first>Hello</p><p>There</p></div><p>None</p>"; Document doc = Jsoup.parse(h); Elements els = doc.select(".head p"); assertEquals(2, els.size()); assertEquals("Hello", els.get(0).text()); assertEquals("There", els.get(1).text()); Elements p = doc.select("p.first"); assertEquals(1, p.size()); assertEquals("Hello", p.get(0).text()); } @Test public void and() { String h = "<div id=1 class='foo bar' title=bar name=qux><p class=foo title=bar>Hello</p></div"; Document doc = Jsoup.parse(h); Elements div = doc.select("div.foo"); assertEquals(1, div.size()); assertEquals("div", div.first().tagName()); Elements p = doc.select("div .foo"); // space indicates like "div *.foo" assertEquals(1, p.size()); assertEquals("p", p.first().tagName()); Elements div2 = doc.select("div#1.foo.bar[title=bar][name=qux]"); // very specific! assertEquals(1, div2.size()); assertEquals("div", div2.first().tagName()); Elements p2 = doc.select("div *.foo"); // space indicates like "div *.foo" assertEquals(1, p2.size()); assertEquals("p", p2.first().tagName()); } @Test public void deeperDescendant() { String h = "<div class=head><p><span class=first>Hello</div><div class=head><p class=first><span>Another</span><p>Again</div>"; Elements els = Jsoup.parse(h).select("div p .first"); assertEquals(1, els.size()); assertEquals("Hello", els.first().text()); assertEquals("span", els.first().tagName()); } @Test public void parentChildElement() { String h = "<div id=1><div id=2><div id = 3></div></div></div><div id=4></div>"; Document doc = Jsoup.parse(h); Elements divs = doc.select("div > div"); assertEquals(2, divs.size()); assertEquals("2", divs.get(0).id()); // 2 is child of 1 assertEquals("3", divs.get(1).id()); // 3 is child of 2 Elements div2 = doc.select("div#1 > div"); assertEquals(1, div2.size()); assertEquals("2", div2.get(0).id()); } @Test public void parentChildStar() { String h = "<div id=1><p>Hello<p><b>there</b></p></div><div id=2><span>Hi</span></div>"; Document doc = Jsoup.parse(h); Elements divChilds = doc.select("div > *"); assertEquals(3, divChilds.size()); assertEquals("p", divChilds.get(0).tagName()); assertEquals("p", divChilds.get(1).tagName()); assertEquals("span", divChilds.get(2).tagName()); } @Test public void caseInsensitive() { String h = "<dIv tItle=bAr><div>"; // mixed case so a simple toLowerCase() on value doesn't catch Document doc = Jsoup.parse(h); assertEquals(2, doc.select("DIV").size()); assertEquals(1, doc.select("DIV[TITLE]").size()); assertEquals(1, doc.select("DIV[TITLE=BAR]").size()); assertEquals(0, doc.select("DIV[TITLE=BARBARELLA").size()); } }
package org.devcloud.snippets.app; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import java.io.IOException; public class MainActivity extends FragmentActivity { private static final String TAG = "MainActivity"; private int post_fragment_id, list_fragment_id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { Fragment list_fragment = new SnippetListFragment(); Fragment post_fragment = new NewPostFragment(); getSupportFragmentManager().beginTransaction() .add(R.id.container,post_fragment) .add(R.id.container, list_fragment) .commit(); // Save IDs list_fragment_id = list_fragment.getId(); post_fragment_id = post_fragment.getId(); } } public void saveMessage(View view) { // Get the text. EditText editText = (EditText) findViewById(R.id.edit_message); String message = editText.getText().toString(); Context context = getApplicationContext(); try { // Save the text. Snippet snippet = new Snippet(message); snippet.save(context); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } Intent intent = new Intent(context, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); context.startActivity(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package br.univel; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.transform.stream.StreamResult; public class GravaXml { public String gravaXml (Object obj){ StringWriter out = new StringWriter(); JAXBContext context; Class<?> classe = obj.getClass(); try { context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(obj, new StreamResult(out)); String xml = out.toString(); FileWriter fw = new FileWriter(classe.getSimpleName() +".xml"); fw.write(xml); fw.close(); return out.toString(); } catch (JAXBException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } } }
/** * <p>: JsonView.java</p> * <p>: </p> * <p>: YMateSoft Co., Ltd.</p> * <p> yMatePlatform-WebMVC</p> * <p> (suninformation@163.com)</p> */ package net.ymate.platform.mvc.web.view.impl; import javax.servlet.http.HttpServletResponse; import net.ymate.platform.mvc.web.context.WebContext; import net.ymate.platform.mvc.web.view.AbstractWebView; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * <p> * JsonView * </p> * <p> * JSON * </p> * * @author (suninformation@163.com) * @version 0.0.0 * <table style="border:1px solid gray;"> * <tr> * <th width="100px"></th><th width="100px"></th><th * width="100px"></th><th width="100px"></th> * </tr> * <!-- Table --> * <tr> * <td>0.0.0</td> * <td></td> * <td></td> * <td>2011-10-2311:27:16</td> * </tr> * </table> */ public class JsonView extends AbstractWebView { public static final String JSON_CONTENT_TYPE = "application/json;charset=utf-8"; protected Object jsonObj; protected boolean withJsonContent; protected String jsonpCallback; /** * * @param obj JSON */ public JsonView(JSONObject jsonObj) { this.jsonObj = jsonObj; } /** * * * @param jsonArr JSON */ public JsonView(JSONArray jsonArr) { this.jsonObj = jsonArr; } /** * * * @param jsonStr JSON * @throws JSONException JSON */ public JsonView(String jsonStr) throws JSONException { if (StringUtils.isNotBlank(jsonStr) && jsonStr.trim().charAt(0) == '[') { this.jsonObj = new JSONArray(jsonStr); } else { this.jsonObj = new JSONObject(jsonStr); } } /** * @return ContentType"application/json" */ public JsonView withJsonContentType() { this.withJsonContent = true; return this; } /** * @param callback * @return JSONPcallbackcallback */ public JsonView withJsonpCallback(String callback) { this.jsonpCallback = StringUtils.defaultIfEmpty(callback, null); return this; } /* (non-Javadoc) * @see net.ymate.platform.mvc.web.view.AbstractWebView#renderView() */ protected void renderView() throws Exception { HttpServletResponse response = WebContext.getResponse(); if (StringUtils.isNotBlank(getContentType())) { response.setContentType(getContentType()); } else if (withJsonContent) { response.setContentType(JSON_CONTENT_TYPE); } StringBuilder _jsonStr = new StringBuilder(jsonObj.toString()); if (this.jsonpCallback != null) { _jsonStr.insert(0, this.jsonpCallback + "(").append(");"); } IOUtils.write(_jsonStr.toString(), response.getOutputStream()); } }
package org.msf.records.ui; import android.app.Activity; import android.content.ContentUris; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import com.android.volley.Response; import com.android.volley.VolleyError; import com.google.common.base.Charsets; import org.json.JSONObject; import org.msf.records.App; import org.msf.records.events.CreatePatientSucceededEvent; import org.msf.records.net.OdkDatabase; import org.msf.records.net.OdkXformSyncTask; import org.msf.records.net.OpenMrsXformIndexEntry; import org.msf.records.net.OpenMrsXformsConnection; import org.odk.collect.android.activities.FormEntryActivity; import org.odk.collect.android.activities.FormHierarchyActivity; import org.odk.collect.android.application.Collect; import org.odk.collect.android.listeners.FormLoaderListener; import org.odk.collect.android.logic.FormController; import org.odk.collect.android.provider.FormsProviderAPI; import org.odk.collect.android.provider.InstanceProviderAPI; import org.odk.collect.android.tasks.DeleteInstancesTask; import org.odk.collect.android.tasks.FormLoaderTask; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.List; import javax.annotation.Nullable; import de.greenrobot.event.EventBus; import static android.provider.BaseColumns._ID; import static org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns.CONTENT_URI; import static org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns.INSTANCE_FILE_PATH; import static org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns.JR_FORM_ID; /** * Convenience class for launching ODK to display an Xform. */ public class OdkActivityLauncher { private static final String TAG = "OdkActivityLauncher"; public static void fetchAndShowXform(final Activity callingActivity, final String uuidToShow, final int requestCode) { new OpenMrsXformsConnection(App.getConnectionDetails()).listXforms( new Response.Listener<List<OpenMrsXformIndexEntry>>() { @Override public void onResponse(final List<OpenMrsXformIndexEntry> response) { if (response.isEmpty()) { Log.i(TAG, "No forms found"); return; } // Cache all the forms into the ODK form cache new OdkXformSyncTask(new OdkXformSyncTask.FormWrittenListener() { @Override public void formWritten(File path, String uuid) { Log.i(TAG, "wrote form " + path); showOdkCollect(callingActivity, requestCode, OdkDatabase.getFormIdForPath(path)); } }).execute(findUuid(response, uuidToShow)); } }, getErrorListenerForTag(TAG)); } public static void showOdkCollect(Activity callingActivity, int requestCode, long formId) { Intent intent = new Intent(callingActivity, FormEntryActivity.class); Uri formUri = ContentUris.withAppendedId(FormsProviderAPI.FormsColumns.CONTENT_URI, formId); intent.setData(formUri); intent.setAction(Intent.ACTION_PICK); callingActivity.startActivityForResult(intent, requestCode); } /** * Convenient shared code for handling an ODK activity result. * * @param callingActivity the calling activity, used for getting content resolvers * @param patientUuid the patient to add an observation to, or null to create a new patient * @param resultCode the result code sent from Android activity transition * @param data the incoming intent */ public static void sendOdkResultToServer( Activity callingActivity, @Nullable String patientUuid, int resultCode, Intent data) { if (resultCode == Activity.RESULT_CANCELED) { return; } if (data == null || data.getData() == null) { // Cancelled. Log.i(TAG, "No data for form result, probably cancelled."); return; } Uri uri = data.getData(); if (!callingActivity.getContentResolver().getType(uri).equals( InstanceProviderAPI.InstanceColumns.CONTENT_ITEM_TYPE)) { Log.e(TAG, "Tried to load a content URI of the wrong type: " + uri); return; } Cursor instanceCursor = null; try { instanceCursor = callingActivity.getContentResolver().query(uri, null, null, null, null); if (instanceCursor.getCount() != 1) { Log.e(TAG, "The form that we tried to load did not exist: " + uri); return; } instanceCursor.moveToFirst(); String instancePath = instanceCursor.getString( instanceCursor.getColumnIndex(INSTANCE_FILE_PATH)); if (instancePath == null) { Log.e(TAG, "No file path for form instance: " + uri); return; } int columnIndex = instanceCursor .getColumnIndex(_ID); if (columnIndex == -1) { Log.e(TAG, "No id to delete for after upload: " + uri); return; } final long idToDelete = instanceCursor.getLong(columnIndex); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(callingActivity.getApplicationContext()); final boolean keepFormInstancesLocally = preferences.getBoolean("keep_form_instances_locally", false); sendFormToServer(patientUuid, readFromPath(instancePath), new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.i(TAG, "Created new patient successfully on server" + response.toString()); if (!keepFormInstancesLocally) { //Code largely copied from InstanceUploaderTask to delete on upload DeleteInstancesTask dit = new DeleteInstancesTask(); dit.setContentResolver( Collect.getInstance().getApplication().getContentResolver()); dit.execute(idToDelete); EventBus.getDefault().post(new CreatePatientSucceededEvent()); } } }); } catch (IOException e) { Log.e(TAG, "Failed to read xml form into a String " + uri, e); } finally { if (instanceCursor != null) { instanceCursor.close(); } } } private static void sendFormToServer(String patientUuid, String xml, Response.Listener<JSONObject> successListener) { OpenMrsXformsConnection connection = new OpenMrsXformsConnection(App.getConnectionDetails()); connection.postXformInstance(patientUuid, xml, successListener, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Did not submit form to server successfully", error); if (error.networkResponse != null && error.networkResponse.statusCode == 500) { Log.e(TAG, "Internal error stack trace:\n"); Log.e(TAG, new String(error.networkResponse.data, Charsets.UTF_8)); } } }); } private static String readFromPath(String path) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new FileReader(path)); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } // Out of a list of OpenMRS Xform entries, find the form that matches the given uuid, or // return null if no xform is found. private static OpenMrsXformIndexEntry findUuid(List<OpenMrsXformIndexEntry> allEntries, String uuid) { for (OpenMrsXformIndexEntry entry : allEntries) { if (entry.uuid.equals(uuid)) { return entry; } } return null; } private static Response.ErrorListener getErrorListenerForTag(final String tag) { return new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(tag, error.toString()); } }; } /** * Show the ODK activity for viewing a saved form. * * @param caller the calling activity. */ public static void showSavedXform(final Activity caller) { // This has to be at the start of anything that uses the ODK file system. Collect.createODKDirs(); final String selection = InstanceProviderAPI.InstanceColumns.STATUS + " != ?"; final String[] selectionArgs = {InstanceProviderAPI.STATUS_SUBMITTED}; final String sortOrder = InstanceProviderAPI.InstanceColumns.STATUS + " DESC, " + InstanceProviderAPI.InstanceColumns.DISPLAY_NAME + " ASC"; final Uri instanceUri; final String instancePath; final String jrFormId; Cursor instanceCursor = null; try { instanceCursor = caller.getContentResolver().query( CONTENT_URI, new String[]{_ID, INSTANCE_FILE_PATH, JR_FORM_ID}, selection, selectionArgs, sortOrder); if (instanceCursor.getCount() == 0) { return; } instanceCursor.moveToFirst(); // The URI code mostly copied from InstanceChooserList.onListItemClicked() instanceUri = ContentUris.withAppendedId(CONTENT_URI, instanceCursor.getLong(instanceCursor.getColumnIndex(_ID))); instancePath = instanceCursor.getString(instanceCursor.getColumnIndex(INSTANCE_FILE_PATH)); jrFormId = instanceCursor.getString(instanceCursor.getColumnIndex(JR_FORM_ID)); } finally { if (instanceCursor != null) { instanceCursor.close(); } } // It looks like we need to load the form as well. Which is odd, because // the main menu doesn't seem to do this, but without the FormLoaderTask run // there is no form manager for the HierarchyActivity. FormLoaderTask loaderTask = new FormLoaderTask(instancePath, null, null); final String formPath; Cursor formCursor = null; try { formCursor = caller.getContentResolver().query( FormsProviderAPI.FormsColumns.CONTENT_URI, new String[]{FormsProviderAPI.FormsColumns.FORM_FILE_PATH}, FormsProviderAPI.FormsColumns.JR_FORM_ID + " = ?", new String[]{jrFormId}, null); if (formCursor.getCount() == 0) { Log.e(TAG, "Loading forms for displaying " + jrFormId + " and got no forms,"); return; } if (formCursor.getCount() != 1) { Log.e(TAG, "Loading forms for displaying instance, expected only 1. Got multiple so using first."); } formCursor.moveToFirst(); formPath = formCursor.getString( formCursor.getColumnIndex(FormsProviderAPI.FormsColumns.FORM_FILE_PATH)); } finally { if (formCursor != null) { formCursor.close(); } } loaderTask.setFormLoaderListener(new FormLoaderListener() { @Override public void loadingComplete(FormLoaderTask task) { // This was extracted from FormEntryActivity.loadingComplete() FormController formController = task.getFormController(); Collect.getInstance().setFormController(formController); Intent intent = new Intent(caller, FormHierarchyActivity.class); intent.setData(instanceUri); intent.setAction(Intent.ACTION_PICK); caller.startActivity(intent); } @Override public void loadingError(String errorMsg) { } @Override public void onProgressStep(String stepMessage) { } }); loaderTask.execute(formPath); } }
package net.sf.mzmine.userinterface.mainwindow; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import javax.imageio.ImageIO; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JDesktopPane; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JLayeredPane; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JSplitPane; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.border.EtchedBorder; import net.sf.mzmine.data.ParameterSet; import net.sf.mzmine.data.PeakList; import net.sf.mzmine.io.PreloadLevel; import net.sf.mzmine.io.RawDataFile; import net.sf.mzmine.main.MZmineCore; import net.sf.mzmine.main.MZmineModule; import net.sf.mzmine.taskcontrol.impl.TaskControllerImpl; import net.sf.mzmine.userinterface.Desktop; import net.sf.mzmine.userinterface.components.TaskProgressWindow; import net.sf.mzmine.userinterface.dialogs.AboutDialog; import net.sf.mzmine.util.NumberFormatter; import org.simplericity.macify.eawt.Application; import org.simplericity.macify.eawt.ApplicationEvent; import org.simplericity.macify.eawt.ApplicationListener; import org.simplericity.macify.eawt.DefaultApplication; /** * This class is the main window of application * */ public class MainWindow extends JFrame implements MZmineModule, Desktop, WindowListener, ApplicationListener { // default tooltip displaying and dismissing delay in ms public static final int DEFAULT_TOOLTIP_DELAY = 50; public static final int DEFAULT_TOOLTIP_DISMISS_DELAY = Integer.MAX_VALUE; private DesktopParameters parameters; private JDesktopPane desktopPane; private JSplitPane split; private ItemSelector itemSelector; private TaskProgressWindow taskList; public TaskProgressWindow getTaskList() { return taskList; } private MainMenu menuBar; private Statusbar statusBar; public MainMenu getMainMenu() { return menuBar; } public void addInternalFrame(JInternalFrame frame) { desktopPane.add(frame, JLayeredPane.DEFAULT_LAYER); // TODO: adjust frame position frame.setVisible(true); } /** * This method returns the desktop */ public JDesktopPane getDesktopPane() { return desktopPane; } /** * WindowListener interface implementation */ public void windowOpened(WindowEvent e) { } public void windowClosing(WindowEvent e) { MZmineCore.exitMZmine(); } public void windowClosed(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } public void setStatusBarText(String text) { setStatusBarText(text, Color.black); } /** * @see net.sf.mzmine.userinterface.Desktop#displayMessage(java.lang.String) */ public void displayMessage(String msg) { JOptionPane.showMessageDialog(this, msg, "Message", JOptionPane.INFORMATION_MESSAGE); } public void displayErrorMessage(String msg) { JOptionPane.showMessageDialog(this, msg, "Sorry", JOptionPane.ERROR_MESSAGE); } public void addMenuItem(MZmineMenu parentMenu, JMenuItem newItem) { menuBar.addMenuItem(parentMenu, newItem); } /** * @see net.sf.mzmine.userinterface.Desktop#getSelectedDataFiles() */ public RawDataFile[] getSelectedDataFiles() { return itemSelector.getSelectedRawData(); } public PeakList[] getSelectedPeakLists() { return itemSelector.getSelectedPeakLists(); } public void addAlignedPeakList(PeakList alignmentResult) { itemSelector.addPeakList(alignmentResult); } public void addDataFile(RawDataFile dataFile) { itemSelector.addRawData(dataFile); } public void removeAlignedPeakList(PeakList alignmentResult) { itemSelector.removePeakList(alignmentResult); } public void removeDataFile(RawDataFile dataFile) { itemSelector.removeRawData(dataFile); } public void initModule() { parameters = new DesktopParameters(); // Create an abstract Application, for better Mac OS X support (using Application application = new DefaultApplication(); application.addApplicationListener(this); try { BufferedImage MZmineIcon = ImageIO.read(new File( "icons/MZmineIcon.png")); setIconImage(MZmineIcon); application.setApplicationIconImage(MZmineIcon); } catch (IOException e) { e.printStackTrace(); } Font defaultFont = new Font("SansSerif", Font.PLAIN, 13); Font smallFont = new Font("SansSerif", Font.PLAIN, 11); Font tinyFont = new Font("SansSerif", Font.PLAIN, 10); Enumeration keys = UIManager.getDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); Object value = UIManager.get(key); if (value instanceof Font) UIManager.put(key, defaultFont); } UIManager.put("List.font", smallFont); UIManager.put("Table.font", smallFont); UIManager.put("ToolTip.font", tinyFont); // Initialize item selector itemSelector = new ItemSelector(this); // Place objects on main window desktopPane = new JDesktopPane(); split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, itemSelector, desktopPane); desktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); desktopPane.setBorder(new EtchedBorder(EtchedBorder.RAISED)); Container c = getContentPane(); c.setLayout(new BorderLayout()); c.add(split, BorderLayout.CENTER); statusBar = new Statusbar(); c.add(statusBar, BorderLayout.SOUTH); // Construct menu menuBar = new MainMenu(); setJMenuBar(menuBar); // Initialize window listener for responding to user events addWindowListener(this); pack(); // TODO: check screen size? setBounds(0, 0, 1000, 700); setLocationRelativeTo(null); // Application wants to control closing by itself setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); setTitle("MZmine II"); taskList = new TaskProgressWindow( (TaskControllerImpl) MZmineCore.getTaskController()); desktopPane.add(taskList, JLayeredPane.DEFAULT_LAYER); ToolTipManager tooltipManager = ToolTipManager.sharedInstance(); tooltipManager.setInitialDelay(DEFAULT_TOOLTIP_DELAY); tooltipManager.setDismissDelay(DEFAULT_TOOLTIP_DISMISS_DELAY); } /** * @see net.sf.mzmine.userinterface.Desktop#getMainFrame() */ public JFrame getMainFrame() { return this; } /** * @see net.sf.mzmine.userinterface.Desktop#isDataFileSelected() */ public boolean isDataFileSelected() { return itemSelector.getSelectedRawData().length > 0; } /** * @see net.sf.mzmine.userinterface.Desktop#isDataFileSelected() */ public boolean isPeakListSelected() { return itemSelector.getSelectedPeakLists().length > 0; } /** * @see net.sf.mzmine.userinterface.Desktop#addMenuItem(net.sf.mzmine.userinterface.Desktop.MZmineMenu, * java.lang.String, java.awt.event.ActionListener, java.lang.String, * int, boolean, boolean) */ public JMenuItem addMenuItem(MZmineMenu parentMenu, String text, ActionListener listener, String actionCommand, int mnemonic, boolean setAccelerator, boolean enabled) { return menuBar.addMenuItem(parentMenu, text, listener, actionCommand, mnemonic, setAccelerator, enabled); } /** * @see net.sf.mzmine.userinterface.Desktop#addMenuSeparator(net.sf.mzmine.userinterface.Desktop.MZmineMenu) */ public void addMenuSeparator(MZmineMenu parentMenu) { menuBar.addMenuSeparator(parentMenu); } /** * @see net.sf.mzmine.userinterface.Desktop#getSelectedFrame() */ public JInternalFrame getSelectedFrame() { return desktopPane.getSelectedFrame(); } /** * @see net.sf.mzmine.userinterface.Desktop#getVisibleFrames() */ public JInternalFrame[] getVisibleFrames() { return getVisibleFrames(JInternalFrame.class); } /** * @see net.sf.mzmine.userinterface.Desktop#getVisibleFrames() */ public JInternalFrame[] getVisibleFrames(Class frameClass) { JInternalFrame[] allFrames = desktopPane.getAllFrames(); ArrayList<JInternalFrame> visibleFrames = new ArrayList<JInternalFrame>(); for (JInternalFrame frame : allFrames) if (frame.isVisible() && (frameClass.isInstance(frame))) visibleFrames.add(frame); return visibleFrames.toArray(new JInternalFrame[0]); } /** * @see net.sf.mzmine.userinterface.Desktop#setStatusBarText(java.lang.String, * java.awt.Color) */ public void setStatusBarText(String text, Color textColor) { statusBar.setStatusText(text, textColor); } public Statusbar getStatusBar() { return statusBar; } /** * @see net.sf.mzmine.userinterface.Desktop#getMZFormatProvider() */ public NumberFormatter getMZFormat() { return parameters.getMZFormat(); } /** * @see net.sf.mzmine.userinterface.Desktop#getRTFormatProvider() */ public NumberFormatter getRTFormat() { return parameters.getRTFormat(); } /** * @see net.sf.mzmine.userinterface.Desktop#getIntensityFormatProvider() */ public NumberFormatter getIntensityFormat() { return parameters.getIntensityFormat(); } /** * @see net.sf.mzmine.main.MZmineModule#getParameterSet() */ public DesktopParameters getParameterSet() { return parameters; } /** * @see net.sf.mzmine.main.MZmineModule#setParameters(net.sf.mzmine.data.ParameterSet) */ public void setParameters(ParameterSet parameterValues) { this.parameters = (DesktopParameters) parameterValues; } public ItemSelector getItemSelector() { return itemSelector; } public void handleAbout(ApplicationEvent event) { AboutDialog dialog = new AboutDialog(); dialog.setVisible(true); event.setHandled(true); } public void handleOpenApplication(ApplicationEvent event) { // ignore } public void handleOpenFile(ApplicationEvent event) { File file = new File(event.getFilename()); MZmineCore.getIOController().openFiles(new File[] { file }, PreloadLevel.NO_PRELOAD); event.setHandled(true); } public void handlePreferences(ApplicationEvent event) { // ignore } public void handlePrintFile(ApplicationEvent event) { // ignore } public void handleQuit(ApplicationEvent event) { MZmineCore.exitMZmine(); event.setHandled(false); } public void handleReopenApplication(ApplicationEvent event) { // ignore } }
package org.msf.records.ui; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ExpandableListView; import android.widget.ListView; import org.msf.records.App; import org.msf.records.R; import org.msf.records.events.CreatePatientSucceededEvent; import org.msf.records.model.Location; import org.msf.records.net.Constants; import org.msf.records.sync.GenericAccountService; import org.msf.records.sync.PatientProviderContract; import de.greenrobot.event.EventBus; /** * A list fragment representing a list of Patients. This fragment * also supports tablet devices by allowing list items to be given an * 'activated' state upon selection. This helps indicate which item is * currently being viewed in a {@link PatientDetailFragment}. * <p> * Activities containing this fragment MUST implement the {@link Callbacks} * interface. */ public class PatientListFragment extends ProgressFragment implements ExpandableListView.OnChildClickListener, SwipeRefreshLayout.OnRefreshListener, LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = PatientListFragment.class.getSimpleName(); private static final String ITEM_LIST_KEY = "ITEM_LIST_KEY"; /** * The serialization (saved instance state) Bundle key representing the * activated item position. Only used on tablets. */ private static final String STATE_ACTIVATED_POSITION = "activated_position"; /** * The id to identify which Cursor is returned */ private static final int LOADER_LIST_ID = 0; /** * The fragment's current callback object, which is notified of list item * clicks. */ private Callbacks mCallbacks = sDummyCallbacks; /** * The current activated item position. Only used on tablets. */ private int mActivatedPosition = ListView.INVALID_POSITION; private ExpandablePatientListAdapter mPatientAdapter; private ExpandableListView mListView; private SwipeRefreshLayout mSwipeToRefresh; private boolean isRefreshing; String mFilterLocation; String mFilterQueryTerm; String mFilterState; /** * Projection for querying the content provider. */ private static final String[] PROJECTION = new String[] { PatientProviderContract.PatientColumns._ID, PatientProviderContract.PatientColumns.COLUMN_NAME_LOCATION_TENT, PatientProviderContract.PatientColumns.COLUMN_NAME_GIVEN_NAME, PatientProviderContract.PatientColumns.COLUMN_NAME_FAMILY_NAME, PatientProviderContract.PatientColumns.COLUMN_NAME_UUID, PatientProviderContract.PatientColumns.COLUMN_NAME_STATUS, PatientProviderContract.PatientColumns.COLUMN_NAME_ADMISSION_TIMESTAMP }; // Constants representing column positions from PROJECTION. public static final int COLUMN_ID = 0; public static final int COLUMN_LOCATION_TENT = 1; public static final int COLUMN_GIVEN_NAME = 2; public static final int COLUMN_FAMILY_NAME = 3; public static final int COLUMN_UUID = 4; public static final int COLUMN_STATUS = 5; public static final int COLUMN_ADMISSION_TIMESTAMP = 6; /** * A callback interface that all activities containing this fragment must * implement. This mechanism allows activities to be notified of item * selections. */ public interface Callbacks { /** * Callback for when an item has been selected. */ public void onItemSelected(String uuid, String givenName, String familyName, String id); } /** * A dummy implementation of the {@link Callbacks} interface that does * nothing. Used only when this fragment is not attached to an activity. */ private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onItemSelected(String uuid, String givenName, String familyName, String id) { } }; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public PatientListFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_patient_list); } @Override public void onResume() { super.onResume(); EventBus.getDefault().register(this); } @Override public void onPause() { EventBus.getDefault().unregister(this); super.onPause(); } @Override public void onRefresh() { if(!isRefreshing){ Log.d(TAG, "onRefresh"); //triggers app wide data refresh GenericAccountService.triggerRefresh(); isRefreshing = true; } } private void stopRefreshing(){ if(isRefreshing){ mSwipeToRefresh.setRefreshing(false); isRefreshing = false; } } private void loadSearchResults(){ getLoaderManager().initLoader(LOADER_LIST_ID, null, this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mListView = (ExpandableListView) view.findViewById(R.id.fragment_patient_list); mListView.setOnChildClickListener(this); mSwipeToRefresh = (SwipeRefreshLayout) view.findViewById(R.id.fragment_patient_list_swipe_to_refresh); mSwipeToRefresh.setOnRefreshListener(this); Button allLocationsButton = (Button) view.findViewById(R.id.patient_list_all_locations); allLocationsButton.setOnClickListener(onClickListener); mPatientAdapter = new ExpandablePatientListAdapter(null, getActivity()); mListView.setAdapter(mPatientAdapter); loadSearchResults(); // Restore the previously serialized activated item position. if (savedInstanceState != null && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) { setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION)); } ((PatientListActivity)getActivity()).setOnSearchListener(new PatientListActivity.OnSearchListener() { @Override public void setQuerySubmitted(String q) { App.getServer().cancelPendingRequests(TAG); isRefreshing = false; mFilterQueryTerm = q; changeState(State.LOADING); onRefresh(); } }); } private View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(final View v) { switch(v.getId()){ case R.id.patient_list_all_locations: FragmentManager fm = getChildFragmentManager(); ListDialogFragment dialogListFragment = new ListDialogFragment(); Bundle bundle = new Bundle(); bundle.putParcelableArray(ITEM_LIST_KEY, Location.getLocation()); dialogListFragment.setArguments(bundle); dialogListFragment.show(fm, null); break; } } }; @Override public void onAttach(Activity activity) { super.onAttach(activity); // Activities containing this fragment must implement its callbacks. if (!(activity instanceof Callbacks)) { throw new IllegalStateException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; if(Constants.OFFLINE_SUPPORT){ // Create account, if needed GenericAccountService.registerSyncAccount(activity); } } @Override public void onDetach() { super.onDetach(); // Reset the active callbacks interface to the dummy implementation. mCallbacks = sDummyCallbacks; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mActivatedPosition != ListView.INVALID_POSITION) { // Serialize and persist the activated item position. outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); } } @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { Cursor childCursor = mPatientAdapter.getChild(groupPosition, childPosition); mCallbacks.onItemSelected( childCursor.getString(ExpandablePatientListAdapter.COLUMN_UUID), childCursor.getString(ExpandablePatientListAdapter.COLUMN_GIVEN_NAME), childCursor.getString(ExpandablePatientListAdapter.COLUMN_FAMILY_NAME), childCursor.getString(ExpandablePatientListAdapter.COLUMN_ID)); return true; } public void onEvent(CreatePatientSucceededEvent event) { if(!isRefreshing){ isRefreshing = true; loadSearchResults(); } } /** * Turns on activate-on-click mode. When this mode is on, list items will be * given the 'activated' state when touched. */ public void setActivateOnItemClick(boolean activateOnItemClick) { // When setting CHOICE_MODE_SINGLE, ListView will automatically // give items the 'activated' state when touched. mListView.setChoiceMode(activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE); } private void setActivatedPosition(int position) { if (position == ListView.INVALID_POSITION) { mListView.setItemChecked(mActivatedPosition, false); } else { mListView.setItemChecked(position, true); } mActivatedPosition = position; } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { return new CursorLoader(getActivity(), // Context PatientProviderContract.CONTENT_URI_PATIENT_TENTS, // URI PROJECTION, // Projection null, // Selection null, // Selection args PatientProviderContract.PatientColumns.COLUMN_NAME_ADMISSION_TIMESTAMP + " desc"); // Sort } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { // Swap the new cursor in. int id = cursorLoader.getId(); Log.d(TAG, "onLoadFinsihed id: " + id); if (id == LOADER_LIST_ID) { mPatientAdapter.setGroupCursor(cursor); changeState(State.LOADED); stopRefreshing(); } } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { // This is called when the last Cursor provided to onLoadFinished() // is about to be closed. int id = cursorLoader.getId(); if (id != LOADER_LIST_ID) { // child cursor try { mPatientAdapter.setChildrenCursor(id, null); } catch (NullPointerException e) { Log.w(TAG, "Adapter expired, try again on the next query: " + e.getMessage()); } } else { mPatientAdapter.setGroupCursor(null); } } }
package net.x4a42.volksempfaenger.service; import net.x4a42.volksempfaenger.PreferenceKeys; import net.x4a42.volksempfaenger.R; import net.x4a42.volksempfaenger.Utils; import net.x4a42.volksempfaenger.VolksempfaengerApplication; import net.x4a42.volksempfaenger.data.DatabaseHelper; import net.x4a42.volksempfaenger.net.EnclosureDownloader; import android.app.DownloadManager; import android.app.DownloadManager.Query; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.BatteryManager; import android.os.IBinder; import android.util.Log; public class DownloadService extends Service { private VolksempfaengerApplication app; private DatabaseHelper dbHelper; private int phonePlugged; private static final int NETWORK_WIFI = 1; private static final int NETWORK_MOBILE = 2; private class DownloadTask extends AsyncTask<Long, Void, Void> { @Override protected Void doInBackground(Long... params) { Log.d(getClass().getSimpleName(), "doInBackground()"); SharedPreferences prefs = app.getSharedPreferences(); int networkAllowd = 0; // if automatic downloading is enabled, downloading via WiFi is // enabled networkAllowd |= NETWORK_WIFI; if (!prefs .getBoolean( PreferenceKeys.DOWNLOAD_WIFI, Utils.stringBoolean(getString(R.string.settings_default_download_wifi)))) { // downloading is not restricted to WiFi networkAllowd |= NETWORK_MOBILE; } if (params == null) { // check if automatic downloads are allowed if (!prefs .getBoolean( PreferenceKeys.DOWNLOAD_AUTO, Utils.stringBoolean(getString(R.string.settings_default_download_auto)))) { // automatic downloading is disabled Log.d(getClass().getSimpleName(), "automatic downloading is disabled"); return null; } if (phonePlugged == 0 && prefs.getBoolean( PreferenceKeys.DOWNLOAD_CHARGING, Utils.stringBoolean(getString(R.string.settings_default_download_charging)))) { // downloading is only allowed while charging but phone is // not plugged in Log.d(getClass().getSimpleName(), "phone is not plugged in"); return null; } int networkType = 0; // get network state ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); if (!cm.getBackgroundDataSetting()) { // background data is disabled Log.d(getClass().getSimpleName(), "background data is disabled"); return null; } NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.getState() == NetworkInfo.State.CONNECTED) { switch (netInfo.getType()) { case ConnectivityManager.TYPE_WIFI: networkType = NETWORK_WIFI; break; case ConnectivityManager.TYPE_MOBILE: networkType = NETWORK_MOBILE; break; } } if ((networkType & networkAllowd) == 0) { // no allowed network connection Log.d(getClass().getSimpleName(), "network type is not allowed"); return null; } } // here we can finally start the downloads SQLiteDatabase db = dbHelper.getWritableDatabase(); String selection = DatabaseHelper.ExtendedEpisode.EPISODE_STATE + " = " + DatabaseHelper.Episode.STATE_NEW; String orderBy = null; if (params == null) { orderBy = String.format("%s DESC", DatabaseHelper.ExtendedEpisode.EPISODE_DATE); } else { selection += " AND " + DatabaseHelper.ExtendedEpisode.ENCLOSURE_ID + " IN (" + Utils.joinArray(params, ",") + ")"; } Cursor cursor = db.query(DatabaseHelper.ExtendedEpisode._TABLE, null, selection, null, null, null, orderBy); EnclosureDownloader ed = new EnclosureDownloader( DownloadService.this, (networkAllowd & NETWORK_WIFI) != 0, (networkAllowd & NETWORK_MOBILE) != 0); DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); int freeSlots = params == null ? ed.getFreeDownloadSlots() : cursor .getCount(); Log.d(getClass().getSimpleName(), String.format( "starting downloads inQueue:%d freeSlots:%d", cursor.getCount(), freeSlots)); ContentValues values = new ContentValues(); while (cursor.moveToNext() && freeSlots Query query = new Query(); query.setFilterById(cursor.getLong(cursor .getColumnIndex(DatabaseHelper.ExtendedEpisode.DOWNLOAD_ID))); if (dm.query(query).getCount() != 0) { // The Download of this episode was already started // TODO: Handling of failed downloads continue; } // get necessary information and enqueue download long enclosureId = cursor .getLong(cursor .getColumnIndex(DatabaseHelper.ExtendedEpisode.ENCLOSURE_ID)); long episodeId = cursor.getLong(cursor .getColumnIndex(DatabaseHelper.ExtendedEpisode.ID)); String title = cursor .getString(cursor .getColumnIndex(DatabaseHelper.ExtendedEpisode.EPISODE_TITLE)); String url = cursor .getString(cursor .getColumnIndex(DatabaseHelper.ExtendedEpisode.ENCLOSURE_URL)); long downloadId = ed.downloadEnclosure(enclosureId, url, title); // update enclosure table values.clear(); values.put(DatabaseHelper.Enclosure.DOWNLOAD_ID, downloadId); db.update(DatabaseHelper.Enclosure._TABLE, values, String.format("%s = ?", DatabaseHelper.Enclosure.ID), new String[] { String.valueOf(enclosureId) }); // update episode table values.clear(); values.put(DatabaseHelper.Episode.STATE, DatabaseHelper.Episode.STATE_DOWNLOADING); db.update(DatabaseHelper.Episode._TABLE, values, String.format("%s = ?", DatabaseHelper.Episode.ID), new String[] { String.valueOf(episodeId) }); } cursor.close(); return null; } @Override protected void onPostExecute(Void result) { stopSelf(); } } private class BatteryChangedReceiver extends BroadcastReceiver { private Long[] extraId; public BatteryChangedReceiver(Long[] extraId) { this.extraId = extraId; } @Override public void onReceive(Context context, Intent intent) { unregisterReceiver(this); phonePlugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); // the charging state is now known so we can start the DownloadTask new DownloadTask().execute(extraId); } } @Override public void onCreate() { super.onCreate(); app = (VolksempfaengerApplication) getApplication(); dbHelper = DatabaseHelper.getInstance(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(getClass().getSimpleName(), "onStartCommand()"); Long[] id = null; long[] extraId = intent.getLongArrayExtra("id"); if (extraId != null && extraId.length > 0) { if (extraId.length != 0) { id = new Long[extraId.length]; for (int i = 0; i < id.length; i++) { id[i] = extraId[i]; } } } // we need to register this broadcast receiver to get the charging state registerReceiver(new BatteryChangedReceiver(id), new IntentFilter( Intent.ACTION_BATTERY_CHANGED)); return START_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } }
package org.xdty.moments.activity; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader; import com.squareup.picasso.Picasso; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Background; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import org.xdty.moments.R; import org.xdty.moments.model.Config; import org.xdty.moments.model.Moment; import org.xdty.moments.model.Tweet; import org.xdty.moments.model.User; import org.xdty.moments.view.TweetAdapter; import java.util.ArrayList; import java.util.List; import retrofit.RestAdapter; @EActivity(R.layout.activity_main) public class MainActivity extends AppCompatActivity { public final static String TAG = "MainActivity"; public final static String USER = "jsmith"; @ViewById SwipeRefreshLayout swipeRefreshLayout; @ViewById RecyclerView recyclerView; TweetAdapter tweetAdapter; boolean isLoading = false; private User mUser = null; private List<Tweet> mTweets = null; private TextView mUsername; private ImageView mAvatar; private ImageView mProfileImage; private int mTweetPage = 0; @AfterViews public void afterViews() { getTweets(); RecyclerViewHeader header = RecyclerViewHeader.fromXml(this, R.layout.header); mUsername = (TextView) header.findViewById(R.id.username); mAvatar = (ImageView) header.findViewById(R.id.avatar); mProfileImage = (ImageView) header.findViewById(R.id.profile_image); tweetAdapter = new TweetAdapter(this); final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(linearLayoutManager); recyclerView.setAdapter(tweetAdapter); header.attachTo(recyclerView); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); int firstPosition = linearLayoutManager.findFirstCompletelyVisibleItemPosition(); if (firstPosition > 0) { swipeRefreshLayout.setEnabled(false); } else { swipeRefreshLayout.setEnabled(true); } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); int lastPosition = linearLayoutManager.findLastVisibleItemPosition(); if (lastPosition == recyclerView.getAdapter().getItemCount() - 1) { // load more tweets loadMoreTweets(); } } }); // pulling down the view to refresh swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mTweetPage = 0; getTweets(); } }); } @Background public void getTweets() { RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(Config.PROVIDER_URI) .setLogLevel(RestAdapter.LogLevel.FULL) .build(); Moment moment = restAdapter.create(Moment.class); try { mUser = moment.user(USER); mTweets = moment.tweet(USER); } catch (Exception e) { e.printStackTrace(); } if (mUser == null) { makeToast(getString(R.string.network_error)); return; } if (mTweets == null) { makeToast(getString(R.string.network_error)); return; } updateProfile(); updateTweets(); } @UiThread public void updateProfile() { mUsername.setText(mUser.getNick()); Picasso.with(this).load(mUser.getAvatar()).into(mAvatar); Picasso.with(this).load(mUser.getProfileImage()) .centerCrop() .resize(mProfileImage.getMeasuredWidth(), mProfileImage.getMeasuredHeight()) .into(mProfileImage); } @UiThread public void updateTweets() { List<Tweet> tweets = new ArrayList<>(); for (Tweet tweet : mTweets) { // ignore the tweet which does not contain a content and images if (tweet.getContent() == null && tweet.getImages().size() == 0) { continue; } tweets.add(tweet); } if (Config.SEPARATE_TWEET) { mTweets.clear(); mTweets.addAll(tweets); // clear recycler view tweetAdapter.swap(new ArrayList<Tweet>()); // show first five tweets. loadMoreTweets(); } else { // load all tweets into RecyclerViewer tweetAdapter.swap(tweets); } swipeRefreshLayout.setRefreshing(false); } @Background public void loadMoreTweets() { if (!isLoading) { isLoading = true; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } List<Tweet> tweets = new ArrayList<>(); for (int i = 0; i < Config.TWEET_PER_PAGE; i++) { int position = mTweetPage * Config.TWEET_PER_PAGE + i; if (position < mTweets.size()) { tweets.add(mTweets.get(position)); } else { makeToast(getString(R.string.no_more_tweets)); break; } } mTweetPage++; appendTweets(tweets); isLoading = false; } } @UiThread public void appendTweets(List<Tweet> tweets) { tweetAdapter.append(tweets); } @UiThread public void makeToast(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } }
package ru.adios.budgeter.util; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.support.annotation.ColorInt; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import java.util.List; import java8.util.Optional; import java8.util.function.Consumer; import ru.adios.budgeter.R; import ru.adios.budgeter.api.OptLimit; import ru.adios.budgeter.api.OrderBy; import ru.adios.budgeter.api.RepoOption; import static com.google.common.base.Preconditions.checkArgument; public class DataTableLayout extends TableLayout { @ColorInt private static final int BORDERS_COLOR = 0xFF4CAC45; private static final int MAX_ROW_CAPACITY = 8; private static final int DEFAULT_PAGE_SIZE = 10; private DataStore dataStore; private int rowsPerSet; private Consumer<DataTableLayout> listener; private String tableName; private OptLimit pageLimit; private OrderBy orderBy; private Drawable cellsBackground; private int setSize; private int itemsPerInnerRow; private int itemsInLastRow; private int headerOffset; private int dp1; private int dp2; private int dp3; private int dp4; private int dp5; public DataTableLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public DataTableLayout(Context context, int rowsPerSet, DataStore dataStore) { super(context); checkArgument(rowsPerSet >= 1, "rowsPerSet must be positive"); checkArgument(dataStore != null, "dataStore is null"); this.rowsPerSet = rowsPerSet; this.dataStore = dataStore; setId(ElementsIdProvider.getNextId()); init(); } public DataTableLayout(Context context, DataStore dataStore) { this(context, 1, dataStore); } public void start() { if (pageLimit == null) { setLimit(DEFAULT_PAGE_SIZE); } if (getChildCount() == 0) { populateFraming(dataStore.getDataHeaders()); } loadDataAndPopulateTable(); } public void repopulate() { removeAllViews(); populateFraming(dataStore.getDataHeaders()); invalidate(); loadDataAndPopulateTable(); } public void setTableName(String tableName) { this.tableName = tableName; } public void setOnDataLoadedListener(Consumer<DataTableLayout> listener) { this.listener = listener; } public void setPageSize(int pageSize) { setLimit(pageSize); } public void setOrderBy(OrderBy orderBy) { this.orderBy = orderBy; } private void setLimit(int pageSize) { pageLimit = OptLimit.createLimit(pageSize); } private void init() { cellsBackground = ContextCompat.getDrawable(getContext(), R.drawable.cell_shape); if (!isInEditMode()) { setSize = dataStore.getDataHeaders().size(); itemsPerInnerRow = setSize / rowsPerSet; checkArgument(itemsPerInnerRow < MAX_ROW_CAPACITY, "Row appears to be too large: %s", MAX_ROW_CAPACITY); itemsInLastRow = setSize % rowsPerSet; if (itemsInLastRow == 0) { itemsInLastRow = itemsPerInnerRow; } } } private void loadDataAndPopulateTable() { new AsyncTask<DataStore, Void, List<Iterable<String>>>() { @Override protected List<Iterable<String>> doInBackground(DataStore... params) { return orderBy != null ? params[0].loadData(pageLimit, orderBy) : params[0].loadData(pageLimit); } @Override protected void onPostExecute(List<Iterable<String>> iterables) { int rowId = headerOffset; for (final Iterable<String> dataSet : iterables) { rowId = addDataRow(dataSet, rowId); } listener.accept(DataTableLayout.this); invalidate(); } }.execute(dataStore); } private void populateFraming(List<String> headers) { final Context context = getContext(); addView(getRowSeparator(1)); headerOffset++; if (tableName != null) { final TableRow tableNameRow = new TableRow(context); tableNameRow.setId(ElementsIdProvider.getNextId()); tableNameRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); tableNameRow.setWeightSum(1f); final LinearLayout inner = new LinearLayout(context); final TableRow.LayoutParams innerParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 1f); innerParams.span = itemsPerInnerRow; inner.setLayoutParams(innerParams); inner.setBackground(cellsBackground); final TextView nameTextView = new TextView(context); nameTextView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); nameTextView.setTextAppearance(context, android.R.style.TextAppearance_Large); nameTextView.setText(tableName); nameTextView.setGravity(Gravity.CENTER); inner.addView(nameTextView); tableNameRow.addView(inner); addView(tableNameRow); headerOffset++; } headerOffset = addDataRow(headers, headerOffset); addView(getRowSeparator(1)); } private int addDataRow(Iterable<String> dataSet, int rowId) { final Context context = getContext(); final float lastColumnWeight = 2f * (itemsPerInnerRow - itemsInLastRow + 1); if (rowsPerSet > 1) { addView(getRowSeparator(rowsPerSet)); rowId++; } int i = 0; boolean firstInner = true; TableRow currentRow = constructRow(context); for (final String str : dataSet) { if (i > 0 && i % itemsPerInnerRow == 0) { addView(currentRow, rowId++); currentRow = constructRow(context); firstInner = true; } final float weight = i < setSize - 1 ? 2f : lastColumnWeight; final TextView textView; if (firstInner) { textView = createSpyingColumnForTableRow(str, rowId, weight, lastColumnWeight, context); firstInner = false; } else { textView = createColumnForTableRow(str, weight, context); } final Optional<Integer> maxWidth = dataStore.getMaxWidthForData(i); if (maxWidth.isPresent()) { textView.setMaxWidth(UiUtils.dpAsPixels(context, maxWidth.get())); } currentRow.addView(textView); i++; } addView(currentRow, rowId++); return rowId; } private TextView createColumnForTableRow(String text, float weight, Context context) { final TextView view = new TextView(context); populateColumn(view, context, weight); view.setText(text); return view; } private TextView createSpyingColumnForTableRow(String text, final int rowId, final float weight, final float lcw, Context context) { final SpyingTextView view = new SpyingTextView(context); populateColumn(view, context, weight); view.heightCatch = true; view.setHeightRunnable(new Runnable() { @Override public void run() { final TableRow row = (TableRow) getChildAt(rowId); final int childCount = row.getChildCount(); int maxHeight = 0; for (int i = 0; i < childCount; i++) { final TextView childAt = (TextView) row.getChildAt(i); maxHeight = Math.max(maxHeight, childAt.getHeight()); } for (int i = 0; i < childCount; i++) { final TextView childAt = (TextView) row.getChildAt(i); childAt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, maxHeight, i < childCount - 1 ? weight : lcw)); } invalidate(); } }); view.setText(text); return view; } private void populateColumn(TextView view, Context context, float weight) { view.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, weight)); view.setId(ElementsIdProvider.getNextId()); view.setBackground(ContextCompat.getDrawable(context, R.drawable.cell_shape)); final int fiveDp = getDpAsPixels(5, context); view.setPadding(fiveDp, fiveDp, fiveDp, fiveDp); view.setTextAppearance(context, android.R.style.TextAppearance_Small); } private TableRow constructRow(Context context) { final TableRow row = new TableRow(context); row.setId(ElementsIdProvider.getNextId()); row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); row.setWeightSum(itemsPerInnerRow * 2); return row; } private View getRowSeparator(int heightDp) { final Context context = getContext(); final View view = new View(context); view.setBackgroundColor(BORDERS_COLOR); view.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, getDpAsPixels(heightDp, context))); return view; } private int getDpAsPixels(int dps, Context context) { switch (dps) { case 1: if (dp1 == 0) { dp1 = UiUtils.dpAsPixels(context, dps); } return dp1; case 2: if (dp2 == 0) { dp2 = UiUtils.dpAsPixels(context, dps); } return dp2; case 3: if (dp3 == 0) { dp3 = UiUtils.dpAsPixels(context, dps); } return dp3; case 4: if (dp4 == 0) { dp4 = UiUtils.dpAsPixels(context, dps); } return dp4; case 5: if (dp5 == 0) { dp5 = UiUtils.dpAsPixels(context, dps); } return dp5; default: return UiUtils.dpAsPixels(context, dps); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); dp1 = 0; dp2 = 0; dp3 = 0; dp4 = 0; dp5 = 0; } public interface DataStore { /** * For execution in a separate thread. * @param options optional pagination for table to request. * @return data in string form. */ List<Iterable<String>> loadData(RepoOption... options); List<String> getDataHeaders(); Optional<Integer> getMaxWidthForData(int index); } }
package org.commcare.dalvik.activities; import android.annotation.TargetApi; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import org.commcare.dalvik.R; /** * @author ctsims */ @TargetApi(11) public class EntityMapActivity extends FragmentActivity implements OnMapReadyCallback { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.entity_map_view); MapFragment mapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap map) { map.addMarker(new MarkerOptions() .position(new LatLng(0, 0)) .title("Marker")); } }
package org.bouncycastle.jce.provider; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.cryptopro.ECGOST3410NamedCurves; import org.bouncycastle.asn1.nist.NISTNamedCurves; import org.bouncycastle.asn1.sec.SECNamedCurves; import org.bouncycastle.asn1.x9.X962NamedCurves; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.generators.DHBasicKeyPairGenerator; import org.bouncycastle.crypto.generators.DHParametersGenerator; import org.bouncycastle.crypto.generators.DSAKeyPairGenerator; import org.bouncycastle.crypto.generators.DSAParametersGenerator; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.generators.ElGamalKeyPairGenerator; import org.bouncycastle.crypto.generators.ElGamalParametersGenerator; import org.bouncycastle.crypto.generators.GOST3410KeyPairGenerator; import org.bouncycastle.crypto.generators.RSAKeyPairGenerator; import org.bouncycastle.crypto.params.DHKeyGenerationParameters; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPrivateKeyParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.crypto.params.DSAKeyGenerationParameters; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPrivateKeyParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.params.ECKeyGenerationParameters; import org.bouncycastle.crypto.params.ECPrivateKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.ElGamalKeyGenerationParameters; import org.bouncycastle.crypto.params.ElGamalParameters; import org.bouncycastle.crypto.params.ElGamalPrivateKeyParameters; import org.bouncycastle.crypto.params.ElGamalPublicKeyParameters; import org.bouncycastle.crypto.params.GOST3410KeyGenerationParameters; import org.bouncycastle.crypto.params.GOST3410Parameters; import org.bouncycastle.crypto.params.GOST3410PrivateKeyParameters; import org.bouncycastle.crypto.params.GOST3410PublicKeyParameters; import org.bouncycastle.crypto.params.RSAKeyGenerationParameters; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters; import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; import org.bouncycastle.jce.spec.ECNamedCurveSpec; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ElGamalParameterSpec; import org.bouncycastle.jce.spec.GOST3410ParameterSpec; import org.bouncycastle.jce.spec.GOST3410PublicKeyParameterSetSpec; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.math.ec.ECFieldElement; import org.bouncycastle.math.ec.ECPoint; import javax.crypto.spec.DHParameterSpec; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.DSAParameterSpec; import java.security.spec.ECField; import java.security.spec.ECFieldF2m; import java.security.spec.ECFieldFp; import java.security.spec.ECGenParameterSpec; import java.security.spec.RSAKeyGenParameterSpec; import java.util.Hashtable; public abstract class JDKKeyPairGenerator extends KeyPairGenerator { public JDKKeyPairGenerator( String algorithmName) { super(algorithmName); } public abstract void initialize(int strength, SecureRandom random); public abstract KeyPair generateKeyPair(); public static class RSA extends JDKKeyPairGenerator { final static BigInteger defaultPublicExponent = BigInteger.valueOf(0x10001); final static int defaultTests = 12; RSAKeyGenerationParameters param; RSAKeyPairGenerator engine; public RSA() { super("RSA"); engine = new RSAKeyPairGenerator(); param = new RSAKeyGenerationParameters(defaultPublicExponent, new SecureRandom(), 2048, defaultTests); engine.init(param); } public void initialize( int strength, SecureRandom random) { param = new RSAKeyGenerationParameters(defaultPublicExponent, random, strength, defaultTests); engine.init(param); } public void initialize( AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { if (!(params instanceof RSAKeyGenParameterSpec)) { throw new InvalidAlgorithmParameterException("parameter object not a RSAKeyGenParameterSpec"); } RSAKeyGenParameterSpec rsaParams = (RSAKeyGenParameterSpec)params; param = new RSAKeyGenerationParameters( rsaParams.getPublicExponent(), random, rsaParams.getKeysize(), defaultTests); engine.init(param); } public KeyPair generateKeyPair() { AsymmetricCipherKeyPair pair = engine.generateKeyPair(); RSAKeyParameters pub = (RSAKeyParameters)pair.getPublic(); RSAPrivateCrtKeyParameters priv = (RSAPrivateCrtKeyParameters)pair.getPrivate(); return new KeyPair(new JCERSAPublicKey(pub), new JCERSAPrivateCrtKey(priv)); } } public static class DH extends JDKKeyPairGenerator { DHKeyGenerationParameters param; DHBasicKeyPairGenerator engine = new DHBasicKeyPairGenerator(); int strength = 1024; int certainty = 20; SecureRandom random = new SecureRandom(); boolean initialised = false; public DH() { super("DH"); } public void initialize( int strength, SecureRandom random) { this.strength = strength; this.random = random; } public void initialize( AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { if (!(params instanceof DHParameterSpec)) { throw new InvalidAlgorithmParameterException("parameter object not a DHParameterSpec"); } DHParameterSpec dhParams = (DHParameterSpec)params; param = new DHKeyGenerationParameters(random, new DHParameters(dhParams.getP(), dhParams.getG(), null, dhParams.getL())); engine.init(param); initialised = true; } public KeyPair generateKeyPair() { if (!initialised) { DHParametersGenerator pGen = new DHParametersGenerator(); pGen.init(strength, certainty, random); param = new DHKeyGenerationParameters(random, pGen.generateParameters()); engine.init(param); initialised = true; } AsymmetricCipherKeyPair pair = engine.generateKeyPair(); DHPublicKeyParameters pub = (DHPublicKeyParameters)pair.getPublic(); DHPrivateKeyParameters priv = (DHPrivateKeyParameters)pair.getPrivate(); return new KeyPair(new JCEDHPublicKey(pub), new JCEDHPrivateKey(priv)); } } public static class DSA extends JDKKeyPairGenerator { DSAKeyGenerationParameters param; DSAKeyPairGenerator engine = new DSAKeyPairGenerator(); int strength = 1024; int certainty = 20; SecureRandom random = new SecureRandom(); boolean initialised = false; public DSA() { super("DSA"); } public void initialize( int strength, SecureRandom random) { if (strength < 512 || strength > 1024 || strength % 64 != 0) { throw new InvalidParameterException("strength must be from 512 - 1024 and a multiple of 64"); } this.strength = strength; this.random = random; } public void initialize( AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { if (!(params instanceof DSAParameterSpec)) { throw new InvalidAlgorithmParameterException("parameter object not a DSAParameterSpec"); } DSAParameterSpec dsaParams = (DSAParameterSpec)params; param = new DSAKeyGenerationParameters(random, new DSAParameters(dsaParams.getP(), dsaParams.getQ(), dsaParams.getG())); engine.init(param); initialised = true; } public KeyPair generateKeyPair() { if (!initialised) { DSAParametersGenerator pGen = new DSAParametersGenerator(); pGen.init(strength, certainty, random); param = new DSAKeyGenerationParameters(random, pGen.generateParameters()); engine.init(param); initialised = true; } AsymmetricCipherKeyPair pair = engine.generateKeyPair(); DSAPublicKeyParameters pub = (DSAPublicKeyParameters)pair.getPublic(); DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)pair.getPrivate(); return new KeyPair(new JDKDSAPublicKey(pub), new JDKDSAPrivateKey(priv)); } } public static class ElGamal extends JDKKeyPairGenerator { ElGamalKeyGenerationParameters param; ElGamalKeyPairGenerator engine = new ElGamalKeyPairGenerator(); int strength = 1024; int certainty = 20; SecureRandom random = new SecureRandom(); boolean initialised = false; public ElGamal() { super("ElGamal"); } public void initialize( int strength, SecureRandom random) { this.strength = strength; this.random = random; } public void initialize( AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { if (!(params instanceof ElGamalParameterSpec) && !(params instanceof DHParameterSpec)) { throw new InvalidAlgorithmParameterException("parameter object not a DHParameterSpec or an ElGamalParameterSpec"); } if (params instanceof ElGamalParameterSpec) { ElGamalParameterSpec elParams = (ElGamalParameterSpec)params; param = new ElGamalKeyGenerationParameters(random, new ElGamalParameters(elParams.getP(), elParams.getG())); } else { DHParameterSpec dhParams = (DHParameterSpec)params; param = new ElGamalKeyGenerationParameters(random, new ElGamalParameters(dhParams.getP(), dhParams.getG(), dhParams.getL())); } engine.init(param); initialised = true; } public KeyPair generateKeyPair() { if (!initialised) { ElGamalParametersGenerator pGen = new ElGamalParametersGenerator(); pGen.init(strength, certainty, random); param = new ElGamalKeyGenerationParameters(random, pGen.generateParameters()); engine.init(param); initialised = true; } AsymmetricCipherKeyPair pair = engine.generateKeyPair(); ElGamalPublicKeyParameters pub = (ElGamalPublicKeyParameters)pair.getPublic(); ElGamalPrivateKeyParameters priv = (ElGamalPrivateKeyParameters)pair.getPrivate(); return new KeyPair(new JCEElGamalPublicKey(pub), new JCEElGamalPrivateKey(priv)); } } public static class GOST3410 extends JDKKeyPairGenerator { GOST3410KeyGenerationParameters param; GOST3410KeyPairGenerator engine = new GOST3410KeyPairGenerator(); GOST3410ParameterSpec gost3410Params; int strength = 1024; SecureRandom random = null; boolean initialised = false; public GOST3410() { super("GOST3410"); } public void initialize( int strength, SecureRandom random) { this.strength = strength; this.random = random; } private void init( GOST3410ParameterSpec gParams, SecureRandom random) { GOST3410PublicKeyParameterSetSpec spec = gParams.getPublicKeyParameters(); param = new GOST3410KeyGenerationParameters(random, new GOST3410Parameters(spec.getP(), spec.getQ(), spec.getA())); engine.init(param); initialised = true; gost3410Params = gParams; } public void initialize( AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { if (!(params instanceof GOST3410ParameterSpec)) { throw new InvalidAlgorithmParameterException("parameter object not a GOST3410ParameterSpec"); } init((GOST3410ParameterSpec)params, random); } public KeyPair generateKeyPair() { if (!initialised) { init(new GOST3410ParameterSpec(CryptoProObjectIdentifiers.gostR3410_94_CryptoPro_A.getId()), new SecureRandom()); } AsymmetricCipherKeyPair pair = engine.generateKeyPair(); GOST3410PublicKeyParameters pub = (GOST3410PublicKeyParameters)pair.getPublic(); GOST3410PrivateKeyParameters priv = (GOST3410PrivateKeyParameters)pair.getPrivate(); return new KeyPair(new JDKGOST3410PublicKey(pub, gost3410Params), new JDKGOST3410PrivateKey(priv, gost3410Params)); } } public static class EC extends JDKKeyPairGenerator { ECKeyGenerationParameters param; ECKeyPairGenerator engine = new ECKeyPairGenerator(); Object ecParams = null; int strength = 239; int certainty = 50; SecureRandom random = new SecureRandom(); boolean initialised = false; String algorithm; static private Hashtable ecParameters; static { ecParameters = new Hashtable(); ecParameters.put(new Integer(192), new ECGenParameterSpec("prime192v1")); ecParameters.put(new Integer(239), new ECGenParameterSpec("prime239v1")); ecParameters.put(new Integer(256), new ECGenParameterSpec("prime256v1")); } public EC() { super("EC"); this.algorithm = "EC"; } public EC( String algorithm) { super(algorithm); this.algorithm = algorithm; } public void initialize( int strength, SecureRandom random) { this.strength = strength; this.random = random; this.ecParams = ecParameters.get(new Integer(strength)); if (ecParams != null) { try { initialize((ECGenParameterSpec)ecParams, random); } catch (InvalidAlgorithmParameterException e) { throw new InvalidParameterException("key size not configurable."); } } else { throw new InvalidParameterException("unknown key size."); } } public void initialize( AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { if (params instanceof ECParameterSpec) { ECParameterSpec p = (ECParameterSpec)params; this.ecParams = params; param = new ECKeyGenerationParameters(new ECDomainParameters(p.getCurve(), p.getG(), p.getN()), random); engine.init(param); initialised = true; } else if (params instanceof java.security.spec.ECParameterSpec) { java.security.spec.ECParameterSpec p = (java.security.spec.ECParameterSpec)params; this.ecParams = params; ECCurve curve; ECPoint g; ECField field = p.getCurve().getField(); if (field instanceof ECFieldFp) { curve = new ECCurve.Fp(((ECFieldFp)p.getCurve().getField()).getP(), p.getCurve().getA(), p.getCurve().getB()); g = new ECPoint.Fp(curve, new ECFieldElement.Fp(((ECCurve.Fp)curve).getQ(), p.getGenerator().getAffineX()), new ECFieldElement.Fp(((ECCurve.Fp)curve).getQ(), p.getGenerator().getAffineY())); } else { ECFieldF2m fieldF2m = (ECFieldF2m)field; int m = fieldF2m.getM(); int ks[] = ECUtil.convertMidTerms(fieldF2m.getMidTermsOfReductionPolynomial()); curve = new ECCurve.F2m(m, ks[0], ks[1], ks[2], p.getCurve().getA(), p.getCurve().getB()); g = new ECPoint.F2m(curve, new ECFieldElement.F2m(m, ks[0], ks[1], ks[2], p.getGenerator().getAffineX()), new ECFieldElement.F2m(m, ks[0], ks[1], ks[2], p.getGenerator().getAffineY()), false); } param = new ECKeyGenerationParameters(new ECDomainParameters(curve, g, p.getOrder(), BigInteger.valueOf(p.getCofactor())), random); engine.init(param); initialised = true; } else if (params instanceof ECGenParameterSpec) { if (this.algorithm.equals("ECGOST3410")) { ECDomainParameters ecP = ECGOST3410NamedCurves.getByName(((ECGenParameterSpec)params).getName()); if (ecP == null) { throw new InvalidAlgorithmParameterException("unknown curve name: " + ((ECGenParameterSpec)params).getName()); } this.ecParams = new ECNamedCurveParameterSpec( ((ECGenParameterSpec)params).getName(), ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed()); } else { X9ECParameters ecP = X962NamedCurves.getByName(((ECGenParameterSpec)params).getName()); if (ecP == null) { ecP = SECNamedCurves.getByName(((ECGenParameterSpec)params).getName()); if (ecP == null) { ecP = NISTNamedCurves.getByName(((ECGenParameterSpec)params).getName()); } if (ecP == null) { throw new InvalidAlgorithmParameterException("unknown curve name: " + ((ECGenParameterSpec)params).getName()); } } this.ecParams = new ECNamedCurveSpec( ((ECGenParameterSpec)params).getName(), ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed()); } java.security.spec.ECParameterSpec p = (java.security.spec.ECParameterSpec)ecParams; ECCurve curve; ECPoint g; ECField field = p.getCurve().getField(); if (field instanceof ECFieldFp) { curve = new ECCurve.Fp(((ECFieldFp)p.getCurve().getField()).getP(), p.getCurve().getA(), p.getCurve().getB()); g = new ECPoint.Fp(curve, new ECFieldElement.Fp(((ECCurve.Fp)curve).getQ(), p.getGenerator().getAffineX()), new ECFieldElement.Fp(((ECCurve.Fp)curve).getQ(), p.getGenerator().getAffineY())); } else { ECFieldF2m fieldF2m = (ECFieldF2m)field; int m = fieldF2m.getM(); int ks[] = ECUtil.convertMidTerms(fieldF2m.getMidTermsOfReductionPolynomial()); curve = new ECCurve.F2m(m, ks[0], ks[1], ks[2], p.getCurve().getA(), p.getCurve().getB()); g = new ECPoint.F2m(curve, new ECFieldElement.F2m(m, ks[0], ks[1], ks[2], p.getGenerator().getAffineX()), new ECFieldElement.F2m(m, ks[0], ks[1], ks[2], p.getGenerator().getAffineY()), false); } param = new ECKeyGenerationParameters(new ECDomainParameters(curve, g, p.getOrder(), BigInteger.valueOf(p.getCofactor())), random); engine.init(param); initialised = true; } else if (params == null && ProviderUtil.getEcImplicitlyCa() != null) { ECParameterSpec p = ProviderUtil.getEcImplicitlyCa(); this.ecParams = params; param = new ECKeyGenerationParameters(new ECDomainParameters(p.getCurve(), p.getG(), p.getN()), random); engine.init(param); initialised = true; } else if (params == null && ProviderUtil.getEcImplicitlyCa() == null) { throw new InvalidAlgorithmParameterException("null parameter passed by no implicitCA set"); } else { throw new InvalidAlgorithmParameterException("parameter object not a ECParameterSpec"); } } public KeyPair generateKeyPair() { if (!initialised) { throw new IllegalStateException("EC Key Pair Generator not initialised"); } AsymmetricCipherKeyPair pair = engine.generateKeyPair(); ECPublicKeyParameters pub = (ECPublicKeyParameters)pair.getPublic(); ECPrivateKeyParameters priv = (ECPrivateKeyParameters)pair.getPrivate(); if (ecParams instanceof ECParameterSpec) { ECParameterSpec p = (ECParameterSpec)ecParams; return new KeyPair(new JCEECPublicKey(algorithm, pub, p), new JCEECPrivateKey(algorithm, priv, p)); } else if (ecParams == null) { return new KeyPair(new JCEECPublicKey(algorithm, pub), new JCEECPrivateKey(algorithm, priv)); } else { java.security.spec.ECParameterSpec p = (java.security.spec.ECParameterSpec)ecParams; return new KeyPair(new JCEECPublicKey(algorithm, pub, p), new JCEECPrivateKey(algorithm, priv, p)); } } } public static class ECDSA extends EC { public ECDSA() { super("ECDSA"); } } public static class ECGOST3410 extends EC { public ECGOST3410() { super("ECGOST3410"); } } public static class ECDH extends EC { public ECDH() { super("ECDH"); } } public static class ECDHC extends EC { public ECDHC() { super("ECDHC"); } } }
package <%=packageName%>.service; <% if (databaseType == 'sql' || databaseType == 'mongodb') { %> import <%=packageName%>.domain.Authority;<% if (authenticationType == 'session') { %> import <%=packageName%>.domain.PersistentToken;<% } %><% } %> import <%=packageName%>.domain.User;<% if (databaseType == 'sql' || databaseType == 'mongodb') { %> import <%=packageName%>.repository.AuthorityRepository;<% if (authenticationType == 'session') { %> import <%=packageName%>.repository.PersistentTokenRepository;<% } %><% } %> import <%=packageName%>.repository.UserRepository;<% if (searchEngine == 'elasticsearch') { %> import <%=packageName%>.repository.search.UserSearchRepository;<% } %><% if (databaseType == 'cassandra') { %> import <%=packageName%>.security.AuthoritiesConstants;<% } %> import <%=packageName%>.security.SecurityUtils; import <%=packageName%>.service.util.RandomUtil; import <%=packageName%>.web.rest.dto.ManagedUserDTO; import java.time.ZonedDateTime;<% if (databaseType == 'sql' || databaseType == 'mongodb') { %> import java.time.LocalDate;<% } %> import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service;<% if (databaseType == 'sql') { %> import org.springframework.transaction.annotation.Transactional;<% } %> import java.time.ZonedDateTime; import javax.inject.Inject; import java.util.*; /** * Service class for managing users. */ @Service<% if (databaseType == 'sql') { %> @Transactional<% } %> public class UserService { private final Logger log = LoggerFactory.getLogger(UserService.class); @Inject private PasswordEncoder passwordEncoder; @Inject private UserRepository userRepository;<% if (searchEngine == 'elasticsearch') { %> @Inject private UserSearchRepository userSearchRepository;<% } %><% if (databaseType == 'sql' || databaseType == 'mongodb') { %><% if (authenticationType == 'session') { %> @Inject private PersistentTokenRepository persistentTokenRepository;<% } %><% } %> <% if (databaseType == 'sql' || databaseType == 'mongodb') { %> @Inject private AuthorityRepository authorityRepository;<% } %> public Optional<User> activateRegistration(String key) { log.debug("Activating user for activation key {}", key); userRepository.findOneByActivationKey(key) .map(user -> { // activate given user for the registration key. user.setActivated(true); user.setActivationKey(null); userRepository.save(user);<% if (searchEngine == 'elasticsearch') { %> userSearchRepository.save(user);<% } %> log.debug("Activated user: {}", user); return user; }); return Optional.empty(); } public Optional<User> completePasswordReset(String newPassword, String key) { log.debug("Reset user password for reset key {}", key); return userRepository.findOneByResetKey(key) .filter(user -> { ZonedDateTime oneDayAgo = ZonedDateTime.now().minusHours(24); return user.getResetDate()<% if (databaseType == 'sql' || databaseType == 'mongodb') { %>.isAfter(oneDayAgo);<% } %><% if (databaseType == 'cassandra') { %>.after(Date.from(oneDayAgo.toInstant()));<% } %> }) .map(user -> { user.setPassword(passwordEncoder.encode(newPassword)); user.setResetKey(null); user.setResetDate(null); userRepository.save(user); return user; }); } public Optional<User> requestPasswordReset(String mail) { return userRepository.findOneByEmail(mail) .filter(User::getActivated) .map(user -> { user.setResetKey(RandomUtil.generateResetKey()); user.<% if (databaseType == 'sql' || databaseType == 'mongodb') { %>setResetDate(ZonedDateTime.now());<% } %><% if (databaseType == 'cassandra') { %>setResetDate(new Date());<% } %> userRepository.save(user); return user; }); } public User createUserInformation(String login, String password, String firstName, String lastName, String email, String langKey) { User newUser = new User();<% if (databaseType == 'sql' || databaseType == 'mongodb') { %> Authority authority = authorityRepository.findOne("ROLE_USER"); Set<Authority> authorities = new HashSet<>();<% } %><% if (databaseType == 'cassandra') { %> newUser.setId(UUID.randomUUID().toString()); Set<String> authorities = new HashSet<>();<% } %> String encryptedPassword = passwordEncoder.encode(password); newUser.setLogin(login); // new user gets initially a generated password newUser.setPassword(encryptedPassword); newUser.setFirstName(firstName); newUser.setLastName(lastName); newUser.setEmail(email); newUser.setLangKey(langKey); // new user is not active newUser.setActivated(false); // new user gets registration key newUser.setActivationKey(RandomUtil.generateActivationKey());<% if (databaseType == 'sql' || databaseType == 'mongodb') { %> authorities.add(authority);<% } %><% if (databaseType == 'cassandra') { %> authorities.add(AuthoritiesConstants.USER);<% } %> newUser.setAuthorities(authorities); userRepository.save(newUser);<% if (searchEngine == 'elasticsearch') { %> userSearchRepository.save(newUser);<% } %> log.debug("Created Information for User: {}", newUser); return newUser; } public User createUser(ManagedUserDTO managedUserDTO) { User user = new User();<% if (databaseType == 'cassandra') { %> user.setId(UUID.randomUUID().toString());<% } %> user.setLogin(managedUserDTO.getLogin()); user.setFirstName(managedUserDTO.getFirstName()); user.setLastName(managedUserDTO.getLastName()); user.setEmail(managedUserDTO.getEmail()); user.setLangKey(managedUserDTO.getLangKey());<% if (databaseType == 'sql' || databaseType == 'mongodb') { %> Set<Authority> authorities = new HashSet<>(); managedUserDTO.getAuthorities().stream().forEach( authority -> authorities.add(authorityRepository.findOne(authority)) ); user.setAuthorities(authorities);<% } %><% if (databaseType == 'cassandra') { %> user.setAuthorities(managedUserDTO.getAuthorities());<% } %> String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword()); user.setPassword(encryptedPassword); user.setResetKey(RandomUtil.generateResetKey()); user.<% if (databaseType == 'sql' || databaseType == 'mongodb') { %>setResetDate(ZonedDateTime.now());<% } %><% if (databaseType == 'cassandra') { %>setResetDate(new Date());<% } %> user.setActivated(true); userRepository.save(user);<% if (searchEngine == 'elasticsearch') { %> userSearchRepository.save(user);<% } %> log.debug("Created Information for User: {}", user); return user; } public void updateUserInformation(String firstName, String lastName, String email, String langKey) { userRepository.findOneByLogin(SecurityUtils.getCurrentUser().getUsername()).ifPresent(u -> { u.setFirstName(firstName); u.setLastName(lastName); u.setEmail(email); u.setLangKey(langKey); userRepository.save(u);<% if (searchEngine == 'elasticsearch') { %> userSearchRepository.save(u);<% } %> log.debug("Changed Information for User: {}", u); }); } public void deleteUserInformation(String login) { userRepository.findOneByLogin(login).ifPresent(u -> { userRepository.delete(u);<% if (searchEngine == 'elasticsearch') { %> userSearchRepository.delete(u);<% } %> log.debug("Deleted User: {}", u); }); } public void changePassword(String password) { userRepository.findOneByLogin(SecurityUtils.getCurrentUser().getUsername()).ifPresent(u -> { String encryptedPassword = passwordEncoder.encode(password); u.setPassword(encryptedPassword); userRepository.save(u); log.debug("Changed password for User: {}", u); }); } <% if (databaseType == 'sql') { %> @Transactional(readOnly = true)<% } %> public Optional<User> getUserWithAuthoritiesByLogin(String login) { return userRepository.findOneByLogin(login).map(u -> { u.getAuthorities().size(); return u; }); } <% if (databaseType == 'sql') { %> @Transactional(readOnly = true)<% } %><% if (databaseType == 'sql' || databaseType == 'mongodb') { %> public User getUserWithAuthorities(<%= pkType %> id) { User user = userRepository.findOne(id); user.getAuthorities().size(); // eagerly load the association return user; }<% } %> <% if (databaseType == 'sql') { %> @Transactional(readOnly = true)<% } %> public User getUserWithAuthorities() { User user = userRepository.findOneByLogin(SecurityUtils.getCurrentUser().getUsername()).get(); user.getAuthorities().size(); // eagerly load the association return user; }<% if ((databaseType == 'sql' || databaseType == 'mongodb') && authenticationType == 'session') { %> /** * Persistent Token are used for providing automatic authentication, they should be automatically deleted after * 30 days. * <p/> * <p> * This is scheduled to get fired everyday, at midnight. * </p> */ @Scheduled(cron = "0 0 0 * * ?") public void removeOldPersistentTokens() { LocalDate now = LocalDate.now(); persistentTokenRepository.findByTokenDateBefore(now.minusMonths(1)).stream().forEach(token -> { log.debug("Deleting token {}", token.getSeries());<% if (databaseType == 'sql') { %> User user = token.getUser(); user.getPersistentTokens().remove(token);<% } %> persistentTokenRepository.delete(token); }); }<% } %><% if (databaseType == 'sql' || databaseType == 'mongodb') { %> /** * Not activated users should be automatically deleted after 3 days. * <p/> * <p> * This is scheduled to get fired everyday, at 01:00 (am). * </p> */ @Scheduled(cron = "0 0 1 * * ?") public void removeNotActivatedUsers() { ZonedDateTime now = ZonedDateTime.now(); List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3)); for (User user : users) { log.debug("Deleting not activated user {}", user.getLogin()); userRepository.delete(user);<% if (searchEngine == 'elasticsearch') { %> userSearchRepository.delete(user);<% } %> } }<% } %> }
package org.ensembl.healthcheck.testcase.generic; import java.sql.Connection; import java.util.HashMap; import java.util.Map; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; import org.ensembl.healthcheck.util.DBUtils; /** * Checks the *_stable_id tables to ensure they are populated, have no orphan * references, and have valid versions. Also prints some examples from the table * for checking by eye. * * <p> * Group is <b>check_stable_ids </b> * </p> * * <p> * To be run after the stable ids have been assigned. * </p> */ public class StableID extends SingleDatabaseTestCase { /** * Create a new instance of StableID. */ public StableID() { addToGroup("id_mapping"); addToGroup("release"); setDescription("Checks *_stable_id tables are valid."); } /** * This only applies to core and Vega databases. */ public void types() { removeAppliesToType(DatabaseType.OTHERFEATURES); removeAppliesToType(DatabaseType.CDNA); } /** * Run the test. * * @param dbre * The database to use. * @return true if the test pased. * */ public boolean run(DatabaseRegistryEntry dbre) { boolean result = true; Connection con = dbre.getConnection(); result &= checkStableIDs(con, "exon"); result &= checkStableIDs(con, "translation"); result &= checkStableIDs(con, "transcript"); result &= checkStableIDs(con, "gene"); result &= checkStableIDEventTypes(con); return result; } /** * Checks that the typeName_stable_id table is valid. The table is valid if it * has >0 rows, and there are no orphan references between typeName table and * typeName_stable_id. Also prints some example data from the * typeName_stable_id table via ReportManager.info(). * * @param con * connection to run quries on. * @param typeName * name of the type to check, e.g. "exon" * @return true if the table and references are valid, otherwise false. */ public boolean checkStableIDs(Connection con, String typeName) { boolean result = true; String stableIDtable = typeName + "_stable_id"; int nStableIDs = countRowsInTable(con, stableIDtable); // ReportManager.info(this, con, "Num " + typeName + "s stable ids = " + // nStableIDs); if (nStableIDs < 1) { ReportManager.problem(this, con, stableIDtable + " table is empty."); result = false; } // look for orphans between type and type_stable_id tables int orphans = countOrphans(con, typeName, typeName + "_id", stableIDtable, typeName + "_id", false); if (orphans > 0) { ReportManager.problem(this, con, "Orphan references between " + typeName + " and " + typeName + "_stable_id tables."); result = false; } int nInvalidVersions = getRowCount(con, "SELECT COUNT(*) AS " + typeName + "_with_invalid_version" + " FROM " + stableIDtable + " WHERE version < 1 OR version IS NULL;"); if (nInvalidVersions > 0) { ReportManager.problem(this, con, "Invalid " + typeName + " versions in " + stableIDtable); DBUtils.printRows(this, con, "SELECT DISTINCT(version) FROM " + stableIDtable); result = false; } // check for duplicate stable IDs (will be redundant when stable ID columns // get a UNIQUE constraint) // to find which records are duplicated use // SELECT exon_id, stable_id, COUNT(*) FROM exon_stable_id GROUP BY // stable_id HAVING COUNT(*) > 1; // this will give the internal IDs for *one* of each of the duplicates // if there are only a few then reassign the stable IDs of one of the // duplicates int duplicates = getRowCount(con, "SELECT COUNT(stable_id)-COUNT(DISTINCT stable_id) FROM " + stableIDtable); if (duplicates > 0) { ReportManager.problem(this, con, stableIDtable + " has " + duplicates + " duplicate stable IDs (versions not checked)"); result = false; } else { ReportManager.correct(this, con, "No duplicate stable IDs in " + stableIDtable); } // check that all stable IDs in the table have the correct prefix // prefix is defined by the stableid.prefix value in the meta table Map tableToLetter = new HashMap(); tableToLetter.put("gene", "G"); tableToLetter.put("transcript", "T"); tableToLetter.put("translation", "P"); tableToLetter.put("exon", "E"); String prefix = getRowColumnValue(con, "SELECT meta_value FROM meta WHERE meta_key='stableid.prefix'"); if (prefix == null || prefix == "") { ReportManager.problem(this, con, "Can't get stableid.prefix from meta table"); result = false; } else { String prefixLetter = prefix + (String)tableToLetter.get(typeName); int wrong = getRowCount(con, "SELECT COUNT(*) FROM " + stableIDtable + " WHERE stable_id NOT LIKE '" + prefixLetter + "%'" ); if (wrong > 0) { ReportManager.problem(this, con, wrong + " rows in " + stableIDtable + " do not have the correct (" + prefixLetter + ") prefix"); result = false; } else { ReportManager.correct(this, con, "All rows in " + stableIDtable + " have the correct prefix (" + prefixLetter + ")"); } } return result; } /** * Check for any stable ID events where the 'type' column does not match the * identifier type. * */ private boolean checkStableIDEventTypes(Connection con) { boolean result = true; String[] types = { "gene", "transcript", "translation" }; for (int i = 0; i < types.length; i++) { String type = types[i]; String prefix = getPrefixForType(con, type); String sql = "SELECT COUNT(*) FROM stable_id_event WHERE (old_stable_id LIKE '" + prefix + "%' OR new_stable_id LIKE '" + prefix + "%') AND type != '" + type + "'"; int rows = getRowCount(con, sql); if (rows > 0) { ReportManager.problem(this, con, rows + " rows of type " + type + " (prefix " + prefix + ") in stable_id_event have identifiers that do not correspond to " + type + "s"); result = false; } else { ReportManager.correct(this, con, "All types in stable_id_event correspond to identifiers"); } } return result; } private String getPrefixForType(Connection con, String type) { String prefix = ""; // hope the first row of the _type_stable_id table is correct String stableID = getRowColumnValue(con, "SELECT stable_id FROM " + type + "_stable_id LIMIT 1"); prefix = stableID.replaceAll("[0-9]", ""); if (prefix.equals("")) { System.err.println("Error, can't get prefix for " + type + " from stable ID " + stableID); } return prefix; } }
package org.hollowcraft.server.heartbeat; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.security.SecureRandom; import java.util.Map; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.hollowcraft.server.Constants; import org.slf4j.*; /** * A class which manages heartbeats. * @author Graham Edgecombe * @author Caleb Champlin */ public class HeartbeatManager { /** * The singleton instance. */ private static final HeartbeatManager INSTANCE = new HeartbeatManager(); /** * Heartbeat server URL. */ public static final URL URL; /** * Initializes the heartbeat server URL. */ static { try { URL = new URL(Constants.HEARTBEAT_SERVER + "heartbeat.jsp"); } catch (MalformedURLException e) { throw new ExceptionInInitializerError(e); } } /** * Logger instance. */ private static final Logger logger = LoggerFactory.getLogger(HeartbeatManager.class); /** * Gets the heartbeat manager instance. * @return The heartbeat manager instance. */ public static HeartbeatManager getHeartbeatManager() { return INSTANCE; } /** * The salt. */ private final long salt = new SecureRandom().nextLong(); /** * An executor service which executes HTTP requests. */ private ExecutorService service = Executors.newSingleThreadExecutor(); /** * Default private constructor. */ private HeartbeatManager() { /* empty */ } /** * Sends a heartbeat with the specified parameters. This method does not * block. * @param parameters The parameters. */ private String connectHash; public String getConnectHash() { if (connectHash == null || connectHash.length() == 0) return "unknown"; return connectHash; } public void sendHeartbeat(final Map<String, String> parameters) { service.submit(new Runnable() { public void run() { // assemble POST data StringBuilder bldr = new StringBuilder(); for (Map.Entry<String, String> entry : parameters.entrySet()) { logger.trace("Param: {} = {}", entry.getKey(), entry.getValue()); bldr.append(entry.getKey()); bldr.append('='); try { bldr.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } bldr.append('&'); } if (bldr.length() > 0) { bldr.deleteCharAt(bldr.length() - 1); } // send it off try { HttpURLConnection conn = (HttpURLConnection) URL.openConnection(); byte[] bytes = bldr.toString().getBytes(); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(bytes.length)); // this emulates the minecraft server exactly.. idk why // notch added this personally conn.setRequestProperty("Content-Language", "en-US"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); try { DataOutputStream os = new DataOutputStream(conn.getOutputStream()); try { os.write(bytes); } finally { os.close(); } BufferedReader rdr = new BufferedReader(new InputStreamReader(conn.getInputStream())); try { URL connectURL = new URL(rdr.readLine()); logger.info("To connect to this server, use : " + connectURL+ "."); String[] params = connectURL.getQuery().split("&"); Map<String, String> map = new HashMap<String, String>(); for(String param : params) { String name = param.split("=")[0]; String value = param.split("=")[1]; map.put(name, value); } connectHash=map.get("server"); } finally { rdr.close(); } } finally { conn.disconnect(); } } catch (IOException ex) { logger.warn("Error sending hearbeat.", ex); } } }); } /** * Gets the salt. * @return The salt. */ public long getSalt() { return salt; } }
/* * $Id: LockssCardFilterRule.java,v 1.2 2005-02-04 20:21:13 troberts Exp $ */ package org.lockss.plugin.locksscard; import java.io.*; import java.util.List; import org.lockss.util.*; import org.lockss.filter.*; import org.lockss.plugin.FilterRule; public class LockssCardFilterRule implements FilterRule { private static final String filterStart = "<!--LOCKSS ignore start private static final String filterEnd = "<!--LOCKSS ignore end public Reader createFilteredReader(Reader reader) { HtmlTagFilter.TagPair pair = new HtmlTagFilter.TagPair(filterStart, filterEnd, true); Reader tagFilter = new HtmlTagFilter(reader, pair); return tagFilter; } }
package org.technbolts.eclipse.util; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.DocumentRewriteSession; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.IDocumentPartitionerExtension; import org.eclipse.jface.text.IDocumentPartitionerExtension2; import org.eclipse.jface.text.IDocumentPartitionerExtension3; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.TypedPosition; import org.eclipse.jface.text.TypedRegion; import org.eclipse.jface.text.rules.FastPartitioner; import org.eclipse.jface.text.rules.IPartitionTokenScanner; import org.eclipse.jface.text.rules.IToken; /** * Copy of {@link FastPartitioner} * * * A standard implementation of a document partitioner. It uses an * {@link IPartitionTokenScanner} to scan the document and to determine the * document's partitioning. The tokens returned by the scanner must return the * partition type as their data. The partitioner remembers the document's * partitions in the document itself rather than maintaining its own data * structure. * <p> * To reduce array creations in {@link IDocument#getPositions(String)}, the * positions get cached. The cache is cleared after updating the positions in * {@link #documentChanged2(DocumentEvent)}. Subclasses need to call * {@link #clearPositionCache()} after modifying the partitioner's positions. * The cached positions may be accessed through {@link #getPositions()}. * </p> * * @see IPartitionTokenScanner * @since 3.1 */ public class CustomFastPartitioner implements IDocumentPartitioner, IDocumentPartitionerExtension, IDocumentPartitionerExtension2, IDocumentPartitionerExtension3 { /** * The position category this partitioner uses to store the document's partitioning information. */ private static final String CONTENT_TYPES_CATEGORY= "__content_types_category"; //$NON-NLS-1$ /** The partitioner's scanner */ protected final IPartitionTokenScanner fScanner; protected final String[] fLegalContentTypes; /** The partitioner's document */ protected IDocument fDocument; /** The document length before a document change occurred */ protected int fPreviousDocumentLength; /** The position updater used to for the default updating of partitions */ protected final DefaultPositionUpdater fPositionUpdater; /** The offset at which the first changed partition starts */ protected int fStartOffset; /** The offset at which the last changed partition ends */ protected int fEndOffset; /**The offset at which a partition has been deleted */ protected int fDeleteOffset; /** * The position category this partitioner uses to store the document's partitioning information. */ private final String fPositionCategory; /** * The active document rewrite session. */ private DocumentRewriteSession fActiveRewriteSession; /** * Flag indicating whether this partitioner has been initialized. */ private boolean fIsInitialized= false; /** * The cached positions from our document, so we don't create a new array every time * someone requests partition information. */ private Position[] fCachedPositions= null; /** Debug option for cache consistency checking. */ private static final boolean CHECK_CACHE_CONSISTENCY= "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.jface.text/debug/FastPartitioner/PositionCache")); //$NON-NLS-1$//$NON-NLS-2$; public CustomFastPartitioner(IPartitionTokenScanner scanner, String[] legalContentTypes) { fScanner= scanner; fLegalContentTypes= TextUtilities.copy(legalContentTypes); fPositionCategory= CONTENT_TYPES_CATEGORY + hashCode(); fPositionUpdater= new DefaultPositionUpdater(fPositionCategory); } public void invalidate () { try { if(fDocument.containsPositionCategory(fPositionCategory)) fDocument.removePositionCategory(fPositionCategory); } catch (BadPositionCategoryException e) { } fDocument.addPositionCategory(fPositionCategory); } /* * @see org.eclipse.jface.text.IDocumentPartitionerExtension2#getManagingPositionCategories() */ public String[] getManagingPositionCategories() { return new String[] { fPositionCategory }; } /* * @see org.eclipse.jface.text.IDocumentPartitioner#connect(org.eclipse.jface.text.IDocument) */ public final void connect(IDocument document) { connect(document, false); } /** * {@inheritDoc} * <p> * May be extended by subclasses. * </p> */ public void connect(IDocument document, boolean delayInitialization) { Assert.isNotNull(document); Assert.isTrue(!document.containsPositionCategory(fPositionCategory)); fDocument= document; fDocument.addPositionCategory(fPositionCategory); fIsInitialized= false; if (!delayInitialization) checkInitialization(); } /** * Calls {@link #initialize()} if the receiver is not yet initialized. */ protected final void checkInitialization() { if (!fIsInitialized) initialize(); } /** * Performs the initial partitioning of the partitioner's document. * <p> * May be extended by subclasses. * </p> */ protected void initialize() { fIsInitialized= true; clearPositionCache(); fScanner.setRange(fDocument, 0, fDocument.getLength()); try { IToken token= fScanner.nextToken(); while (!token.isEOF()) { String contentType= getTokenContentType(token); if (isSupportedContentType(contentType)) { TypedPosition p= new TypedPosition(fScanner.getTokenOffset(), fScanner.getTokenLength(), contentType); fDocument.addPosition(fPositionCategory, p); } token= fScanner.nextToken(); } } catch (BadLocationException x) { // cannot happen as offsets come from scanner } catch (BadPositionCategoryException x) { // cannot happen if document has been connected before } } /** * {@inheritDoc} * <p> * May be extended by subclasses. * </p> */ public void disconnect() { Assert.isTrue(fDocument.containsPositionCategory(fPositionCategory)); try { fDocument.removePositionCategory(fPositionCategory); } catch (BadPositionCategoryException x) { // can not happen because of Assert } } /** * {@inheritDoc} * <p> * May be extended by subclasses. * </p> */ public void documentAboutToBeChanged(DocumentEvent e) { if (fIsInitialized) { Assert.isTrue(e.getDocument() == fDocument); fPreviousDocumentLength= e.getDocument().getLength(); fStartOffset= -1; fEndOffset= -1; fDeleteOffset= -1; } } /* * @see IDocumentPartitioner#documentChanged(DocumentEvent) */ public final boolean documentChanged(DocumentEvent e) { if (fIsInitialized) { IRegion region= documentChanged2(e); return (region != null); } return false; } /** * Helper method for tracking the minimal region containing all partition changes. * If <code>offset</code> is smaller than the remembered offset, <code>offset</code> * will from now on be remembered. If <code>offset + length</code> is greater than * the remembered end offset, it will be remembered from now on. * * @param offset the offset * @param length the length */ private void rememberRegion(int offset, int length) { // remember start offset if (fStartOffset == -1) fStartOffset= offset; else if (offset < fStartOffset) fStartOffset= offset; // remember end offset int endOffset= offset + length; if (fEndOffset == -1) fEndOffset= endOffset; else if (endOffset > fEndOffset) fEndOffset= endOffset; } /** * Remembers the given offset as the deletion offset. * * @param offset the offset */ private void rememberDeletedOffset(int offset) { fDeleteOffset= offset; } /** * Creates the minimal region containing all partition changes using the * remembered offset, end offset, and deletion offset. * * @return the minimal region containing all the partition changes */ private IRegion createRegion() { if (fDeleteOffset == -1) { if (fStartOffset == -1 || fEndOffset == -1) return null; return new Region(fStartOffset, fEndOffset - fStartOffset); } else if (fStartOffset == -1 || fEndOffset == -1) { return new Region(fDeleteOffset, 0); } else { int offset= Math.min(fDeleteOffset, fStartOffset); int endOffset= Math.max(fDeleteOffset, fEndOffset); return new Region(offset, endOffset - offset); } } /** * {@inheritDoc} * <p> * May be extended by subclasses. * </p> */ public IRegion documentChanged2(DocumentEvent e) { if (!fIsInitialized) return null; try { Assert.isTrue(e.getDocument() == fDocument); Position[] category= getPositions(); IRegion line= fDocument.getLineInformationOfOffset(e.getOffset()); int reparseStart= line.getOffset(); int partitionStart= -1; String contentType= null; int newLength= e.getText() == null ? 0 : e.getText().length(); int first= fDocument.computeIndexInCategory(fPositionCategory, reparseStart); if (first > 0) { TypedPosition partition= (TypedPosition) category[first - 1]; if (partition.includes(reparseStart)) { partitionStart= partition.getOffset(); contentType= partition.getType(); if (e.getOffset() == partition.getOffset() + partition.getLength()) reparseStart= partitionStart; -- first; } else if (reparseStart == e.getOffset() && reparseStart == partition.getOffset() + partition.getLength()) { partitionStart= partition.getOffset(); contentType= partition.getType(); reparseStart= partitionStart; -- first; } else { partitionStart= partition.getOffset() + partition.getLength(); contentType= IDocument.DEFAULT_CONTENT_TYPE; } } fPositionUpdater.update(e); for (int i= first; i < category.length; i++) { Position p= category[i]; if (p.isDeleted) { rememberDeletedOffset(e.getOffset()); break; } } clearPositionCache(); category= getPositions(); fScanner.setPartialRange(fDocument, reparseStart, fDocument.getLength() - reparseStart, contentType, partitionStart); int behindLastScannedPosition= reparseStart; IToken token= fScanner.nextToken(); while (!token.isEOF()) { contentType= getTokenContentType(token); if (!isSupportedContentType(contentType)) { token= fScanner.nextToken(); continue; } int start= fScanner.getTokenOffset(); int length= fScanner.getTokenLength(); behindLastScannedPosition= start + length; int lastScannedPosition= behindLastScannedPosition - 1; // remove all affected positions while (first < category.length) { TypedPosition p= (TypedPosition) category[first]; if (lastScannedPosition >= p.offset + p.length || (p.overlapsWith(start, length) && (!fDocument.containsPosition(fPositionCategory, start, length) || !contentType.equals(p.getType())))) { rememberRegion(p.offset, p.length); fDocument.removePosition(fPositionCategory, p); ++ first; } else break; } // if position already exists and we have scanned at least the // area covered by the event, we are done if (fDocument.containsPosition(fPositionCategory, start, length)) { if (lastScannedPosition >= e.getOffset() + newLength) return createRegion(); ++ first; } else { // insert the new type position try { fDocument.addPosition(fPositionCategory, new TypedPosition(start, length, contentType)); rememberRegion(start, length); } catch (BadPositionCategoryException x) { } catch (BadLocationException x) { } } token= fScanner.nextToken(); } first= fDocument.computeIndexInCategory(fPositionCategory, behindLastScannedPosition); clearPositionCache(); category= getPositions(); TypedPosition p; while (first < category.length) { p= (TypedPosition) category[first++]; fDocument.removePosition(fPositionCategory, p); rememberRegion(p.offset, p.length); } } catch (BadPositionCategoryException x) { // should never happen on connected documents } catch (BadLocationException x) { } finally { clearPositionCache(); } return createRegion(); } /** * Returns the position in the partitoner's position category which is * close to the given offset. This is, the position has either an offset which * is the same as the given offset or an offset which is smaller than the given * offset. This method profits from the knowledge that a partitioning is * a ordered set of disjoint position. * <p> * May be extended or replaced by subclasses. * </p> * @param offset the offset for which to search the closest position * @return the closest position in the partitioner's category */ protected TypedPosition findClosestPosition(int offset) { try { int index= fDocument.computeIndexInCategory(fPositionCategory, offset); Position[] category= getPositions(); if (category.length == 0) return null; if (index < category.length) { if (offset == category[index].offset) return (TypedPosition) category[index]; } if (index > 0) index return (TypedPosition) category[index]; } catch (BadPositionCategoryException x) { } catch (BadLocationException x) { } return null; } /** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> */ public String getContentType(int offset) { checkInitialization(); TypedPosition p= findClosestPosition(offset); if (p != null && p.includes(offset)) return p.getType(); return IDocument.DEFAULT_CONTENT_TYPE; } /** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> */ public ITypedRegion getPartition(int offset) { checkInitialization(); try { Position[] category = getPositions(); if (category == null || category.length == 0) return new TypedRegion(0, fDocument.getLength(), IDocument.DEFAULT_CONTENT_TYPE); int index= fDocument.computeIndexInCategory(fPositionCategory, offset); if (index < category.length) { TypedPosition next= (TypedPosition) category[index]; if (offset == next.offset) return new TypedRegion(next.getOffset(), next.getLength(), next.getType()); if (index == 0) return new TypedRegion(0, next.offset, IDocument.DEFAULT_CONTENT_TYPE); TypedPosition previous= (TypedPosition) category[index - 1]; if (previous.includes(offset)) return new TypedRegion(previous.getOffset(), previous.getLength(), previous.getType()); int endOffset= previous.getOffset() + previous.getLength(); return new TypedRegion(endOffset, next.getOffset() - endOffset, IDocument.DEFAULT_CONTENT_TYPE); } TypedPosition previous= (TypedPosition) category[category.length - 1]; if (previous.includes(offset)) return new TypedRegion(previous.getOffset(), previous.getLength(), previous.getType()); int endOffset= previous.getOffset() + previous.getLength(); return new TypedRegion(endOffset, fDocument.getLength() - endOffset, IDocument.DEFAULT_CONTENT_TYPE); } catch (BadPositionCategoryException x) { } catch (BadLocationException x) { } return new TypedRegion(0, fDocument.getLength(), IDocument.DEFAULT_CONTENT_TYPE); } /* * @see IDocumentPartitioner#computePartitioning(int, int) */ public final ITypedRegion[] computePartitioning(int offset, int length) { return computePartitioning(offset, length, false); } /** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> */ public String[] getLegalContentTypes() { return TextUtilities.copy(fLegalContentTypes); } protected boolean isSupportedContentType(String contentType) { if (contentType != null) { for (int i= 0; i < fLegalContentTypes.length; i++) { if (fLegalContentTypes[i].equals(contentType)) return true; } } return false; } /** * Returns a content type encoded in the given token. If the token's * data is not <code>null</code> and a string it is assumed that * it is the encoded content type. * <p> * May be replaced or extended by subclasses. * </p> * * @param token the token whose content type is to be determined * @return the token's content type */ protected String getTokenContentType(IToken token) { Object data= token.getData(); if (data instanceof String) return (String) data; return null; } /* zero-length partition support */ /** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> */ public String getContentType(int offset, boolean preferOpenPartitions) { return getPartition(offset, preferOpenPartitions).getType(); } /** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> */ public ITypedRegion getPartition(int offset, boolean preferOpenPartitions) { ITypedRegion region= getPartition(offset); if (preferOpenPartitions) { if (region.getOffset() == offset && !region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE)) { if (offset > 0) { region= getPartition(offset - 1); if (region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE)) return region; } return new TypedRegion(offset, 0, IDocument.DEFAULT_CONTENT_TYPE); } } return region; } /** * {@inheritDoc} * <p> * May be replaced or extended by subclasses. * </p> */ public ITypedRegion[] computePartitioning(int offset, int length, boolean includeZeroLengthPartitions) { checkInitialization(); List<TypedRegion> list= new ArrayList<TypedRegion>(); try { int endOffset= offset + length; Position[] category= getPositions(); TypedPosition previous= null, current= null; int start, end, gapOffset; Position gap= new Position(0); int startIndex= getFirstIndexEndingAfterOffset(category, offset); int endIndex= getFirstIndexStartingAfterOffset(category, endOffset); for (int i= startIndex; i < endIndex; i++) { current= (TypedPosition) category[i]; gapOffset= (previous != null) ? previous.getOffset() + previous.getLength() : 0; gap.setOffset(gapOffset); if(current.getOffset() > gapOffset) { gap.setLength(current.getOffset() - gapOffset); if ((includeZeroLengthPartitions && overlapsOrTouches(gap, offset, length)) || (gap.getLength() > 0 && gap.overlapsWith(offset, length))) { start= Math.max(offset, gapOffset); end= Math.min(endOffset, gap.getOffset() + gap.getLength()); list.add(new TypedRegion(start, end - start, IDocument.DEFAULT_CONTENT_TYPE)); } } if (current.overlapsWith(offset, length)) { start= Math.max(offset, current.getOffset()); end= Math.min(endOffset, current.getOffset() + current.getLength()); list.add(new TypedRegion(start, end - start, current.getType())); } previous= current; } if (previous != null) { gapOffset= previous.getOffset() + previous.getLength(); gap.setOffset(gapOffset); if(fDocument.getLength() > gapOffset) { gap.setLength(fDocument.getLength() - gapOffset); if ((includeZeroLengthPartitions && overlapsOrTouches(gap, offset, length)) || (gap.getLength() > 0 && gap.overlapsWith(offset, length))) { start= Math.max(offset, gapOffset); end= Math.min(endOffset, fDocument.getLength()); list.add(new TypedRegion(start, end - start, IDocument.DEFAULT_CONTENT_TYPE)); } } } if (list.isEmpty()) list.add(new TypedRegion(offset, length, IDocument.DEFAULT_CONTENT_TYPE)); } catch (BadPositionCategoryException ex) { // Make sure we clear the cache clearPositionCache(); } catch (RuntimeException ex) { // Make sure we clear the cache clearPositionCache(); throw ex; } TypedRegion[] result= new TypedRegion[list.size()]; list.toArray(result); return result; } /** * Returns <code>true</code> if the given ranges overlap with or touch each other. * * @param gap the first range * @param offset the offset of the second range * @param length the length of the second range * @return <code>true</code> if the given ranges overlap with or touch each other */ private boolean overlapsOrTouches(Position gap, int offset, int length) { return gap.getOffset() <= offset + length && offset <= gap.getOffset() + gap.getLength(); } /** * Returns the index of the first position which ends after the given offset. * * @param positions the positions in linear order * @param offset the offset * @return the index of the first position which ends after the offset */ private int getFirstIndexEndingAfterOffset(Position[] positions, int offset) { int i= -1, j= positions.length; while (j - i > 1) { int k= (i + j) >> 1; Position p= positions[k]; if (p.getOffset() + p.getLength() > offset) j= k; else i= k; } return j; } /** * Returns the index of the first position which starts at or after the given offset. * * @param positions the positions in linear order * @param offset the offset * @return the index of the first position which starts after the offset */ private int getFirstIndexStartingAfterOffset(Position[] positions, int offset) { int i= -1, j= positions.length; while (j - i > 1) { int k= (i + j) >> 1; Position p= positions[k]; if (p.getOffset() >= offset) j= k; else i= k; } return j; } /* * @see org.eclipse.jface.text.IDocumentPartitionerExtension3#startRewriteSession(org.eclipse.jface.text.DocumentRewriteSession) */ public void startRewriteSession(DocumentRewriteSession session) throws IllegalStateException { if (fActiveRewriteSession != null) throw new IllegalStateException(); fActiveRewriteSession= session; } /** * {@inheritDoc} * <p> * May be extended by subclasses. * </p> */ public void stopRewriteSession(DocumentRewriteSession session) { if (fActiveRewriteSession == session) flushRewriteSession(); } /** * {@inheritDoc} * <p> * May be extended by subclasses. * </p> */ public DocumentRewriteSession getActiveRewriteSession() { return fActiveRewriteSession; } /** * Flushes the active rewrite session. */ protected final void flushRewriteSession() { fActiveRewriteSession= null; // remove all position belonging to the partitioner position category try { fDocument.removePositionCategory(fPositionCategory); } catch (BadPositionCategoryException x) { } fDocument.addPositionCategory(fPositionCategory); fIsInitialized= false; } /** * Clears the position cache. Needs to be called whenever the positions have * been updated. */ protected final void clearPositionCache() { if (fCachedPositions != null) { fCachedPositions= null; } } /** * Returns the partitioners positions. * * @return the partitioners positions * @throws BadPositionCategoryException if getting the positions from the * document fails */ protected final Position[] getPositions() throws BadPositionCategoryException { if (fCachedPositions == null) { fCachedPositions= fDocument.getPositions(fPositionCategory); } else if (CHECK_CACHE_CONSISTENCY) { Position[] positions= fDocument.getPositions(fPositionCategory); int len= Math.min(positions.length, fCachedPositions.length); for (int i= 0; i < len; i++) { if (!positions[i].equals(fCachedPositions[i])) System.err.println("FastPartitioner.getPositions(): cached position is not up to date: from document: " + toString(positions[i]) + " in cache: " + toString(fCachedPositions[i])); //$NON-NLS-1$ //$NON-NLS-2$ } for (int i= len; i < positions.length; i++) System.err.println("FastPartitioner.getPositions(): new position in document: " + toString(positions[i])); //$NON-NLS-1$ for (int i= len; i < fCachedPositions.length; i++) System.err.println("FastPartitioner.getPositions(): stale position in cache: " + toString(fCachedPositions[i])); //$NON-NLS-1$ } return fCachedPositions; } /** * Pretty print a <code>Position</code>. * * @param position the position to format * @return a formatted string */ private String toString(Position position) { return "P[" + position.getOffset() + "+" + position.getLength() + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } }
package lib.orianna.type.staticdata; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class MasteryTree implements Serializable { private static final long serialVersionUID = -1878212419731346677L; public final List<MasteryTreeList> defense, offense, utility; private final Map<Mastery, MasteryType> types; public MasteryTree(final List<MasteryTreeList> defense, final List<MasteryTreeList> offense, final List<MasteryTreeList> utility) { this.defense = defense; this.offense = offense; this.utility = utility; types = new HashMap<Mastery, MasteryType>(); offense.forEach((list) -> list.masteryTreeItems.forEach((item) -> { if(item != null) { types.put(item.mastery, MasteryType.OFFENSE); } })); defense.forEach((list) -> list.masteryTreeItems.forEach((item) -> { if(item != null) { types.put(item.mastery, MasteryType.DEFENSE); } })); utility.forEach((list) -> list.masteryTreeItems.forEach((item) -> { if(item != null) { types.put(item.mastery, MasteryType.UTILITY); } })); } /** * Gets defensive masteries * * @return defensive masteries */ public List<Mastery> defensiveMasteries() { return Collections.unmodifiableList(types.entrySet().stream().filter((entry) -> entry.getValue() == MasteryType.DEFENSE).map((entry) -> entry.getKey()) .collect(Collectors.toList())); } @Override public boolean equals(final Object obj) { if(this == obj) { return true; } if(obj == null) { return false; } if(!(obj instanceof MasteryTree)) { return false; } final MasteryTree other = (MasteryTree)obj; if(defense == null) { if(other.defense != null) { return false; } } else if(!defense.equals(other.defense)) { return false; } if(offense == null) { if(other.offense != null) { return false; } } else if(!offense.equals(other.offense)) { return false; } if(utility == null) { if(other.utility != null) { return false; } } else if(!utility.equals(other.utility)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (defense == null ? 0 : defense.hashCode()); result = prime * result + (offense == null ? 0 : offense.hashCode()); result = prime * result + (utility == null ? 0 : utility.hashCode()); return result; } /** * Gets offensive masteries * * @return offensive masteries */ public List<Mastery> offensiveMasteries() { return Collections.unmodifiableList(types.entrySet().stream().filter((entry) -> entry.getValue() == MasteryType.OFFENSE).map((entry) -> entry.getKey()) .collect(Collectors.toList())); } @Override public String toString() { return "MasteryTree"; } /** * Determines of what type a mastery is (offense, defense, utility) * * @param mastery * the mastery to test * @return the mastery's type */ public MasteryType typeOf(final Mastery mastery) { return types.get(mastery); } /** * Gets utility masteries * * @return utility masteries */ public List<Mastery> utilityMasteries() { return Collections.unmodifiableList(types.entrySet().stream().filter((entry) -> entry.getValue() == MasteryType.UTILITY).map((entry) -> entry.getKey()) .collect(Collectors.toList())); } }
package pitt.search.semanticvectors; import java.util.Hashtable; import java.util.Enumeration; import java.util.Random; import java.io.IOException; import java.lang.RuntimeException; import org.apache.lucene.index.IndexModifier; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermDocs; import org.apache.lucene.index.TermEnum; import org.apache.lucene.analysis.standard.StandardAnalyzer; /** * Implementation of vector store that creates term vectors by * iterating through all the terms in a Lucene index. Uses a sparse * representation for the basic document vectors, which saves * considerable space for collections with many individual documents. * * @author Dominic Widdows, Trevor Cohen. */ public class TermVectorsFromLucene implements VectorStore { private Hashtable<String, ObjectVector> termVectors; private IndexReader indexReader; private int seedLength; private String[] fieldsToIndex; private LuceneUtils lUtils; private int nonAlphabet; private int minFreq; private VectorStore basicDocVectors; // Basic accessor methods. /** * @return The object's basicDocVectors. */ public VectorStore getBasicDocVectors(){ return this.basicDocVectors; } /** * @return The object's indexReader. */ public IndexReader getIndexReader(){ return this.indexReader; } /** * @return The object's list of Lucene fields to index. */ public String[] getFieldsToIndex(){ return this.fieldsToIndex; } /** * @param indexDir Directory containing Lucene index. * @param seedLength Number of +1 or -1 entries in basic * vectors. Should be even to give same number of each. * @param minFreq The minimum term frequency for a term to be indexed. * @param basicDocVectors The store of basic document vectors. Null * is an acceptable value, in which case the constructor will build * this table. If non-null, the identifiers must correspond to the Lucene doc numbers. * @param fieldsToIndex These fields will be indexed. If null, all fields will be indexed. */ public TermVectorsFromLucene(String indexDir, int seedLength, int minFreq, int nonAlphabet, VectorStore basicDocVectors, String[] fieldsToIndex) throws IOException, RuntimeException { this.minFreq = minFreq; this.nonAlphabet = nonAlphabet; this.fieldsToIndex = fieldsToIndex; this.seedLength = seedLength; /* This small preprocessing step uses an IndexModifier to make * sure that the Lucene index is optimized to use contiguous * integers as identifiers, otherwise exceptions can occur if * document id's are greater than indexReader.numDocs(). */ IndexModifier modifier = new IndexModifier(indexDir, new StandardAnalyzer(), false); modifier.optimize(); modifier.close(); // Create LuceneUtils Class to filter terms. lUtils = new LuceneUtils(indexDir); indexReader = IndexReader.open(indexDir); // Check that basicDocVectors is the right size. if (basicDocVectors != null) { this.basicDocVectors = basicDocVectors; System.out.println("Reusing basic doc vectors; number of documents: " + basicDocVectors.getNumVectors()); if (basicDocVectors.getNumVectors() != indexReader.numDocs()) { throw new RuntimeException("Wrong number of basicDocVectors " + "passed into constructor ..."); } } else { // Create basic doc vectors in vector store. // Derived term vectors will be linear combinations of these. System.err.println("Populating basic sparse doc vector store, number of vectors: " + indexReader.numDocs()); VectorStoreSparseRAM randomBasicDocVectors = new VectorStoreSparseRAM(); randomBasicDocVectors.CreateRandomVectors(indexReader.numDocs(), this.seedLength); this.basicDocVectors = randomBasicDocVectors; } termVectors = new Hashtable<String, ObjectVector>(); // Iterate through an enumeration of terms and create termVector table. System.err.println("Creating term vectors ..."); TermEnum terms = this.indexReader.terms(); int tc = 0; while(terms.next()){ tc++; } System.err.println("There are " + tc + " terms (and " + indexReader.numDocs() + " docs)"); tc = 0; terms = indexReader.terms(); while (terms.next()) { // Output progress counter. if (( tc % 10000 == 0 ) || ( tc < 10000 && tc % 1000 == 0 )) { System.err.print(tc + " ... "); } tc++; Term term = terms.term(); // Skip terms that don't pass the filter. if (!lUtils.termFilter(terms.term(), fieldsToIndex, nonAlphabet, minFreq)) { continue; } // Initialize new termVector. float[] termVector = new float[Flags.dimension]; for (int i = 0; i < Flags.dimension; ++i) { termVector[i] = 0; } TermDocs tDocs = indexReader.termDocs(term); while (tDocs.next()) { String docID = Integer.toString(tDocs.doc()); float[] docVector = this.basicDocVectors.getVector(docID); int freq = tDocs.freq(); for (int i = 0; i < Flags.dimension; ++i) { termVector[i] += freq * docVector[i]; } } termVector = VectorUtils.getNormalizedVector(termVector); termVectors.put(term.text(), new ObjectVector(term.text(), termVector)); } System.err.println("\nCreated " + termVectors.size() + " term vectors ..."); } /** * This constructor generates an elemental vector for each term. These elemental (random index) vectors will * be used to construct document vectors, a procedure we have called term-based reflective random indexing * @param indexDir the directory of the Lucene Index * @param seedLength Number of +1 or -1 entries in basic * vectors. Should be even to give same number of each. * @param nonAlphabet the number of nonalphabet characters permitted * @param minFreq The minimum term frequency for a term to be indexed. * @param fieldsToIndex the fields to be indexed (most commonly "contents") */ public TermVectorsFromLucene(String indexDir, int seedLength, int minFreq, int nonAlphabet, String[] fieldsToIndex) throws IOException, RuntimeException { this.minFreq = minFreq; this.nonAlphabet = nonAlphabet; this.fieldsToIndex = fieldsToIndex; this.seedLength = seedLength; /* This small preprocessing step uses an IndexModifier to make * sure that the Lucene index is optimized to use contiguous * integers as identifiers, otherwise exceptions can occur if * document id's are greater than indexReader.numDocs(). */ IndexModifier modifier = new IndexModifier(indexDir, new StandardAnalyzer(), false); modifier.optimize(); modifier.close(); // Create LuceneUtils Class to filter terms. lUtils = new LuceneUtils(indexDir); indexReader = IndexReader.open(indexDir); Random random = new Random(); this.termVectors = new Hashtable<String,ObjectVector>(); // For each term in the index TermEnum terms = indexReader.terms(); int tc = 0; while(terms.next()){ Term term = terms.term(); // Skip terms that don't pass the filter. if (!lUtils.termFilter(terms.term(), fieldsToIndex, nonAlphabet, minFreq)) { continue; } tc++; short[] indexVector = VectorUtils.generateRandomVector(seedLength, random); float[] indexVector2 = VectorUtils.getNormalizedVector(VectorUtils.sparseVectorToFloatVector(indexVector, Flags.dimension)); // Place each term vector in the vector store. this.termVectors.put(term.text(), new ObjectVector(term.text(),VectorUtils.sparseVectorToFloatVector(indexVector, Flags.dimension))); } } public float[] getVector(Object term) { return termVectors.get(term).getVector(); } public Enumeration getAllVectors() { return termVectors.elements(); } public int getNumVectors() { return termVectors.size(); } }
package ch.ice.controller; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.time.StopWatch; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.EncryptedDocumentException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.json.JSONArray; import org.json.JSONObject; import ch.ice.controller.file.FileParserFactory; import ch.ice.controller.file.FileWriterFactory; import ch.ice.controller.interf.Parser; import ch.ice.controller.interf.SearchEngine; import ch.ice.controller.interf.Writer; import ch.ice.controller.threads.SearchThread; import ch.ice.controller.web.ResultAnalyzer; import ch.ice.controller.web.SearchEngineFactory; import ch.ice.exceptions.FileParserNotAvailableException; import ch.ice.exceptions.IllegalFileExtensionException; import ch.ice.exceptions.InternalFormatException; import ch.ice.exceptions.MissingCustomerRowsException; import ch.ice.model.Customer; import ch.ice.utils.Config; import ch.ice.utils.JSONStandardizedKeys; import ch.ice.view.SaveWindowController; public class MainController { public static final Logger logger = LogManager.getLogger(MainController.class.getName()); public static File uploadedFileContainingCustomers; /** * List containing all rendered Customers */ public static List<Customer> customerList; public static int customersEnhanced; public static String progressText; private static StopWatch stopwatch; /** * Searchengine to be used.<br > * See: {@see SearchEngineFactory} */ public static String searchEngineIdentifier; /** * Requested Searchengine. */ private static SearchEngine searchEngine; /** * Limit searchresult that will be returned from the SearchEngine */ private static Integer limitSearchResults; /** * Fallback url if search is not available */ public static URL defaultUrl; public static boolean isSearchAvail; /** * Searchengine to be used.<br > * See: {@see SearchEngineFactory} - Available SearchEngines: Google or Bing */ public static boolean fileWriterFactory; public static boolean processEnded = false; /** * All available Metatags */ public static List<String> metaTagElements; public static List<Customer> firstArray; public static List<Customer> secondArray; public static List<Customer> thirdArray; public static List<Customer> fourthArray; // file Parser private static Parser fileParser; public static Writer fileWriter = null; /** * This is the main controller. From here the whole program gets controlled. * I/O and lookups are also triggered from here. * * @throws InternalFormatException * @throws MissingCustomerRowsException * @throws InterruptedException */ public void startMainController() throws InternalFormatException, MissingCustomerRowsException, InterruptedException { // Core settings isSearchAvail = false; defaultUrl = null; PropertiesConfiguration config = Config.PROPERTIES; metaTagElements = new ArrayList<String>(); /* * Load Configuration File */ try { isSearchAvail = config.getBoolean("core.search.isEnabled"); defaultUrl = new URL(config.getString("core.search.defaultUrl")); MainController.limitSearchResults = config.getInteger( "searchEngine.limitSearchResult", 5); metaTagElements = Arrays.asList(config .getStringArray("crawler.searchForMetaTags")); } catch (MalformedURLException e) { logger.error("Faild to load config file"); } // for test without gui if (searchEngineIdentifier == null) { searchEngineIdentifier = "BING"; } // request new SearchEngine MainController.searchEngine = SearchEngineFactory .requestSearchEngine(MainController.searchEngineIdentifier); logger.info("Starting " + searchEngine.getClass().getName()); stopwatch = new StopWatch(); stopwatch.start(); // For testing if used without GUI if (uploadedFileContainingCustomers == null) { MainController.customerList = retrieveCustomerFromFile(new File( "posTest.xlsx")); } else { MainController.customerList = retrieveCustomerFromFile(uploadedFileContainingCustomers); // retrieve all customers from file logger.info("Retrieve Customers from File " + uploadedFileContainingCustomers.getAbsolutePath()); } stopwatch.split(); logger.info("Spilt: " + stopwatch.toSplitString() + " total: " + stopwatch.toString()); int listSize = customerList.size(); int quarterSize = listSize / 4; int firstEnd = quarterSize; int secondStart = quarterSize; int secondEnd = (quarterSize) * 2; int thirdStart = 2 * quarterSize; int thirdEnd = quarterSize * 3; int fourthStart = quarterSize * 3; int fourthEnd = listSize; System.out.println(0 + ", " + firstEnd + ", " + secondStart + ", " + secondEnd + ", " + thirdStart + ", " + thirdEnd + ", " + fourthStart + ", " + fourthEnd); if (listSize < 16) { System.out.println("Below 16"); firstArray = new ArrayList<Customer>(customerList); SearchThread s1 = new SearchThread(); s1.setCheckNumber(1); s1.setSearchList(firstArray); Thread t1 = new Thread(s1); t1.setName("FIRST THREAD"); t1.start(); t1.join(); customerList.clear(); customerList.addAll(s1.getSearchList()); } else { firstArray = new ArrayList<Customer>(customerList.subList(0, firstEnd)); secondArray = new ArrayList<Customer>(customerList.subList( secondStart, secondEnd)); thirdArray = new ArrayList<Customer>(customerList.subList( thirdStart, thirdEnd)); fourthArray = new ArrayList<Customer>(customerList.subList( fourthStart, fourthEnd)); SearchThread s1 = new SearchThread(); s1.setCheckNumber(1); s1.setSearchList(firstArray); Thread t1 = new Thread(s1); t1.setName("FIRST THREAD"); System.out.println("First Thread Size: " + s1.getSearchList().size()); SearchThread s2 = new SearchThread(); s2.setCheckNumber(2); s2.setSearchList(secondArray); Thread t2 = new Thread(s2); t2.setName("SECOND THREAD"); System.out.println("Second Thread Size: " + s2.getSearchList().size()); SearchThread s3 = new SearchThread(); s3.setCheckNumber(4); s3.setSearchList(thirdArray); Thread t3 = new Thread(s3); t3.setName("THIRD THREAD"); System.out.println("Third Thread Size: " + s3.getSearchList().size()); SearchThread s4 = new SearchThread(); s4.setCheckNumber(4); s4.setSearchList(fourthArray); Thread t4 = new Thread(s4); t4.setName("FOURTH THREAD"); System.out.println("Fourth Thread Size: " + s4.getSearchList().size()); t1.start(); t2.start(); t3.start(); t4.start(); t1.join(); t2.join(); t3.join(); t4.join(); System.out.println("First Thread Size: " + s1.getSearchList().size()); System.out.println("Second Thread Size: " + s2.getSearchList().size()); System.out.println("Third Thread Size: " + s3.getSearchList().size()); System.out.println("Fourth Thread Size: " + s4.getSearchList().size()); customerList.clear(); customerList.addAll(s1.getSearchList()); customerList.addAll(s2.getSearchList()); customerList.addAll(s3.getSearchList()); customerList.addAll(s4.getSearchList()); } stopwatch.split(); logger.info("Spilt: " + stopwatch.toSplitString() + " total: " + stopwatch.toString()); /* * Write every enhanced customer object into a new file */ SaveWindowController.myBooWriting = true; this.startWriter(MainController.customerList); stopwatch.stop(); logger.info("Spilt: " + stopwatch.toSplitString() + " total: " + stopwatch.toString()); logger.info("end"); SaveWindowController.myBoo = true; processEnded = true; } /** * Each Row returns a customer object. These customers are saved in a * List-Object. * * @param file * @return List of Customers from file. Each row in a file represents a * customer * @throws InternalFormatException * , MissingCustomerRowsException */ public static List<Customer> retrieveCustomerFromFile(File file) throws InternalFormatException, MissingCustomerRowsException { String uploadedFileExtension = FilenameUtils.getExtension(file .getName()); String fileParserIdentifier = ""; switch (uploadedFileExtension) { case "xlsx": case "xls": fileParserIdentifier = FileParserFactory.EXCEL; break; case "csv": fileParserIdentifier = FileParserFactory.CSV; break; } try { MainController.fileParser = FileParserFactory .requestParser(fileParserIdentifier); return MainController.fileParser.readFile(file); } catch (FileParserNotAvailableException | EncryptedDocumentException | InvalidFormatException | IOException | IllegalFileExtensionException e) { logger.error(e.getMessage()); } return new LinkedList<Customer>(); } /** * Search for a Customers URL based on his name and other parameters. * * @param Customer * @return URL of Customer - Depends on the quality of the search engine */ public URL searchForUrl(Customer c) { // more parameters can be added. These parameters are similar to Googles // site: input. E.g. Automation site:schurter.com List<String> params = new ArrayList<String>(); params.add(c.getFullName().toLowerCase()); String lookupQuery = MainController.searchEngine.buildQuery(params); progressText = "Lookup on: " + lookupQuery; logger.info("Lookup " + MainController.searchEngine.getClass().getName() + " with Query \"" + lookupQuery + "\""); try { // Start Search JSONArray results = MainController.searchEngine.search(lookupQuery, MainController.limitSearchResults, c.getCountryCode().toLowerCase()); // logic to pick the first record ; here should be the search logic! JSONObject aResult = ResultAnalyzer.analyse(results, params); c.getWebsite().setUnsure(aResult.getBoolean("Unsure")); // return only the URL form first object return new URL((String) aResult.get(JSONStandardizedKeys.URL)); } catch (Exception e) { e.printStackTrace(); System.out.println("FEHLER!!!!!!!"); } return defaultUrl; } /** * Write enhanced customer array into a file and save it to the selected * directory * * @param customerList */ public void startWriter(List<Customer> enhancedCustomerList) { logger.info("Start writing customers to File"); try { if (fileWriterFactory == true) { fileWriter = FileWriterFactory .requestFileWriter(FileWriterFactory.EXCEL); } if (fileWriterFactory == false) { fileWriter = FileWriterFactory .requestFileWriter(FileWriterFactory.CSV); } } catch (FileParserNotAvailableException e) { e.printStackTrace(); } try { fileWriter.writeFile(enhancedCustomerList, MainController.fileParser); } catch (IOException e) { // TODO Throw this to gui!!!!!!!!!!!!!!!!!!!!!!!!! e.printStackTrace(); } } public void stopThread(String threadName) throws InterruptedException { ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); Thread[] threads = new Thread[threadGroup.activeCount()]; threadGroup.enumerate(threads); for (int nIndex = 0; nIndex < threads.length; nIndex++) { if (threads[nIndex] != null && threads[nIndex].getName().equals(threadName)) { threads[nIndex].stop(); } } } }
import java.io.*; import java.net.*; import java.sql.SQLException; import java.util.ArrayList; import DatabaseModel.DatabaseConnection; import DatabaseModel.Tables.Product; public class Server { public static int PortNumber = 2035; private static ServerSocket MyService; public static void main(String[] args) { // TODO Auto-generated method stub try { Server.Run(); } catch (IOException exception) { System.out.println(exception); if (MyService != null && MyService.isClosed() == false) { try { MyService.close(); } catch (IOException ioCloseException) { System.out.println(ioCloseException); } } } } public static void Run() throws IOException { MyService = new ServerSocket(PortNumber); DatabaseConnection db; ArrayList<Product> products; /*Testing serialization and deserialization*/ try { db = new DatabaseConnection(true); } catch (SQLException exception) { System.out.println("Failed to connect to database - " + exception); return; } try { products = db.select(Product.class); } catch (SQLException exception) { System.out.println("Failed to get products for client - " + exception); return; } FileOutputStream stream = new FileOutputStream("tmp/Product.ser"); // WHYYY DO YOU HAVE TO SERIALIZE IN THIS WAY JAVA; WHAT THE FUCK. ObjectOutputStream objectStream = new ObjectOutputStream(stream); objectStream.writeObject(products); objectStream.close(); stream.close(); FileInputStream fileInputStream = new FileInputStream("tmp/Product.ser"); // Java serialization still sucks dunkey dick. ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); try { ArrayList<Product> deserializedProduct = (ArrayList<Product>)objectInputStream.readObject(); for (Product product : deserializedProduct) { System.out.print(product); } } catch (ClassNotFoundException anExceptionThatShouldNeverBeThrown) { System.out.println(anExceptionThatShouldNeverBeThrown); return; } objectInputStream.close(); fileInputStream.close(); /*Testing ended*/ // Next up send the individual OutputFileStream bytes to the client. And parse it there. boolean Running = true; while(Running = true) { Socket s=MyService.accept(); System.out.println("Connection Etableret"); OutputStream obj=s.getOutputStream(); PrintStream ps=new PrintStream(obj); String str = "Hej Klient"; ps.println(str); ps.println("Bye"); ps.close(); MyService.close(); s.close(); } } }
package authenticator; import authenticator.BAGeneralEventsListener.HowBalanceChanged; import authenticator.BAApplicationParameters.NetworkType; import authenticator.helpers.exceptions.AddressNotWatchedByWalletException; import authenticator.helpers.exceptions.AddressWasNotFoundException; import authenticator.hierarchy.BAHierarchy; import authenticator.hierarchy.HierarchyUtils; import authenticator.hierarchy.exceptions.IncorrectPathException; import authenticator.hierarchy.exceptions.KeyIndexOutOfRangeException; import authenticator.hierarchy.exceptions.NoAccountCouldBeFoundException; import authenticator.hierarchy.exceptions.NoUnusedKeyException; import java.io.FileNotFoundException; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import javafx.scene.image.Image; import javax.annotation.Nullable; import org.json.JSONException; import org.slf4j.Logger; import wallettemplate.Main; import authenticator.Utils.EncodingUtils; import authenticator.db.ConfigFile; import authenticator.protobuf.AuthWalletHierarchy.HierarchyAddressTypes; import authenticator.protobuf.AuthWalletHierarchy.HierarchyCoinTypes; import authenticator.protobuf.ProtoConfig.ATAddress; import authenticator.protobuf.ProtoConfig.AuthenticatorConfiguration; import authenticator.protobuf.ProtoConfig.AuthenticatorConfiguration.ATAccount; import authenticator.protobuf.ProtoConfig.PairedAuthenticator; import authenticator.protobuf.ProtoConfig.PendingRequest; import authenticator.protobuf.ProtoConfig.WalletAccountType; import com.google.bitcoin.core.AbstractWalletEventListener; import com.google.bitcoin.core.Address; import com.google.bitcoin.core.AddressFormatException; import com.google.bitcoin.core.Coin; import com.google.bitcoin.core.ECKey; import com.google.bitcoin.core.InsufficientMoneyException; import com.google.bitcoin.core.NetworkParameters; import com.google.bitcoin.core.PeerGroup; import com.google.bitcoin.core.ScriptException; import com.google.bitcoin.core.Transaction; import com.google.bitcoin.core.TransactionConfidence; import com.google.bitcoin.core.TransactionConfidence.ConfidenceType; import com.google.bitcoin.core.TransactionInput; import com.google.bitcoin.core.TransactionOutput; import com.google.bitcoin.core.Utils; import com.google.bitcoin.core.Wallet; import com.google.bitcoin.core.WalletEventListener; import com.google.bitcoin.core.Wallet.ExceededMaxTransactionSize; import com.google.bitcoin.core.Wallet.SendResult; import com.google.bitcoin.crypto.DeterministicKey; import com.google.bitcoin.crypto.HDKeyDerivation; import com.google.bitcoin.crypto.TransactionSignature; import com.google.bitcoin.script.Script; import com.google.bitcoin.script.ScriptBuilder; import com.google.bitcoin.wallet.CoinSelection; import com.google.bitcoin.wallet.DefaultCoinSelector; import com.google.bitcoin.wallet.DeterministicSeed; import com.google.common.collect.ImmutableList; /** *<p>A super class for handling all wallet operations<br> * This class covers DB data retrieving, bitcoinj wallet operations, Authenticator wallet operations<br></p> * * <b>Main components are:</b> * <ol> * <li>{@link authenticator.WalletWrapper} for normal bitcoinj wallet operations</li> * <li>Authenticator wallet operations</li> * <li>Pending requests control</li> * <li>Active account control</li> * </ol> * @author Alon */ public class WalletOperation extends BASE{ public static WalletWrapper mWalletWrapper; private static BAHierarchy authenticatorWalletHierarchy; public static ConfigFile configFile; private static Logger staticLogger; private BAApplicationParameters AppParams; public WalletOperation(){ super(WalletOperation.class); } /** * Instantiate WalletOperations without bitcoinj wallet. * * @param params * @throws IOException */ public WalletOperation(BAApplicationParameters params, DeterministicKey mpubkey) throws IOException{ super(WalletOperation.class); init(params, mpubkey); } /** * Instantiate WalletOperations with bitcoinj wallet * * @param wallet * @param peerGroup * @throws IOException */ public WalletOperation(Wallet wallet, PeerGroup peerGroup, BAApplicationParameters params, DeterministicKey mpubkey) throws IOException{ super(WalletOperation.class); if(mWalletWrapper == null){ mWalletWrapper = new WalletWrapper(wallet,peerGroup); mWalletWrapper.addEventListener(new WalletListener()); } init(params, mpubkey); } public void dispose(){ mWalletWrapper = null; authenticatorWalletHierarchy = null; configFile = null; staticLogger = null; } private void init(BAApplicationParameters params, DeterministicKey mpubkey) throws IOException{ staticLogger = this.LOG; AppParams = params; if(configFile == null){ configFile = new ConfigFile(params.getAppName()); /** * Check to see if a config file exists, if not, initialize */ if(!configFile.checkConfigFile()){ //byte[] seed = BAHierarchy.generateMnemonicSeed(); configFile.initConfigFile(mpubkey); } } if(authenticatorWalletHierarchy == null) { //byte[] seed = configFile.getHierarchySeed(); authenticatorWalletHierarchy = new BAHierarchy(mpubkey,HierarchyCoinTypes.CoinBitcoin); /** * Load num of keys generated in every account to get * the next fresh key */ List<BAHierarchy.AccountTracker> accountTrackers = new ArrayList<BAHierarchy.AccountTracker>(); List<ATAccount> allAccount = getAllAccounts(); for(ATAccount acc:allAccount){ BAHierarchy.AccountTracker at = new BAHierarchy().new AccountTracker(acc.getIndex(), BAHierarchy.keyLookAhead, acc.getUsedExternalKeysList(), acc.getUsedInternalKeysList()); accountTrackers.add(at); } authenticatorWalletHierarchy.buildWalletHierarchyForStartup(accountTrackers); } if(mWalletWrapper != null){ new Thread(){ @Override public void run() { try { updateBalace(mWalletWrapper.getTrackedWallet()); } catch (Exception e) { e.printStackTrace(); } } }.start(); } } public BAApplicationParameters getApplicationParams(){ return AppParams; } /** *A basic listener to keep track of balances and transaction state.<br> *Will mark addresses as "used" when any amount of bitcoins were transfered to the address. * * @author alon * */ public static boolean isRequiringBalanceChange = true; public class WalletListener extends AbstractWalletEventListener { @Override public void onCoinsSent(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { try { staticLogger.info("Updating balance, Received {}, Sent {}", tx.getValueSentToMe(wallet).toFriendlyString(), tx.getValueSentFromMe(wallet).toFriendlyString()); isRequiringBalanceChange = true; updateBalace(wallet); notifyBalanceUpdate(wallet,tx); } catch (Exception e) { e.printStackTrace(); } } @Override public void onCoinsReceived(Wallet wallet, Transaction tx, Coin prevBalance, Coin newBalance) { try { staticLogger.info("Updating balance, Received {}, Sent {}", tx.getValueSentToMe(wallet).toFriendlyString(), tx.getValueSentFromMe(wallet).toFriendlyString()); isRequiringBalanceChange = true; updateBalace(wallet); notifyBalanceUpdate(wallet,tx); } catch (Exception e) { e.printStackTrace(); } } @Override public void onTransactionConfidenceChanged(Wallet wallet, Transaction tx) { try { if(isRequiringBalanceChange){ staticLogger.info("Updating balance, Received {}, Sent {}", tx.getValueSentToMe(wallet).toFriendlyString(), tx.getValueSentFromMe(wallet).toFriendlyString()); updateBalace(wallet); notifyBalanceUpdate(wallet,tx); isRequiringBalanceChange = false; } } catch (Exception e) { e.printStackTrace(); } } private void notifyBalanceUpdate(Wallet wallet, Transaction tx){ if(tx.getValueSentToMe(wallet).signum() > 0){ Authenticator.fireOnBalanceChanged(tx, HowBalanceChanged.ReceivedCoins, tx.getConfidence().getConfidenceType()); } if(tx.getValueSentFromMe(wallet).signum() > 0){ Authenticator.fireOnBalanceChanged(tx, HowBalanceChanged.SentCoins, tx.getConfidence().getConfidenceType()); } } } @SuppressWarnings("incomplete-switch") private synchronized void updateBalace(Wallet wallet) throws Exception{ List<ATAccount> accounts = getAllAccounts(); for(ATAccount acc:accounts){ setConfirmedBalance(acc.getIndex(), Coin.ZERO); setUnConfirmedBalance(acc.getIndex(), Coin.ZERO); } List<Transaction> allTx = wallet.getRecentTransactions(0, false); Collections.reverse(allTx); for(Transaction tx: allTx){ /** * BUILDING */ if(tx.getConfidence().getConfidenceType() == ConfidenceType.BUILDING){ if(tx.getValueSentToMe(wallet).signum() > 0){ for (TransactionOutput out : tx.getOutputs()){ Script scr = out.getScriptPubKey(); String addrStr = scr.getToAddress(getNetworkParams()).toString(); if(isWatchingAddress(addrStr)){ ATAddress add = Authenticator.getWalletOperation().findAddressInAccounts(addrStr); addToConfirmedBalance(add.getAccountIndex(), out.getValue()); } } } if(tx.getValueSentFromMe(wallet).signum() > 0){ for (TransactionInput in : tx.getInputs()){ TransactionOutput out = in.getConnectedOutput(); if(out != null){ Script scr = out.getScriptPubKey(); String addrStr = scr.getToAddress(getNetworkParams()).toString(); if(isWatchingAddress(addrStr)){ ATAddress add = Authenticator.getWalletOperation().findAddressInAccounts(addrStr); subtractFromConfirmedBalance(add.getAccountIndex(), out.getValue()); } } } } } /** * PENDING */ if(tx.getConfidence().getConfidenceType() == ConfidenceType.PENDING){ if(tx.getValueSentToMe(wallet).signum() > 0){ for (TransactionOutput out : tx.getOutputs()){ Script scr = out.getScriptPubKey(); String addrStr = scr.getToAddress(getNetworkParams()).toString(); if(isWatchingAddress(addrStr)){ ATAddress add = Authenticator.getWalletOperation().findAddressInAccounts(addrStr); addToUnConfirmedBalance(add.getAccountIndex(), out.getValue()); } } } if(tx.getValueSentFromMe(wallet).signum() > 0){ for (TransactionInput in : tx.getInputs()){ TransactionOutput out = in.getConnectedOutput(); if(out != null){ Script scr = out.getScriptPubKey(); String addrStr = scr.getToAddress(getNetworkParams()).toString(); if(isWatchingAddress(addrStr)){ ATAddress add = Authenticator.getWalletOperation().findAddressInAccounts(addrStr); subtractFromConfirmedBalance(add.getAccountIndex(), out.getValue()); } } } } } } } // // Authenticator Wallet Operations // /**Pushes the raw transaction * @throws InsufficientMoneyException */ public SendResult pushTxWithWallet(Transaction tx) throws IOException, InsufficientMoneyException{ this.LOG.info("Broadcasting to network..."); return mWalletWrapper.broadcastTrabsactionFromWallet(tx); } /** * Derives a child public key from the master public key. Generates a new local key pair. * Uses the two public keys to create a 2of2 multisig address. Saves key and address to json file. * @throws JSONException * @throws NoSuchAlgorithmException * @throws AddressFormatException * @throws NoAccountCouldBeFoundException * @throws NoUnusedKeyException * @throws KeyIndexOutOfRangeException * @throws IncorrectPathException */ private ATAddress generateNextP2SHAddress(int accountIdx, HierarchyAddressTypes addressType) throws NoSuchAlgorithmException, JSONException, AddressFormatException, NoUnusedKeyException, NoAccountCouldBeFoundException, KeyIndexOutOfRangeException, IncorrectPathException{ PairedAuthenticator po = getPairingObjectForAccountIndex(accountIdx); return generateNextP2SHAddress(po.getPairingID(), addressType); } @SuppressWarnings({ "deprecation" }) private ATAddress generateNextP2SHAddress(String pairingID, HierarchyAddressTypes addressType) throws NoSuchAlgorithmException, JSONException, AddressFormatException, NoUnusedKeyException, NoAccountCouldBeFoundException, KeyIndexOutOfRangeException, IncorrectPathException{ try { //Create a new key pair for wallet DeterministicKey walletHDKey = null; int walletAccountIdx = getAccountIndexForPairing(pairingID); int keyIndex = -1; if(addressType == HierarchyAddressTypes.External){ walletHDKey = getNextExternalKey(walletAccountIdx, false); keyIndex = HierarchyUtils.getKeyIndexFromPath(walletHDKey.getPath()).num();//walletHDKey.getPath().get(walletHDKey.getPath().size() - 1).num(); } /*else walletHDKey = getNextSavingsKey(this.getAccountIndexForPairing(pairingID));*/ ECKey walletKey = null; if(!walletHDKey.isPubKeyOnly()) walletKey = new ECKey(walletHDKey.getPrivKeyBytes(), walletHDKey.getPubKey()); else walletKey = new ECKey(null, walletHDKey.getPubKey()); //Derive the child public key from the master public key. PairedAuthenticator po = getPairingObject(pairingID); ECKey authKey = getPairedAuthenticatorKey(po, keyIndex); // generate P2SH ATAddress p2shAdd = getP2SHAddress(authKey, walletKey, keyIndex, walletAccountIdx, addressType); addAddressToWatch(p2shAdd.getAddressStr()); return p2shAdd; } catch (IOException e) { e.printStackTrace(); return null; } } /** * * * @param k1 * @param k2 * @param indxK - <b>is the same for both keys, make sure they are both HD derived</b> * @param accountIndx * @param addressType * @return */ private ATAddress getP2SHAddress(ECKey k1, ECKey k2, int indxK, int accountIndx, HierarchyAddressTypes addressType){ //network params NetworkParameters params = getNetworkParams(); //Create a 2-of-2 multisig output script. List<ECKey> keys = ImmutableList.of(k1,k2);//childPubKey, walletKey); byte[] scriptpubkey = Script.createMultiSigOutputScript(2,keys); Script script = ScriptBuilder.createP2SHOutputScript(Utils.sha256hash160(scriptpubkey)); //Create the address Address multisigaddr = Address.fromP2SHScript(params, script); // generate object String ret = multisigaddr.toString(); ATAddress.Builder b = ATAddress.newBuilder(); b.setAccountIndex(accountIndx);//walletAccountIdx); b.setAddressStr(ret); b.setIsUsed(true); b.setKeyIndex(indxK);//walletAccount.getLastExternalIndex()); b.setType(addressType); return b.build(); } @SuppressWarnings("static-access") public Transaction mkUnsignedTxWithSelectedInputs(ArrayList<TransactionOutput> outSelected, ArrayList<TransactionOutput>to, Coin fee, String changeAdd, @Nullable NetworkParameters np) throws AddressFormatException, JSONException, IOException, NoSuchAlgorithmException, IllegalArgumentException { Transaction tx; if(np == null) tx = new Transaction(getNetworkParams()); else tx = new Transaction(np); //Get total output Coin totalOut = Coin.ZERO; for (TransactionOutput out:to){ totalOut = totalOut.add(out.getValue()); } //Check minimum output if(totalOut.compareTo(Transaction.MIN_NONDUST_OUTPUT) < 0) throw new IllegalArgumentException("Tried to send dust with ensureMinRequiredFee set - no way to complete this"); // add inputs Coin inAmount = Coin.ZERO; for (TransactionOutput input : outSelected){ tx.addInput(input); inAmount = inAmount.add(input.getValue()); } //Check in covers the out if(inAmount.compareTo(totalOut.add(fee)) < 0) throw new IllegalArgumentException("Insufficient funds! You cheap bastard !"); //Add the outputs for (TransactionOutput output : to) tx.addOutput(output); //Add the change Address change = new Address(getNetworkParams(), changeAdd); Coin rest = inAmount.subtract(totalOut.add(fee)); if(rest.compareTo(Transaction.MIN_NONDUST_OUTPUT) > 0){ TransactionOutput changeOut = new TransactionOutput(this.mWalletWrapper.getNetworkParameters(), null, rest, change); tx.addOutput(changeOut); this.LOG.info("New Out Tx Sends " + totalOut.toFriendlyString() + ", Fees " + fee.toFriendlyString() + ", Rest " + rest.toFriendlyString() + ". From " + Integer.toString(tx.getInputs().size()) + " Inputs" + ", To " + Integer.toString(tx.getOutputs().size()) + " Outputs."); } else{ fee = fee.add(rest); this.LOG.info("New Out Tx Sends " + totalOut.toFriendlyString() + ", Fees " + fee.toFriendlyString() + ". From " + Integer.toString(tx.getInputs().size()) + " Inputs" + ", To " + Integer.toString(tx.getOutputs().size()) + " Outputs."); } // Check size. int size = tx.bitcoinSerialize().length; if (size > Transaction.MAX_STANDARD_TX_SIZE) throw new ExceededMaxTransactionSize(); return tx; } /** * If WALLET_PW is null, assumes wallet is not encrypted * * @param tx * @param keys * @param WALLET_PW * @return * @throws KeyIndexOutOfRangeException * @throws AddressFormatException * @throws AddressNotWatchedByWalletException */ public Transaction signStandardTxWithAddresses(Transaction tx, Map<String,ATAddress> keys, @Nullable String WALLET_PW) throws KeyIndexOutOfRangeException, AddressFormatException, AddressNotWatchedByWalletException{ Map<String,ECKey> keys2 = new HashMap<String,ECKey> (); for(String k:keys.keySet()){ ECKey addECKey = getPrivECKeyFromAccount(keys.get(k).getAccountIndex(), HierarchyAddressTypes.External, keys.get(k).getKeyIndex(), WALLET_PW, true); keys2.put(k, addECKey); } return signStandardTx(tx, keys2); } private Transaction signStandardTx(Transaction tx, Map<String,ECKey> keys){ // sign for(int index=0;index < tx.getInputs().size(); index++){ TransactionInput in = tx.getInput(index); TransactionOutput connectedOutput = in.getConnectedOutput(); String addFrom = connectedOutput.getScriptPubKey().getToAddress(Authenticator.getWalletOperation().getNetworkParams()).toString(); TransactionSignature sig = tx.calculateSignature(index, keys.get(addFrom), connectedOutput.getScriptPubKey(), Transaction.SigHash.ALL, false); Script inputScript = ScriptBuilder.createInputScript(sig, keys.get(addFrom)); in.setScriptSig(inputScript); try { in.getScriptSig().correctlySpends(tx, index, connectedOutput.getScriptPubKey(), false); } catch (ScriptException e) { return null; } } return tx; } // // Keys handling // /** * Generate a new wallet account and writes it to the config file * @return * @throws IOException */ private ATAccount generateNewAccount(NetworkType nt, String accountName, WalletAccountType type) throws IOException{ int accoutnIdx = authenticatorWalletHierarchy.generateNewAccount().getAccountIndex(); ATAccount b = completeAccountObject(nt, accoutnIdx, accountName, type); //writeHierarchyNextAvailableAccountID(accoutnIdx + 1); // update addNewAccountToConfigAndHierarchy(b); return b; } /** * Giving the necessary params, will return a complete {@link authenticator.protobuf.ProtoConfig.AuthenticatorConfiguration.ATAccount ATAccount} object * * @param nt * @param accoutnIdx * @param accountName * @param type * @return */ public ATAccount completeAccountObject(NetworkType nt, int accoutnIdx, String accountName, WalletAccountType type){ ATAccount.Builder b = ATAccount.newBuilder(); b.setIndex(accoutnIdx); b.setConfirmedBalance(0); b.setUnConfirmedBalance(0); b.setNetworkType(nt.getValue()); b.setAccountName(accountName); b.setAccountType(type); return b.build(); } /** * Register an account in the config file. Should be used whenever a new account is created * @param b * @throws IOException */ public void addNewAccountToConfigAndHierarchy(ATAccount b) throws IOException{ configFile.addAccount(b); staticLogger.info("Generated new account at index, " + b.getIndex()); authenticatorWalletHierarchy.addAccountToTracker(b.getIndex(), BAHierarchy.keyLookAhead); staticLogger.info("Added an account at index, " + b.getIndex() + " to hierarchy"); } public ATAccount generateNewStandardAccount(NetworkType nt, String accountName) throws IOException{ ATAccount ret = generateNewAccount(nt, accountName, WalletAccountType.StandardAccount); Authenticator.fireOnNewStandardAccountAdded(); return ret; } /** * Get the next {@link authenticator.protobuf.ProtoConfig.ATAddress ATAddress} object that is not been used, <b>it may been seen already</b><br> * If the account is a <b>standard Pay-To-PubHash</b>, a Pay-To-PubHash address will be returned (prefix 1).<br> * If the account is a <b>P2SH</b>, a P2SH address will be returned (prefix 3).<br> * * @param accountI * @return * @throws Exception */ public ATAddress getNextExternalAddress(int accountI) throws Exception{ ATAccount acc = getAccount(accountI); if(acc.getAccountType() == WalletAccountType.StandardAccount) return getNextExternalPayToPubHashAddress(accountI,true); else return generateNextP2SHAddress(accountI, HierarchyAddressTypes.External); } /** * * @param accountI * @param shouldAddToWatchList * @return * @throws Exception */ private ATAddress getNextExternalPayToPubHashAddress(int accountI, boolean shouldAddToWatchList) throws Exception{ DeterministicKey hdKey = getNextExternalKey(accountI,shouldAddToWatchList); ATAddress ret = getATAddreessFromAccount(accountI, HierarchyAddressTypes.External, HierarchyUtils.getKeyIndexFromPath(hdKey.getPath()).num()); return ret; } /** * * @param accountI * @param shouldAddToWatchList * @return * @throws AddressFormatException * @throws IOException * @throws NoAccountCouldBeFoundException * @throws NoUnusedKeyException * @throws KeyIndexOutOfRangeException */ private DeterministicKey getNextExternalKey(int accountI, boolean shouldAddToWatchList) throws AddressFormatException, IOException, NoUnusedKeyException, NoAccountCouldBeFoundException, KeyIndexOutOfRangeException{ DeterministicKey ret = authenticatorWalletHierarchy.getNextPubKey(accountI, HierarchyAddressTypes.External); if(shouldAddToWatchList) addAddressToWatch( ret.toAddress(getNetworkParams()).toString() ); return ret; } public ECKey getPrivECKeyFromAccount(int accountIndex, HierarchyAddressTypes type, int addressKey, String WALLET_PW, boolean iKnowAddressFromKeyIsNotWatched) throws KeyIndexOutOfRangeException, AddressFormatException, AddressNotWatchedByWalletException{ DeterministicKey ret = getPrivKeyFromAccount(accountIndex, type, addressKey, WALLET_PW, iKnowAddressFromKeyIsNotWatched); return new ECKey(ret.getPrivKeyBytes(), ret.getPubKey()); } /** * <b>The method remains public if any external method need it.</b><br> * If u don't know if the corresponding Pay-To-PubHash address is watched, will throw exception. <br> * If the key is part of a P2SH address, pass false for iKnowAddressFromKeyIsNotWatched<br> * If the key was never created before, use {@link authenticator.WalletOperation#getNextExternalAddress getNextExternalAddress} instead. * * @param accountIndex * @param type * @param addressKey * @param WALLET_PW * @param iKnowAddressFromKeyIsNotWatched * @return * @throws KeyIndexOutOfRangeException * @throws AddressFormatException * @throws AddressNotWatchedByWalletException */ public DeterministicKey getPrivKeyFromAccount(int accountIndex, HierarchyAddressTypes type, int addressKey, String WALLET_PW, boolean iKnowAddressFromKeyIsNotWatched) throws KeyIndexOutOfRangeException, AddressFormatException, AddressNotWatchedByWalletException{ byte[] seed = getWalletSeed(WALLET_PW); DeterministicKey ret = authenticatorWalletHierarchy.getPrivKeyFromAccount(seed, accountIndex, type, addressKey); if(!iKnowAddressFromKeyIsNotWatched && !isWatchingAddress(ret.toAddress(getNetworkParams()))) throw new AddressNotWatchedByWalletException("You are trying to get an unwatched address"); return ret; } public DeterministicKey getPubKeyFromAccount(int accountIndex, HierarchyAddressTypes type, int addressKey, boolean iKnowAddressFromKeyIsNotWatched) throws KeyIndexOutOfRangeException, AddressFormatException, AddressNotWatchedByWalletException{ DeterministicKey ret = authenticatorWalletHierarchy.getPubKeyFromAccount(accountIndex, type, addressKey); if(!iKnowAddressFromKeyIsNotWatched && !isWatchingAddress(ret.toAddress(getNetworkParams()))) throw new AddressNotWatchedByWalletException("You are trying to get an unwatched address"); return ret; } /** * <b>WARNING</b> - This is a very costly operation !!<br> * Finds an address in the accounts, will throw exception if not.<br> * Will only search for external address cause its reasonable that only they will be needing search with only the address string.<br> * <br> * <b>Assumes the address is already watched by the wallet</b> * * @param addressStr * @return {@link authenticator.protobuf.ProtoConfig.ATAddress ATAddress} * @throws AddressWasNotFoundException * @throws KeyIndexOutOfRangeException * @throws AddressFormatException * @throws JSONException * @throws NoSuchAlgorithmException */ public ATAddress findAddressInAccounts(String addressStr) throws AddressWasNotFoundException, NoSuchAlgorithmException, JSONException, AddressFormatException, KeyIndexOutOfRangeException{ if(!isWatchingAddress(addressStr)) throw new AddressWasNotFoundException("Cannot find address in accounts"); List<ATAccount> accounts = getAllAccounts(); int gapLookAhead = 30; while(gapLookAhead < 10000) // just arbitrary number, TODO - this is very stupid !! { for(ATAccount acc:accounts){ for(int i = gapLookAhead - 30 ; i < gapLookAhead; i++) { try{ ATAddress add = getATAddreessFromAccount(acc.getIndex(), HierarchyAddressTypes.External, i); if(add.getAddressStr().equals(addressStr)) return add; } catch (AddressNotWatchedByWalletException e) { break; // address is not watched which means we reached the end on the generated addresses } } } gapLookAhead += 30; } throw new AddressWasNotFoundException("Cannot find address in accounts"); } /** * get addresses from a particular account and his chain * * @param accountIndex * @param type * @param limit * @return * @throws NoSuchAlgorithmException * @throws JSONException * @throws AddressFormatException * @throws KeyIndexOutOfRangeException * @throws AddressNotWatchedByWalletException */ public List<ATAddress> getATAddreessesFromAccount(int accountIndex, HierarchyAddressTypes type,int standOff, int limit) throws NoSuchAlgorithmException, JSONException, AddressFormatException, KeyIndexOutOfRangeException, AddressNotWatchedByWalletException{ List<ATAddress> ret = new ArrayList<ATAddress>(); if(type == HierarchyAddressTypes.External) for(int i = standOff;i <= limit; i++)//Math.min(limit==-1? acc.getLastExternalIndex():limit, acc.getLastExternalIndex()) ; i++){ { ret.add(getATAddreessFromAccount(accountIndex, type, i)); } return ret; } /** * Gets a particular address from an account.<br> * Will assert that the address was created before, if not will throw exception. * * * @param accountIndex * @param type * @param addressKey * @return * @throws NoSuchAlgorithmException * @throws JSONException * @throws AddressFormatException * @throws KeyIndexOutOfRangeException * @throws AddressNotWatchedByWalletException */ @SuppressWarnings("static-access") public ATAddress getATAddreessFromAccount(int accountIndex, HierarchyAddressTypes type, int addressKey) throws NoSuchAlgorithmException, JSONException, AddressFormatException, KeyIndexOutOfRangeException, AddressNotWatchedByWalletException{ ATAccount acc = getAccount(accountIndex); ATAddress.Builder atAdd = ATAddress.newBuilder(); atAdd.setAccountIndex(accountIndex); atAdd.setKeyIndex(addressKey); atAdd.setType(type); /** * Standard Pay-To-PubHash */ if(acc.getAccountType() == WalletAccountType.StandardAccount){ //TODO - THIS LINE THROWS A NULLPOINTER EXCEPTION DUE TO CHANGE IN HIERARCHY DeterministicKey hdKey = getPubKeyFromAccount(accountIndex,type,addressKey, false); atAdd.setAddressStr(hdKey.toAddress(getNetworkParams()).toString()); } else{ /** * P2SH */ PairedAuthenticator po = getPairingObjectForAccountIndex(accountIndex); // Auth key ECKey authKey = getPairedAuthenticatorKey(po, addressKey); // wallet key ECKey walletKey = getPubKeyFromAccount(accountIndex, type, addressKey, true); //get address ATAddress add = getP2SHAddress(authKey, walletKey, addressKey, accountIndex, type); atAdd.setAddressStr(add.getAddressStr()); } return atAdd.build(); } public List<ATAccount> getAllAccounts(){ return configFile.getAllAccounts(); } public ATAccount getAccount(int index){ return configFile.getAccount(index); } /** * Remove account from config file.<br> * <b>Will assert at least one account remains after the removal</b> * * @param index * @throws IOException */ public void removeAccount(int index) throws IOException{ PairedAuthenticator po = getPairingObjectForAccountIndex(index); if(po != null) removePairingObject(po.getPairingID()); configFile.removeAccount(index); staticLogger.info("Removed account at index, " + index); Authenticator.fireOnAccountDeleted(index); } public ATAccount getAccountByName(String name){ List<ATAccount> all = getAllAccounts(); for(ATAccount acc: all) if(acc.getAccountName().equals(name)) return acc; return null; } /** * * @param accountIndex * @param addressesType * @param limit * @return * @throws NoSuchAlgorithmException * @throws JSONException * @throws AddressFormatException * @throws KeyIndexOutOfRangeException * @throws AddressNotWatchedByWalletException */ public ArrayList<String> getAccountNotUsedAddress(int accountIndex, HierarchyAddressTypes addressesType, int limit) throws NoSuchAlgorithmException, JSONException, AddressFormatException, KeyIndexOutOfRangeException, AddressNotWatchedByWalletException{ ArrayList<String> ret = new ArrayList<String>(); ATAccount account = getAccount(accountIndex); if(addressesType == HierarchyAddressTypes.External) for(int i=0;i < limit; i++)//Math.min(account.getLastExternalIndex(), limit == -1? account.getLastExternalIndex():limit); i++){ { if(account.getUsedExternalKeysList().contains(i)) continue; ATAddress a = getATAddreessFromAccount(accountIndex,addressesType, i); ret.add(a.getAddressStr()); } return ret; } /** * Will return all used address of the account * * @param accountIndex * @param addressesType * @return * @throws NoSuchAlgorithmException * @throws JSONException * @throws AddressFormatException * @throws KeyIndexOutOfRangeException * @throws AddressNotWatchedByWalletException */ public ArrayList<ATAddress> getAccountUsedAddresses(int accountIndex, HierarchyAddressTypes addressesType) throws NoSuchAlgorithmException, JSONException, AddressFormatException, KeyIndexOutOfRangeException, AddressNotWatchedByWalletException{ ArrayList<ATAddress> ret = new ArrayList<ATAddress>(); ATAccount acc = getAccount(accountIndex); if(addressesType == HierarchyAddressTypes.External){ List<Integer> used = acc.getUsedExternalKeysList(); for(Integer i:used){ ATAddress a = getATAddreessFromAccount(accountIndex,addressesType, i); ret.add(a); } } return ret; } public ArrayList<String> getAccountUsedAddressesString(int accountIndex, HierarchyAddressTypes addressesType) throws NoSuchAlgorithmException, JSONException, AddressFormatException, KeyIndexOutOfRangeException, AddressNotWatchedByWalletException{ ArrayList<ATAddress> addresses = getAccountUsedAddresses(accountIndex, addressesType); ArrayList<String> ret = new ArrayList<String>(); for(ATAddress add: addresses) ret.add(add.getAddressStr()); return ret; } /** * Returns all addresses from an account in a ArrayList of strings * * @param accountIndex * @param addressesType * @param limit * @return ArrayList of strings * @throws NoSuchAlgorithmException * @throws JSONException * @throws AddressFormatException * @throws KeyIndexOutOfRangeException * @throws AddressNotWatchedByWalletException */ public ArrayList<String> getAccountAddresses(int accountIndex, HierarchyAddressTypes addressesType, int limit) throws NoSuchAlgorithmException, JSONException, AddressFormatException, KeyIndexOutOfRangeException, AddressNotWatchedByWalletException{ ArrayList<String> ret = new ArrayList<String>(); if(addressesType == HierarchyAddressTypes.External) for(int i=0;i < limit; i ++) //Math.min(account.getLastExternalIndex(), limit == -1? account.getLastExternalIndex():limit); i++){ { ATAddress a = getATAddreessFromAccount(accountIndex,addressesType, i); ret.add(a.getAddressStr()); } return ret; } public ATAccount setAccountName(String newName, int index) throws IOException{ assert(newName.length() > 0); ATAccount.Builder b = ATAccount.newBuilder(getAccount(index)); b.setAccountName(newName); configFile.updateAccount(b.build()); Authenticator.fireOnAccountBeenModified(index); return b.build(); } public void markAddressAsUsed(int accountIdx, int addIndx, HierarchyAddressTypes type) throws IOException, NoSuchAlgorithmException, JSONException, AddressFormatException, NoAccountCouldBeFoundException, KeyIndexOutOfRangeException, AddressNotWatchedByWalletException{ configFile.markAddressAsUsed(accountIdx, addIndx,type); authenticatorWalletHierarchy.markAddressAsUsed(accountIdx, addIndx, type); ATAddress add = getATAddreessFromAccount(accountIdx, type, addIndx); this.LOG.info("Marked " + add.getAddressStr() + " as used."); } /*public int getHierarchyNextAvailableAccountID(){ return configFile.getHierarchyNextAvailableAccountID(); } public void writeHierarchyNextAvailableAccountID(int i) throws IOException{ configFile.writeHierarchyNextAvailableAccountID(i); }*/ /*public byte[] getHierarchySeed() throws FileNotFoundException, IOException{ return configFile.getHierarchySeed(); } public void writeHierarchySeed(byte[] seed) throws FileNotFoundException, IOException{ configFile.writeHierarchySeed(seed); }*/ // // Pairing handling // public PairedAuthenticator getPairingObjectForAccountIndex(int accIdx){ List<PairedAuthenticator> all = new ArrayList<PairedAuthenticator>(); try { all = getAllPairingObjectArray(); } catch (IOException e) { e.printStackTrace(); } for(PairedAuthenticator po: all) { if(po.getWalletAccountIndex() == accIdx) { return po; } } return null; } public int getAccountIndexForPairing(String PairID){ List<PairedAuthenticator> all = new ArrayList<PairedAuthenticator>(); try { all = getAllPairingObjectArray(); } catch (IOException e) { e.printStackTrace(); } for(PairedAuthenticator po: all) { if(po.getPairingID().equals(PairID)) { return po.getWalletAccountIndex(); } } return -1; } /** * Returns all addresses from a pairing in a ArrayList of strings * * @param accountIndex * @param addressesType * @return ArrayList of strings * @throws NoSuchAlgorithmException * @throws JSONException * @throws AddressFormatException * @throws KeyIndexOutOfRangeException * @throws AddressNowWatchedByWalletException */ public ArrayList<String> getPairingAddressesArray(String PairID, HierarchyAddressTypes addressesType, int limit) throws NoSuchAlgorithmException, JSONException, AddressFormatException, KeyIndexOutOfRangeException, AddressNotWatchedByWalletException{ int accIndex = getAccountIndexForPairing(PairID); return getAccountAddresses(accIndex,addressesType, limit); } /**Returns the Master Public Key and Chaincode as an ArrayList object */ public ArrayList<String> getPublicKeyAndChain(String pairingID){ List<PairedAuthenticator> all = new ArrayList<PairedAuthenticator>(); try { all = getAllPairingObjectArray(); } catch (IOException e) { e.printStackTrace(); } ArrayList<String> ret = new ArrayList<String>(); for(PairedAuthenticator o:all) { if(o.getPairingID().equals(pairingID)) { ret.add(o.getMasterPublicKey()); ret.add(o.getChainCode()); } } return ret; } public ECKey getPairedAuthenticatorKey(PairedAuthenticator po, int keyIndex){ ArrayList<String> keyandchain = getPublicKeyAndChain(po.getPairingID()); byte[] key = EncodingUtils.hexStringToByteArray(keyandchain.get(0)); byte[] chain = EncodingUtils.hexStringToByteArray(keyandchain.get(1)); HDKeyDerivation HDKey = null; DeterministicKey mPubKey = HDKey.createMasterPubKeyFromBytes(key, chain); DeterministicKey childKey = HDKey.deriveChildKey(mPubKey, keyIndex); byte[] childpublickey = childKey.getPubKey(); ECKey authKey = new ECKey(null, childpublickey); return authKey; } /**Returns the number of key pairs in the wallet */ public long getKeyNum(String pairID){ List<PairedAuthenticator> all = new ArrayList<PairedAuthenticator>(); try { all = getAllPairingObjectArray(); } catch (IOException e) { e.printStackTrace(); } for(PairedAuthenticator o:all) { if(o.getPairingID().equals(pairID)) return o.getKeysN(); } return 0; } /**Pulls the AES key from file and returns it */ public String getAESKey(String pairID) { List<PairedAuthenticator> all = new ArrayList<PairedAuthenticator>(); try { all = getAllPairingObjectArray(); } catch (IOException e) { e.printStackTrace(); } for(PairedAuthenticator o:all) { if(o.getPairingID().equals(pairID)) return o.getAesKey(); } return ""; } public List<PairedAuthenticator> getAllPairingObjectArray() throws FileNotFoundException, IOException { return configFile.getAllPairingObjectArray(); } public PairedAuthenticator getPairingObject(String pairID) { List<PairedAuthenticator> all = new ArrayList<PairedAuthenticator>(); try { all = getAllPairingObjectArray(); } catch (IOException e) { e.printStackTrace(); } for(PairedAuthenticator po: all) if(po.getPairingID().equals(pairID)) return po; return null; } public ArrayList<String> getPairingIDs() { List<PairedAuthenticator> all = new ArrayList<PairedAuthenticator>(); try { all = getAllPairingObjectArray(); } catch (IOException e) { e.printStackTrace(); } ArrayList<String> ret = new ArrayList<String>(); for(PairedAuthenticator o:all) ret.add(o.getPairingID()); return ret; } /** * If accID is provided, will not create a new account but will use the account ID * * @param authMpubkey * @param authhaincode * @param sharedAES * @param GCM * @param pairingID * @param pairName * @param accID * @param nt * @throws IOException */ public void generatePairing(String authMpubkey, String authhaincode, String sharedAES, String GCM, String pairingID, String pairName, @Nullable Integer accID, NetworkType nt) throws IOException{ int accountID ; if( accID == null ) accountID = generateNewAccount(nt, pairName, WalletAccountType.AuthenticatorAccount).getIndex(); else{ accountID = accID; ATAccount a = completeAccountObject(nt, accountID, pairName, WalletAccountType.AuthenticatorAccount); addNewAccountToConfigAndHierarchy(a); } writePairingData(authMpubkey,authhaincode,sharedAES,GCM,pairingID,accountID); Authenticator.fireOnNewPairedAuthenticator(); } private void writePairingData(String mpubkey, String chaincode, String key, String GCM, String pairingID, int accountIndex) throws IOException{ configFile.writePairingData(mpubkey, chaincode, key, GCM, pairingID, accountIndex); } /** * * @param pairingID * @throws FileNotFoundException * @throws IOException */ private void removePairingObject(String pairingID) throws FileNotFoundException, IOException{ configFile.removePairingObject(pairingID); } /*public void addGeneratedAddressForPairing(String pairID, String addr, int indexWallet, int indexAuth) throws FileNotFoundException, IOException, ParseException{ configFile.addGeneratedAddressForPairing(pairID, addr, indexWallet, indexAuth); }*/ // // Balances handling // public Coin getConfirmedBalance(int accountIdx){ long balance = configFile.getConfirmedBalace(accountIdx); return Coin.valueOf(balance); } /** * Will return updated balance * * @param accountIdx * @param amount * @return * @throws IOException */ public Coin addToConfirmedBalance(int accountIdx, Coin amount) throws IOException{ Coin old = getConfirmedBalance(accountIdx); Coin ret = setConfirmedBalance(accountIdx, old.add(amount)); staticLogger.info("Added " + amount.toFriendlyString() + " to confirmed balance. Account: " + accountIdx ); return ret; } /** * Will return updated balance * * @param accountIdx * @param amount * @return * @throws IOException */ public Coin subtractFromConfirmedBalance(int accountIdx, Coin amount) throws IOException{ Coin old = getConfirmedBalance(accountIdx); staticLogger.info("Subtracting " + amount.toFriendlyString() + " from confirmed balance(" + old.toFriendlyString() + "). Account: " + accountIdx); assert(old.compareTo(amount) >= 0); Coin ret = setConfirmedBalance(accountIdx, old.subtract(amount)); return ret; } /** * Will return the updated balance * * @param accountIdx * @param newBalance * @return * @throws IOException */ public Coin setConfirmedBalance(int accountIdx, Coin newBalance) throws IOException{ long balance = configFile.writeConfirmedBalace(accountIdx, newBalance.longValue()); Coin ret = Coin.valueOf(balance); return ret; } public Coin getUnConfirmedBalance(int accountIdx){ long balance = configFile.getUnConfirmedBalace(accountIdx); return Coin.valueOf(balance); } /** * Will return updated balance * * @param accountIdx * @param amount * @return * @throws IOException */ public Coin addToUnConfirmedBalance(int accountIdx, Coin amount) throws IOException{ Coin old = getUnConfirmedBalance(accountIdx); Coin ret = setUnConfirmedBalance(accountIdx, old.add(amount)); staticLogger.info("Added " + amount.toFriendlyString() + " to unconfirmed balance. Account: " + accountIdx ); return ret; } /** * Will return updated balance * * @param accountIdx * @param amount * @return * @throws IOException */ public Coin subtractFromUnConfirmedBalance(int accountIdx, Coin amount) throws IOException{ Coin old = getUnConfirmedBalance(accountIdx); staticLogger.info("Subtracting " + amount.toFriendlyString() + " from unconfirmed balance(" + old.toFriendlyString() + "). Account: " + accountIdx); assert(old.compareTo(amount) >= 0); Coin ret = setUnConfirmedBalance(accountIdx, old.subtract(amount)); return ret; } /** * Will return the updated balance * * @param accountIdx * @param newBalance * @return * @throws IOException */ public Coin setUnConfirmedBalance(int accountIdx, Coin newBalance) throws IOException{ long balance = configFile.writeUnConfirmedBalace(accountIdx, newBalance.longValue()); return Coin.valueOf(balance); } /** * Will return the updated confirmed balance * * @param accountId * @param amount * @return * @throws IOException */ public Coin moveFundsFromUnconfirmedToConfirmed(int accountId,Coin amount) throws IOException{ Coin beforeConfirmed = getConfirmedBalance(accountId); Coin beforeUnconf = getUnConfirmedBalance(accountId); staticLogger.info("Moving " + amount.toFriendlyString() + " from unconfirmed(" + beforeUnconf.toFriendlyString() +") to confirmed(" + beforeConfirmed.toFriendlyString() + ") balance. Account: " + accountId ); assert(beforeUnconf.compareTo(amount) >= 0); Coin afterConfirmed = beforeConfirmed.add(amount); Coin afterUnconfirmed = beforeUnconf.subtract(amount); setConfirmedBalance(accountId,afterConfirmed); setUnConfirmedBalance(accountId,afterUnconfirmed); return afterConfirmed; } /** * Will return the updated unconfirmed balance * * @param accountId * @param amount * @return * @throws IOException */ public Coin moveFundsFromConfirmedToUnConfirmed(int accountId,Coin amount) throws IOException{ Coin beforeConfirmed = getConfirmedBalance(accountId); Coin beforeUnconf = getUnConfirmedBalance(accountId); staticLogger.info("Moving " + amount.toFriendlyString() + " from confirmed(" + beforeConfirmed.toFriendlyString() +") to unconfirmed(" + beforeUnconf.toFriendlyString() + ") balance. Account: " + accountId ); assert(beforeConfirmed.compareTo(amount) >= 0); Coin afterConfirmed = beforeConfirmed.subtract(amount); Coin afterUnconfirmed = beforeUnconf.add(amount); setConfirmedBalance(accountId,afterConfirmed); setUnConfirmedBalance(accountId,afterUnconfirmed); return afterUnconfirmed; } // // Pending Requests Control // public static void addPendingRequest(PendingRequest req) throws FileNotFoundException, IOException{ configFile.writeNewPendingRequest(req); } public static void removePendingRequest(PendingRequest req) throws FileNotFoundException, IOException{ staticLogger.info("Removed pending request: " + req.getRequestID()); configFile.removePendingRequest(req); } public static int getPendingRequestSize(){ try { return getPendingRequests().size(); } catch (FileNotFoundException e) { } catch (IOException e) { } return 0; } public static List<PendingRequest> getPendingRequests() throws FileNotFoundException, IOException{ return configFile.getPendingRequests(); } public String pendingRequestToString(PendingRequest op){ String type = ""; switch(op.getOperationType()){ case Pairing: type = "Pairing"; break; case Unpair: type = "Unpair"; break; case SignAndBroadcastAuthenticatorTx: type = "Sign and broadcast Auth. Tx"; break; case BroadcastNormalTx: type = "Broadcast normal Tx"; break; case updateIpAddressesForPreviousMessage: type = "Update Ip address from previous message"; break; } PairedAuthenticator po = getPairingObject(op.getPairingID()); ATAccount acc = getAccount(po.getWalletAccountIndex()); String pairingName = acc.getAccountName(); return pairingName + ": " + type + " --- " + op.getRequestID(); } // // Pending transactions // /*public List<String> getPendingOutTx(int accountIdx){ return configFile.getPendingOutTx(accountIdx); } public void addPendingOutTx(int accountIdx, String txID) throws FileNotFoundException, IOException{ configFile.addPendingOutTx(accountIdx,txID); } public void removePendingOutTx(int accountIdx, String txID) throws FileNotFoundException, IOException{ configFile.removePendingOutTx(accountIdx,txID); } public boolean isPendingOutTx(int accountIdx, String txID) throws FileNotFoundException, IOException{ List<String> all = getPendingOutTx(accountIdx); for(String tx:all) if(tx.equals(txID)) return true; return false; } public List<String> getPendingInTx(int accountIdx){ return configFile.getPendingInTx(accountIdx); } public void addPendingInTx(int accountIdx, String txID) throws FileNotFoundException, IOException{ configFile.addPendingInTx(accountIdx,txID); } public void removePendingInTx(int accountIdx, String txID) throws FileNotFoundException, IOException{ configFile.removePendingInTx(accountIdx,txID); } public boolean isPendingInTx(int accountIdx, String txID) throws FileNotFoundException, IOException{ List<String> all = getPendingInTx(accountIdx); for(String tx:all) if(tx.equals(txID)) return true; return false; }*/ // // One name // public AuthenticatorConfiguration.ConfigOneNameProfile getOnename(){ try { AuthenticatorConfiguration.ConfigOneNameProfile on = configFile.getOnename(); if(on.getOnename().length() == 0) return null; return on; } catch (IOException e) { e.printStackTrace(); } return null; } public void writeOnename(AuthenticatorConfiguration.ConfigOneNameProfile one) throws FileNotFoundException, IOException{ configFile.writeOnename(one); } // // Active account Control // /** * Surrounded with try & catch because we access it a lot. * * @return */ public AuthenticatorConfiguration.ConfigActiveAccount getActiveAccount() { try { return configFile.getActiveAccount(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * Sets the active account according to account index, returns the active account.<br> * Will return null in case its not successful * @param accountIdx * @return * @throws IOException * @throws FileNotFoundException */ public ATAccount setActiveAccount(int accountIdx){ ATAccount acc = getAccount(accountIdx); AuthenticatorConfiguration.ConfigActiveAccount.Builder b1 = AuthenticatorConfiguration.ConfigActiveAccount.newBuilder(); b1.setActiveAccount(acc); if(acc.getAccountType() == WalletAccountType.AuthenticatorAccount){ PairedAuthenticator p = Authenticator.getWalletOperation().getPairingObjectForAccountIndex(acc.getIndex()); b1.setPairedAuthenticator(p); } try { writeActiveAccount(b1.build()); return acc; } catch (IOException e) { e.printStackTrace(); } return null; } private void writeActiveAccount(AuthenticatorConfiguration.ConfigActiveAccount acc) throws FileNotFoundException, IOException{ configFile.writeActiveAccount(acc); } // // Regular Bitocoin Wallet Operations // public Wallet getTrackedWallet(){ return mWalletWrapper.getTrackedWallet(); } public void setTrackedWallet(Wallet wallet){ if(mWalletWrapper == null) mWalletWrapper = new WalletWrapper(wallet,null); else mWalletWrapper.setTrackedWallet(wallet); mWalletWrapper.addEventListener(new WalletListener()); } public NetworkParameters getNetworkParams() { assert(mWalletWrapper != null); return mWalletWrapper.getNetworkParams(); } public boolean isWatchingAddress(Address address) throws AddressFormatException{ return isWatchingAddress(address.toString()); } public boolean isWatchingAddress(String address) throws AddressFormatException { assert(mWalletWrapper != null); return mWalletWrapper.isAuthenticatorAddressWatched(address); } public boolean isTransactionOutputMine(TransactionOutput out) { assert(mWalletWrapper != null); return mWalletWrapper.isTransactionOutputMine(out); } public void addAddressToWatch(String address) throws AddressFormatException { assert(mWalletWrapper != null); if(!mWalletWrapper.isAuthenticatorAddressWatched(address)){ mWalletWrapper.addAddressToWatch(address); this.LOG.info("Added address to watch: " + address); } } public void connectInputs(List<TransactionInput> inputs) { assert(mWalletWrapper != null); List<TransactionOutput> unspentOutputs = mWalletWrapper.getWatchedOutputs(); for(TransactionOutput out:unspentOutputs) for(TransactionInput in:inputs){ String hashIn = in.getOutpoint().getHash().toString(); String hashOut = out.getParentTransaction().getHash().toString(); if(hashIn.equals(hashOut)){ in.connect(out); break; } } } public void disconnectInputs(List<TransactionInput> inputs){ for(TransactionInput input:inputs) input.disconnect(); } public SendResult sendCoins(Wallet.SendRequest req) throws InsufficientMoneyException { assert(mWalletWrapper != null); this.LOG.info("Sent Tx: " + req.tx.getHashAsString()); return mWalletWrapper.sendCoins(req); } public void addEventListener(WalletEventListener listener) { assert(mWalletWrapper != null); mWalletWrapper.addEventListener(listener); } public ECKey findKeyFromPubHash(byte[] pubkeyHash){ assert(mWalletWrapper != null); return mWalletWrapper.findKeyFromPubHash(pubkeyHash); } public List<Transaction> getRecentTransactions(){ assert(mWalletWrapper != null); return mWalletWrapper.getRecentTransactions(); } public ArrayList<TransactionOutput> selectOutputsFromAccount(int accountIndex, Coin value) throws ScriptException, NoSuchAlgorithmException, AddressWasNotFoundException, JSONException, AddressFormatException, KeyIndexOutOfRangeException{ ArrayList<TransactionOutput> all = getUnspentOutputsForAccount(accountIndex); ArrayList<TransactionOutput> ret = selectOutputs(value, all); return ret; } public ArrayList<TransactionOutput> selectOutputs(Coin value, ArrayList<TransactionOutput> candidates) { LinkedList<TransactionOutput> outs = new LinkedList<TransactionOutput> (candidates); DefaultCoinSelector selector = new DefaultCoinSelector(); CoinSelection cs = selector.select(value, outs); Collection<TransactionOutput> gathered = cs.gathered; ArrayList<TransactionOutput> ret = new ArrayList<TransactionOutput>(gathered); return ret; } public ArrayList<TransactionOutput> getUnspentOutputsForAccount(int accountIndex) throws ScriptException, NoSuchAlgorithmException, AddressWasNotFoundException, JSONException, AddressFormatException, KeyIndexOutOfRangeException{ List<TransactionOutput> all = mWalletWrapper.getWatchedOutputs(); ArrayList<TransactionOutput> ret = new ArrayList<TransactionOutput>(); for(TransactionOutput unspentOut:all){ ATAddress add = findAddressInAccounts(unspentOut.getScriptPubKey().getToAddress(getNetworkParams()).toString()); if(add.getAccountIndex() == accountIndex) ret.add(unspentOut); } return ret; } public ArrayList<TransactionOutput> getUnspentOutputsForAddresses(ArrayList<String> addressArr) { return mWalletWrapper.getUnspentOutputsForAddresses(addressArr); } public Coin getTxValueSentToMe(Transaction tx){ return mWalletWrapper.getTxValueSentToMe(tx); } public Coin getTxValueSentFromMe(Transaction tx){ return mWalletWrapper.getTxValueSentFromMe(tx); } public void decryptWallet(String password){ staticLogger.info("Decrypted wallet with password: " + password); mWalletWrapper.decryptWallet(password); } public void encryptWallet(String password){ staticLogger.info("Encrypted wallet with password: " + password); mWalletWrapper.encryptWallet(password); } public boolean isWalletEncrypted(){ return mWalletWrapper.isWalletEncrypted(); } /** * If pw is not null, will decrypt the wallet, get the seed and encrypt the wallet. * * @param pw * @return */ public byte[] getWalletSeed(@Nullable String pw){ if(isWalletEncrypted() && pw == null) return null; if(isWalletEncrypted()) decryptWallet(pw); byte[] ret = mWalletWrapper.getWalletSeed(); encryptWallet(pw); return ret; } public ArrayList<Transaction> filterTransactionsByAccount (int accountIndex) throws NoSuchAlgorithmException, JSONException, AddressFormatException, KeyIndexOutOfRangeException, AddressNotWatchedByWalletException{ ArrayList<Transaction> filteredHistory = new ArrayList<Transaction>(); ArrayList<String> usedExternalAddressList = getAccountUsedAddressesString(accountIndex, HierarchyAddressTypes.External); //ArrayList<String> usedInternalAddressList = getAccountUsedAddressesString(accountIndex, HierarchyAddressTypes.Internal); Set<Transaction> fullTxSet = mWalletWrapper.trackedWallet.getTransactions(false); for (Transaction tx : fullTxSet){ for (int a=0; a<tx.getInputs().size(); a++){ if (tx.getInput(a).getConnectedOutput()!=null){ String address = tx.getInput(a).getConnectedOutput().getScriptPubKey().getToAddress(Authenticator.getWalletOperation().getNetworkParams()).toString(); for (String addr : usedExternalAddressList){ if (addr.equals(address)){ if (!filteredHistory.contains(tx)){filteredHistory.add(tx);} } } /*for (String addr : usedInternalAddressList){ if (addr.equals(address)){ if (!filteredHistory.contains(tx)){filteredHistory.add(tx);} } }*/ } //We need to do the same thing here for internal addresses } for (int b=0; b<tx.getOutputs().size(); b++){ String address = tx.getOutput(b).getScriptPubKey().getToAddress(Authenticator.getWalletOperation().getNetworkParams()).toString(); for (String addr : usedExternalAddressList){ if (addr.equals(address)){ if (!filteredHistory.contains(tx)){filteredHistory.add(tx);} } } //Same thing here, we need to check internal addresses as well. } } return filteredHistory; } }
package bishakh.psync; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.*; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; /** * The File Transporter module : request a file from a peer node */ public class FileTransporter { Gson gson = new Gson(); public ConcurrentHashMap<Thread, ResumeDownloadThread> ongoingDownloadThreads = new ConcurrentHashMap<Thread, ResumeDownloadThread>(); Type ConcurrentHashMapType = new TypeToken<ConcurrentHashMap<String, FileEntry>>(){}.getType(); String syncDirectory; Logger logger; public FileTransporter(String syncDirectory, Logger LoggerObj){ this.syncDirectory = syncDirectory; this.logger = LoggerObj; } public void downloadFile(String fileID, String fileName, String filePath, String peerIP, String peerID, long startByte, long endByte, double fileSize) throws MalformedURLException { File f = new File(syncDirectory + "/" + filePath); File parent = f.getParentFile(); if(!parent.exists() && !parent.mkdirs()){ throw new IllegalStateException("Couldn't create dir: " + parent); } URL fileUrl = new URL("http://"+ peerIP +":8080/getFile/" + fileID); ResumeDownloadThread resumeDownloadThread = new ResumeDownloadThread(fileUrl , fileID, fileName, f, startByte, endByte, fileSize, peerID); Thread t = new Thread(resumeDownloadThread); ongoingDownloadThreads.put(t, resumeDownloadThread); logger.d("DEBUG:", "MISSING FILE DOWNLOAD START START BYTE = " + startByte + " END BYTE = " + endByte); t.start(); } public class ResumeDownloadThread implements Runnable { URL url; File outputFile; long startByte, endByte; final int BUFFER_SIZE = 10240; public String fileID; public String fileName; boolean mIsFinished = false; boolean DOWNLOADING = true; boolean mState = true; long presentByte; public boolean isRunning = false; double filesize; String peerId; public ResumeDownloadThread(URL url, String fileID, String filename, File outputFile, long startByte, long endByte, double fileSize, String peerID){ this.url = url; this.outputFile = outputFile; this.startByte = startByte; this.endByte = endByte; this.isRunning = false; this.presentByte = startByte; this.fileID = fileID; this.filesize = fileSize; this.peerId = peerID; this.fileName = filename; } @Override public void run() { this.isRunning = true; BufferedInputStream in = null; RandomAccessFile raf = null; int response = 0; try { String byteRange; isRunning = true; // open Http connection to URL HttpURLConnection connection = (HttpURLConnection)url.openConnection(); logger.d("DEBUG:FILE TRANSPORTER", "URl is" + url); // set the range of byte to download if(endByte < 0) { byteRange = startByte + "-" /*+ endByte*/; } else { if(endByte < startByte){ throw new IllegalArgumentException(); } byteRange = startByte + "-" + endByte; } connection.setRequestProperty("Range", "bytes=" + byteRange); connection.setRequestMethod("GET"); connection.setConnectTimeout( 5*1000); connection.setReadTimeout(5*1000); logger.d("DEBUG:FILE TRANSPORTER", "Connection created" + byteRange); // connect to server connection.connect(); logger.d("DEBUG:FILE TRANSPORTER", "Callled connect with timeout " + connection.getConnectTimeout()); logger.d("DEBUG:FILE TRANSPORTER", ""+connection.getResponseCode()); // Make sure the response code is in the 200 range. if (connection.getResponseCode() / 100 != 2) { logger.d("DEBUG:FILE TRANSPORTER", "error : Response code out of 200 range"); } else { response = 200; logger.d("DEBUG:FILE TRANSPORTER", "Response code : " + connection.getResponseCode()); // get the input stream in = new BufferedInputStream(connection.getInputStream()); // open the output file and seek to the start location raf = new RandomAccessFile(outputFile, "rw"); raf.seek(startByte); logger.write("START_FILE_DOWNLOAD, " + fileID + ", " + fileName + ", " + startByte + ", " + this.filesize + ", " + this.peerId); byte data[] = new byte[BUFFER_SIZE]; int numBytesRead; while (/*(mState == DOWNLOADING) &&*/ ((numBytesRead = in.read(data, 0, BUFFER_SIZE)) != -1)) { // write to buffer raf.write(data, 0, numBytesRead); this.presentByte = this.presentByte + numBytesRead; // increase the startByte for resume later startByte += numBytesRead; // increase the downloaded size //Log.d("DEBUG:FILE TRANSPORTER", "Fetching data " + startByte); } if (mState == DOWNLOADING) { mIsFinished = true; } } } catch (Exception e) { e.printStackTrace(); logger.d("DEBUG:FILE TRANSPORTER", "Connection not established" + e); } finally { isRunning = false; if (raf != null) { try { raf.close(); } catch (IOException e) {} } if (in != null) { try { in.close(); } catch (IOException e) {} } if(response == 200) { logger.write("STOP_FILE_DOWNLOAD, " + fileID + ", " + fileName + ", " + this.presentByte + ", " + this.filesize + ", " + this.peerId); } this.isRunning = false; } } public long getPresentByte(){ return this.presentByte; } } /** * Thread to fetch the list of files from a peer */ class ListFetcher implements Runnable { URL url; String peerAddress; final int BUFFER_SIZE = 10240; Controller controller; boolean mIsFinished = false; boolean DOWNLOADING = true; boolean mState = true; public ListFetcher(Controller controller, URL url, String peerAddress){ this.url = url; this.peerAddress = peerAddress; this.controller = controller; } @Override public void run() { BufferedInputStream in = null; try { // open Http connection to URL HttpURLConnection connection = (HttpURLConnection)url.openConnection(); logger.d("DEBUG:FILE TRANSPORTER", "URl is" + url); // set the range of byte to download String byteRange = "0-"; //conn.setRequestProperty("Range", "bytes=" + byteRange); connection.setRequestMethod("GET"); connection.setConnectTimeout(5 * 1000); connection.setReadTimeout(5 * 1000); logger.d("DEBUG:FILE TRANSPORTER", "Connection created" + byteRange); // connect to server connection.connect(); logger.d("DEBUG:FILE TRANSPORTER", "Callled connect with timeout " + connection.getConnectTimeout()); logger.d("DEBUG:FILE TRANSPORTER", "" + connection.getResponseCode()); // Make sure the response code is in the 200 range. if (connection.getResponseCode() / 100 != 2) { logger.d("DEBUG:FILE TRANSPORTER", "error : Response code out of 200 range"); } logger.d("DEBUG:FILE TRANSPORTER", "Response code : " + connection.getResponseCode()); // get the input stream in = new BufferedInputStream(connection.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); FileTable fileTable; fileTable = (FileTable) gson.fromJson(br, FileTable.class); controller.peerFilesFetched(peerAddress, fileTable); logger.write("SUMMARY_VECTOR_RECEIVED, " + connection.getContentLength()); //Log.d("DEBUG:FILE TRANSPORTER", "List Json: " + gson.toJson(fileTableHashMap).toString()); } catch (Exception e) { e.printStackTrace(); logger.d("DEBUG:FILE TRANSPORTER", "Connection not established" + e); } finally { if (in != null) { try { in.close(); } catch (IOException e) {} } } } } }
package br.eti.rslemos.bitsmagic; import static br.eti.rslemos.bitsmagic.IntRef.byRef; import static br.eti.rslemos.bitsmagic.Store.BYTE_ADDRESS_LINES; import static br.eti.rslemos.bitsmagic.Store.BYTE_ADDRESS_MASK; import static br.eti.rslemos.bitsmagic.Store.BYTE_DATA_LINES; import static br.eti.rslemos.bitsmagic.Store.BYTE_DATA_MASK; import static br.eti.rslemos.bitsmagic.Store.CHAR_ADDRESS_LINES; import static br.eti.rslemos.bitsmagic.Store.CHAR_ADDRESS_MASK; import static br.eti.rslemos.bitsmagic.Store.CHAR_DATA_LINES; import static br.eti.rslemos.bitsmagic.Store.CHAR_DATA_MASK; import static br.eti.rslemos.bitsmagic.Store.INT_ADDRESS_LINES; import static br.eti.rslemos.bitsmagic.Store.INT_ADDRESS_MASK; import static br.eti.rslemos.bitsmagic.Store.INT_DATA_LINES; import static br.eti.rslemos.bitsmagic.Store.INT_DATA_MASK; import static br.eti.rslemos.bitsmagic.Store.LONG_ADDRESS_LINES; import static br.eti.rslemos.bitsmagic.Store.LONG_ADDRESS_MASK; import static br.eti.rslemos.bitsmagic.Store.LONG_DATA_LINES; import static br.eti.rslemos.bitsmagic.Store.LONG_DATA_MASK; import static br.eti.rslemos.bitsmagic.Store.SHORT_ADDRESS_LINES; import static br.eti.rslemos.bitsmagic.Store.SHORT_ADDRESS_MASK; import static br.eti.rslemos.bitsmagic.Store.SHORT_DATA_LINES; import static br.eti.rslemos.bitsmagic.Store.SHORT_DATA_MASK; /** * This class consists exclusively of static methods that copy bits over arrays * of integral primitive type. * * <p>For every method available in this class, the arguments that represent * offsets should always be given in bits, and are 0-based. For more * information about bit mapping in arrays of integral primitive types see * {@link Store} class. * </p> * <p>The general syntax for methods in this class conforms to that of * {@link System#arraycopy}. * </p> * <p>For {@link #copyFrom} methods, touching any offlimits bits throws * {@code ArrayIndexOutOfBoundsException}, destination being left unchanged. * </p> * <p>For {@link #safeCopyFrom} methods, offlimits bits are hardwired to 0: * they always read as 0, and any value written to them is discarded. Those * methods should never throw {@code ArrayIndexOutOfBoundsException}. * </p> * <p>In case of using the same underlying storage for both source and * destination, all methods of this class behave as if copying the bits first * to a temporary location, then writing them to the destination. * </p> * <p>{@code NullPointerException} is thrown if either given array is * {@code null}. * </p> * <p>All methods are inherently thread unsafe: in case of more than one thread * acting upon the same storage the results are undefined. Also neither they * acquire nor block on any monitor. Any necessary synchronization should be * done externally. * </p> * * @author Rodrigo Lemos * @since 1.0.0 */ public class Copy { private Copy() { /* non-instantiable */ } private static boolean checkSafeIndices(int srcPos, int destPos, int length, int maxSrc, int maxDest) { if (srcPos < 0 || srcPos > maxSrc) throw new ArrayIndexOutOfBoundsException(srcPos); if (destPos < 0 || destPos > maxDest) throw new ArrayIndexOutOfBoundsException(destPos); if (srcPos + length < 0 || srcPos + length > maxSrc) throw new ArrayIndexOutOfBoundsException(srcPos + length); if (destPos + length < 0 || destPos + length > maxDest) throw new ArrayIndexOutOfBoundsException(destPos + length); if (length < 0) throw new IllegalArgumentException(); return length > 0; } private static boolean prepareSafeCopy(IntRef srcPos, IntRef destPos, IntRef length, IntRef fillLow, IntRef fillHigh, final int maxDest, final int maxSource) { if (length.i == 0) return false; if (length.i < 0) throw new IllegalArgumentException(); if (!(destPos.i < maxDest && destPos.i + length.i > 0)) return false; // fix destination starting point out of range if (destPos.i < 0) { length.i -= -destPos.i; srcPos.i += -destPos.i; destPos.i += -destPos.i; } // fix destination ending point out of range if (destPos.i + length.i > maxDest) { length.i -= (destPos.i + length.i) - maxDest; } if (!(srcPos.i < maxSource && srcPos.i + length.i > 0)) { fillHigh.i = length.i; length.i = 0; srcPos.i = 0; return true; } // fix source starting point out of range if (srcPos.i < 0) { fillLow.i = -srcPos.i; length.i -= -srcPos.i; destPos.i += -srcPos.i; srcPos.i += -srcPos.i; } // fix source ending point out of range if (srcPos.i + length.i > maxSource) { fillHigh.i = (srcPos.i + length.i) - maxSource; length.i -= (srcPos.i + length.i) - maxSource; } return true; } /** * Copies bits from the specified source storage, beginning at the * specified bit, to the specified bits of the destination storage. A * region of bits is copied from the source storage referenced by * {@code source} to the destination storage referenced by {@code dest}. * The number of bits copied is equal to the {@code length} argument. The * bits at offsets {@code srcPos} through {@code srcPos+length-1} in the * source storage are copied into positions {@code destPos} through * {@code destPos+length-1}, respectively, of the destination storage. * * <p>Offlimits bits are read as 0, and discarded when written to. * </p> * * @param source the source storage. * @param srcPos starting bit in the source storage. * @param dest the destination storage. * @param destPos starting bit in the destination storage. * @param length the number of bits to be copied. * * @since 1.0.0 */ public static void safeCopyFrom(byte[] source, int srcPos, byte[] dest, int destPos, int length) { safeCopyFrom0(source, byRef(srcPos), dest, byRef(destPos), byRef(length)); } private static void safeCopyFrom0(byte[] source, IntRef srcPos, byte[] dest, IntRef destPos, IntRef length) { IntRef fillLow = byRef(0); IntRef fillHigh = byRef(0); if (!prepareSafeCopy(srcPos, destPos, length, fillLow, fillHigh, dest.length << BYTE_ADDRESS_LINES, source.length << BYTE_ADDRESS_LINES)) return; copyFrom(source, srcPos.i, dest, destPos.i, length.i); Store.fill(dest, destPos.i + length.i, destPos.i + length.i + fillHigh.i, false); Store.fill(dest, destPos.i - fillLow.i, destPos.i, false); } /** * Copies bits from the specified source storage, beginning at the * specified bit, to the specified bits of the destination storage. A * region of bits is copied from the source storage referenced by * {@code source} to the destination storage referenced by {@code dest}. * The number of bits copied is equal to the {@code length} argument. The * bits at offsets {@code srcPos} through {@code srcPos+length-1} in the * source storage are copied into positions {@code destPos} through * {@code destPos+length-1}, respectively, of the destination storage. * * @param source the source storage. * @param srcPos starting bit in the source storage. * @param dest the destination storage. * @param destPos starting bit in the destination storage. * @param length the number of bits to be copied. * * @since 1.0.0 */ public static void copyFrom(byte[] source, int srcPos, byte[] dest, int destPos, int length) { if (!checkSafeIndices(srcPos, destPos, length, source.length << BYTE_ADDRESS_LINES, dest.length << BYTE_ADDRESS_LINES)) return; int[] sIndex = {srcPos >> BYTE_ADDRESS_LINES, (srcPos + length) >> BYTE_ADDRESS_LINES}; int[] sOffset = {srcPos & BYTE_ADDRESS_MASK, (srcPos + length) & BYTE_ADDRESS_MASK }; int[] dIndex = {destPos >> BYTE_ADDRESS_LINES, (destPos + length) >> BYTE_ADDRESS_LINES}; int[] dOffset = {destPos & BYTE_ADDRESS_MASK, (destPos + length) & BYTE_ADDRESS_MASK }; if (sOffset[0] == dOffset[0]) // FAST PATH: handle both ends specially, copy middle unchanged copyParallelFrom0(source, dest, sIndex, dIndex, dOffset); else if (sOffset[0] < dOffset[0]) copyHigherFrom0(source, dest, sIndex, sOffset, dIndex, dOffset); else /* if (sOffset[0] > dOffset[0]) */ copyLowerFrom0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyParallelFrom0(byte[] source, byte[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { if (dIndex[1] == dIndex[0]) { // special case: subword copy within word and neither offset is zero final int LOWEST_BITS_FROM = ~(BYTE_DATA_MASK << dOffset[0]); final int HIGHEST_BITS_TO = BYTE_DATA_MASK << dOffset[1]; byte save = (byte) (source[sIndex[0]] & ~(LOWEST_BITS_FROM | HIGHEST_BITS_TO)); dest[dIndex[0]] &= LOWEST_BITS_FROM | HIGHEST_BITS_TO; dest[dIndex[0]] |= save; return; } if (dIndex[0] < sIndex[0]) copyParallelFromForwards0(source, dest, sIndex, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyParallelFromForwards0(source, dest, sIndex, dIndex, dOffset); else copyParallelFromBackwards0(source, dest, sIndex, dIndex, dOffset); } private static void copyParallelFromForwards0(byte[] source, byte[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them byte save; if (dOffset[0] != 0) { // handle "from" end specially final int HIGHEST_BITS = BYTE_DATA_MASK << dOffset[0]; final int LOWEST_BITS = ~HIGHEST_BITS; save = (byte) (source[sIndex[0]] & HIGHEST_BITS); dest[dIndex[0]] &= LOWEST_BITS; dest[dIndex[0]] |= save; // first index already taken care of sIndex[0]++; dIndex[0]++; } if (dIndex[1] > dIndex[0]) // main bulk copy (FASTEST PATH if no end should be handled specially) System.arraycopy(source, sIndex[0], dest, dIndex[0], dIndex[1]-dIndex[0]); if (dOffset[1] != 0) { // handle "to" end specially final int HIGHEST_BITS = BYTE_DATA_MASK << dOffset[1]; final int LOWEST_BITS = ~HIGHEST_BITS; save = (byte) (source[sIndex[1]] & LOWEST_BITS); dest[dIndex[1]] &= HIGHEST_BITS; dest[dIndex[1]] |= save; } } private static void copyParallelFromBackwards0(byte[] source, byte[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them byte save; if (dOffset[1] != 0) { // handle "to" end specially final int HIGHEST_BITS = BYTE_DATA_MASK << dOffset[1]; final int LOWEST_BITS = ~HIGHEST_BITS; save = (byte) (source[sIndex[1]] & LOWEST_BITS); dest[dIndex[1]] &= HIGHEST_BITS; dest[dIndex[1]] |= save; } if (dOffset[0] != 0) { // don't copy the first index if partial dIndex[0]++; sIndex[0]++; } if (dIndex[1] > dIndex[0]) // main bulk copy (FASTEST PATH if no end should be handled specially) System.arraycopy(source, sIndex[0], dest, dIndex[0], dIndex[1]-dIndex[0]); if (dOffset[0] != 0) { // handle "from" end specially dIndex[0] sIndex[0] final int HIGHEST_BITS = BYTE_DATA_MASK << dOffset[0]; final int LOWEST_BITS = ~HIGHEST_BITS; save = (byte) (source[sIndex[0]] & HIGHEST_BITS); dest[dIndex[0]] &= LOWEST_BITS; dest[dIndex[0]] |= save; } } private static void copyHigherFrom0(byte[] source, byte[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { if (dIndex[0] == dIndex[1]) { int d = dIndex[0]; int s = sIndex[0]; // At this point dIndex[0] == dIndex[1] AND sOffset[0] < dOffset[0]. // This implies that sIndex[0] == sIndex[1] (so there is no need to copy more than 1 chunk). // I have discovered a truly marvelous proof of this, which this media is too clumsy to contain. byte save = (byte) ((source[s] << dOffset[0] - sOffset[0]) & ~(BYTE_DATA_MASK << dOffset[1]) & BYTE_DATA_MASK << dOffset[0]); dest[d] &= BYTE_DATA_MASK << dOffset[1] | ~(BYTE_DATA_MASK << dOffset[0]); dest[d] |= save; return; } if (dIndex[0] < sIndex[0]) copyHigherFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyHigherFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else copyHigherFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyHigherFromForwards0(byte[] source, byte[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them byte save; int d = dIndex[0]; int s = sIndex[0]; save = (byte) ((source[s] & BYTE_DATA_MASK) >>> sOffset[0] << dOffset[0]); dest[d] &= ~(BYTE_DATA_MASK << dOffset[0]); dest[d] |= save; while(++d < dIndex[1]) { save = (byte) ((source[s] & BYTE_DATA_MASK) >>> BYTE_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= ~(BYTE_DATA_MASK >>> BYTE_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; ++s; save = (byte) (source[s] << dOffset[0] - sOffset[0]); dest[d] &= BYTE_DATA_MASK >>> BYTE_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] |= save; } if (dOffset[1] > 0) { if (dOffset[1] < sOffset[1]) { // implies s == sIndex[1] [proof needed] save = (byte) ((source[s] & BYTE_DATA_MASK & ~(BYTE_DATA_MASK << sOffset[1])) >>> BYTE_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= BYTE_DATA_MASK << dOffset[1]; dest[d] |= save; } else /* dOffset[1] > sOffset[1] */ { save = (byte) ((source[s] & BYTE_DATA_MASK) >>> BYTE_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= ~(BYTE_DATA_MASK >>> BYTE_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; if (sOffset[1] > 0) { s++; save = (byte) ((source[s] & BYTE_DATA_MASK & ~(BYTE_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]); dest[d] &= BYTE_DATA_MASK << dOffset[1] | BYTE_DATA_MASK >>> BYTE_DATA_LINES - (dOffset[1] - sOffset[1]); dest[d] |= save; } } } } private static void copyHigherFromBackwards0(byte[] source, byte[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them byte save; int d = dIndex[1]; int s = sIndex[1]; if (dOffset[1] > 0) { if (dOffset[1] < sOffset[1]) { save = (byte) ((source[s] & BYTE_DATA_MASK & ~(BYTE_DATA_MASK << sOffset[1])) >>> BYTE_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= BYTE_DATA_MASK << dOffset[1]; dest[d] |= save; } else /* dOffset[1] > sOffset[1] */ { if (sOffset[1] > 0) { save = (byte) ((source[s] & BYTE_DATA_MASK & ~(BYTE_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]); dest[d] &= BYTE_DATA_MASK << dOffset[1] | BYTE_DATA_MASK >>> BYTE_DATA_LINES - (dOffset[1] - sOffset[1]); dest[d] |= save; } s save = (byte) ((source[s] & BYTE_DATA_MASK) >>> BYTE_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= ~(BYTE_DATA_MASK >>> BYTE_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; } } while(--d > dIndex[0]) { save = (byte) (source[s] << dOffset[0] - sOffset[0]); dest[d] &= BYTE_DATA_MASK >>> BYTE_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] |= save; --s; save = (byte) ((source[s] & BYTE_DATA_MASK) >>> BYTE_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= ~(BYTE_DATA_MASK >>> BYTE_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; } save = (byte) ((source[s] & BYTE_DATA_MASK) >>> sOffset[0] << dOffset[0]); dest[d] &= ~(BYTE_DATA_MASK << dOffset[0]); dest[d] |= save; } private static void copyLowerFrom0(byte[] source, byte[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { if (sIndex[0] == sIndex[1]) { int d = dIndex[0]; int s = sIndex[0]; // At this point sIndex[0] == sIndex[1] AND sOffset[0] > dOffset[0]. // This implies that dIndex[0] == dIndex[1] (so there is no need to copy more than 1 chunk). // I have discovered a truly marvelous proof of this, which this media is too clumsy to contain. byte save = (byte) ((source[s] & BYTE_DATA_MASK) >>> (sOffset[0] - dOffset[0]) & ~(BYTE_DATA_MASK << dOffset[1]) & BYTE_DATA_MASK << dOffset[0]); dest[d] &= BYTE_DATA_MASK << dOffset[1] | ~(BYTE_DATA_MASK << dOffset[0]); dest[d] |= save; return; } if (dIndex[0] < sIndex[0]) copyLowerFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyLowerFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else copyLowerFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyLowerFromForwards0(byte[] source, byte[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them byte save; int d = dIndex[0]; int s = sIndex[0]; save = (byte) ((source[s] & BYTE_DATA_MASK) >>> sOffset[0] << dOffset[0]); dest[d] &= ~((BYTE_DATA_MASK >>> sOffset[0]) << dOffset[0]); dest[d] |= save; while(++s < sIndex[1]) { save = (byte) (source[s] << BYTE_DATA_LINES - (sOffset[0] - dOffset[0])); dest[d] &= BYTE_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; ++d; save = (byte) ((source[s] & BYTE_DATA_MASK) >>> sOffset[0] - dOffset[0]); dest[d] &= ~(BYTE_DATA_MASK >>> sOffset[0] - dOffset[0]); dest[d] |= save; } if (sOffset[1] > 0) { if (dOffset[1] > sOffset[1]) { // implies d == dIndex[1] [proof needed] save = (byte) ((source[s] & ~(BYTE_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]); dest[d] &= ~(~(BYTE_DATA_MASK << sOffset[1]) << dOffset[1] - sOffset[1]); dest[d] |= save; } else /* dOffset[1] < sOffset[1] */ { save = (byte) (source[s] << BYTE_DATA_LINES - (sOffset[0] - dOffset[0])); dest[d] &= BYTE_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; if (dOffset[1] > 0) { d++; save = (byte) ((source[s] & ~(BYTE_DATA_MASK << sOffset[1])) >>> sOffset[0] - dOffset[0]); dest[d] &= ~(~(BYTE_DATA_MASK << sOffset[1]) >>> sOffset[0] - dOffset[0]); dest[d] |= save; } } } } private static void copyLowerFromBackwards0(byte[] source, byte[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them byte save; int d = dIndex[1]; int s = sIndex[1]; if (sOffset[1] > 0) { if (dOffset[1] > sOffset[1]) { save = (byte) ((source[s] & ~(BYTE_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]); dest[d] &= ~(~(BYTE_DATA_MASK << sOffset[1]) << dOffset[1] - sOffset[1]); dest[d] |= save; } else /* dOffset[1] < sOffset[1] */ { if (dOffset[1] > 0) { save = (byte) ((source[s] & ~(BYTE_DATA_MASK << sOffset[1])) >>> sOffset[0] - dOffset[0]); dest[d] &= ~(~(BYTE_DATA_MASK << sOffset[1]) >>> sOffset[0] - dOffset[0]); dest[d] |= save; } d save = (byte) (source[s] << BYTE_DATA_LINES - (sOffset[0] - dOffset[0])); dest[d] &= BYTE_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; } } while(--s > sIndex[0]) { save = (byte) ((source[s] & BYTE_DATA_MASK) >>> sOffset[0] - dOffset[0]); dest[d] &= ~(BYTE_DATA_MASK >>> sOffset[0] - dOffset[0]); dest[d] |= save; --d; save = (byte) (source[s] << BYTE_DATA_LINES - (sOffset[0] - dOffset[0])); dest[d] &= BYTE_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; } save = (byte) ((source[s] & BYTE_DATA_MASK) >>> sOffset[0] << dOffset[0]); dest[d] &= ~((BYTE_DATA_MASK >>> sOffset[0]) << dOffset[0]); dest[d] |= save; } /** * Copies bits from the specified source storage, beginning at the * specified bit, to the specified bits of the destination storage. A * region of bits is copied from the source storage referenced by * {@code source} to the destination storage referenced by {@code dest}. * The number of bits copied is equal to the {@code length} argument. The * bits at offsets {@code srcPos} through {@code srcPos+length-1} in the * source storage are copied into positions {@code destPos} through * {@code destPos+length-1}, respectively, of the destination storage. * * <p>Offlimits bits are read as 0, and discarded when written to. * </p> * * @param source the source storage. * @param srcPos starting bit in the source storage. * @param dest the destination storage. * @param destPos starting bit in the destination storage. * @param length the number of bits to be copied. * * @since 1.0.0 */ public static void safeCopyFrom(char[] source, int srcPos, char[] dest, int destPos, int length) { safeCopyFrom0(source, byRef(srcPos), dest, byRef(destPos), byRef(length)); } private static void safeCopyFrom0(char[] source, IntRef srcPos, char[] dest, IntRef destPos, IntRef length) { IntRef fillLow = byRef(0); IntRef fillHigh = byRef(0); if (!prepareSafeCopy(srcPos, destPos, length, fillLow, fillHigh, dest.length << CHAR_ADDRESS_LINES, source.length << CHAR_ADDRESS_LINES)) return; copyFrom(source, srcPos.i, dest, destPos.i, length.i); Store.fill(dest, destPos.i + length.i, destPos.i + length.i + fillHigh.i, false); Store.fill(dest, destPos.i - fillLow.i, destPos.i, false); } /** * Copies bits from the specified source storage, beginning at the * specified bit, to the specified bits of the destination storage. A * region of bits is copied from the source storage referenced by * {@code source} to the destination storage referenced by {@code dest}. * The number of bits copied is equal to the {@code length} argument. The * bits at offsets {@code srcPos} through {@code srcPos+length-1} in the * source storage are copied into positions {@code destPos} through * {@code destPos+length-1}, respectively, of the destination storage. * * @param source the source storage. * @param srcPos starting bit in the source storage. * @param dest the destination storage. * @param destPos starting bit in the destination storage. * @param length the number of bits to be copied. * * @since 1.0.0 */ public static void copyFrom(char[] source, int srcPos, char[] dest, int destPos, int length) { if (!checkSafeIndices(srcPos, destPos, length, source.length << CHAR_ADDRESS_LINES, dest.length << CHAR_ADDRESS_LINES)) return; int[] sIndex = {srcPos >> CHAR_ADDRESS_LINES, (srcPos + length) >> CHAR_ADDRESS_LINES}; int[] sOffset = {srcPos & CHAR_ADDRESS_MASK, (srcPos + length) & CHAR_ADDRESS_MASK }; int[] dIndex = {destPos >> CHAR_ADDRESS_LINES, (destPos + length) >> CHAR_ADDRESS_LINES}; int[] dOffset = {destPos & CHAR_ADDRESS_MASK, (destPos + length) & CHAR_ADDRESS_MASK }; if (sOffset[0] == dOffset[0]) // FAST PATH: handle both ends specially, copy middle unchanged copyParallelFrom0(source, dest, sIndex, dIndex, dOffset); else if (sOffset[0] < dOffset[0]) copyHigherFrom0(source, dest, sIndex, sOffset, dIndex, dOffset); else /* if (sOffset[0] > dOffset[0]) */ copyLowerFrom0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyParallelFrom0(char[] source, char[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { if (dIndex[1] == dIndex[0]) { // special case: subword copy within word and neither offset is zero final int LOWEST_BITS_FROM = ~(CHAR_DATA_MASK << dOffset[0]); final int HIGHEST_BITS_TO = CHAR_DATA_MASK << dOffset[1]; char save = (char) (source[sIndex[0]] & ~(LOWEST_BITS_FROM | HIGHEST_BITS_TO)); dest[dIndex[0]] &= LOWEST_BITS_FROM | HIGHEST_BITS_TO; dest[dIndex[0]] |= save; return; } if (dIndex[0] < sIndex[0]) copyParallelFromForwards0(source, dest, sIndex, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyParallelFromForwards0(source, dest, sIndex, dIndex, dOffset); else copyParallelFromBackwards0(source, dest, sIndex, dIndex, dOffset); } private static void copyParallelFromForwards0(char[] source, char[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them char save; if (dOffset[0] != 0) { // handle "from" end specially final int HIGHEST_BITS = CHAR_DATA_MASK << dOffset[0]; final int LOWEST_BITS = ~HIGHEST_BITS; save = (char) (source[sIndex[0]] & HIGHEST_BITS); dest[dIndex[0]] &= LOWEST_BITS; dest[dIndex[0]] |= save; // first index already taken care of sIndex[0]++; dIndex[0]++; } if (dIndex[1] > dIndex[0]) // main bulk copy (FASTEST PATH if no end should be handled specially) System.arraycopy(source, sIndex[0], dest, dIndex[0], dIndex[1]-dIndex[0]); if (dOffset[1] != 0) { // handle "to" end specially final int HIGHEST_BITS = CHAR_DATA_MASK << dOffset[1]; final int LOWEST_BITS = ~HIGHEST_BITS; save = (char) (source[sIndex[1]] & LOWEST_BITS); dest[dIndex[1]] &= HIGHEST_BITS; dest[dIndex[1]] |= save; } } private static void copyParallelFromBackwards0(char[] source, char[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them char save; if (dOffset[1] != 0) { // handle "to" end specially final int HIGHEST_BITS = CHAR_DATA_MASK << dOffset[1]; final int LOWEST_BITS = ~HIGHEST_BITS; save = (char) (source[sIndex[1]] & LOWEST_BITS); dest[dIndex[1]] &= HIGHEST_BITS; dest[dIndex[1]] |= save; } if (dOffset[0] != 0) { // don't copy the first index if partial dIndex[0]++; sIndex[0]++; } if (dIndex[1] > dIndex[0]) // main bulk copy (FASTEST PATH if no end should be handled specially) System.arraycopy(source, sIndex[0], dest, dIndex[0], dIndex[1]-dIndex[0]); if (dOffset[0] != 0) { // handle "from" end specially sIndex[0] dIndex[0] final int HIGHEST_BITS = CHAR_DATA_MASK << dOffset[0]; final int LOWEST_BITS = ~HIGHEST_BITS; save = (char) (source[sIndex[0]] & HIGHEST_BITS); dest[dIndex[0]] &= LOWEST_BITS; dest[dIndex[0]] |= save; } } private static void copyHigherFrom0(char[] source, char[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { if (dIndex[0] == dIndex[1]) { int d = dIndex[0]; int s = sIndex[0]; // At this point dIndex[0] == dIndex[1] AND sOffset[0] < dOffset[0]. // This implies that sIndex[0] == sIndex[1] (so there is no need to copy more than 1 chunk). // I have discovered a truly marvelous proof of this, which this media is too clumsy to contain. char save = (char) ((source[s] << dOffset[0] - sOffset[0]) & ~(CHAR_DATA_MASK << dOffset[1]) & CHAR_DATA_MASK << dOffset[0]); dest[d] &= CHAR_DATA_MASK << dOffset[1] | ~(CHAR_DATA_MASK << dOffset[0]); dest[d] |= save; return; } if (dIndex[0] < sIndex[0]) copyHigherFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyHigherFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else copyHigherFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyHigherFromForwards0(char[] source, char[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them char save; int d = dIndex[0]; int s = sIndex[0]; save = (char) (source[s] >>> sOffset[0] << dOffset[0]); dest[d] &= ~(CHAR_DATA_MASK << dOffset[0]); dest[d] |= save; while(++d < dIndex[1]) { save = (char) (source[s] >>> CHAR_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= ~(CHAR_DATA_MASK >>> CHAR_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; ++s; save = (char) (source[s] << dOffset[0] - sOffset[0]); dest[d] &= CHAR_DATA_MASK >>> CHAR_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] |= save; } if (dOffset[1] > 0) { if (dOffset[1] < sOffset[1]) { // implies s == sIndex[1] [proof needed] save = (char) ((source[s] & ~(CHAR_DATA_MASK << sOffset[1])) >>> CHAR_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= CHAR_DATA_MASK << dOffset[1]; dest[d] |= save; } else /* dOffset[1] > sOffset[1] */ { save = (char) (source[s] >>> CHAR_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= ~(CHAR_DATA_MASK >>> CHAR_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; if (sOffset[1] > 0) { s++; save = (char) ((source[s] & ~(CHAR_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]); dest[d] &= CHAR_DATA_MASK << dOffset[1] | CHAR_DATA_MASK >>> CHAR_DATA_LINES - (dOffset[1] - sOffset[1]); dest[d] |= save; } } } } private static void copyHigherFromBackwards0(char[] source, char[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them char save; int d = dIndex[1]; int s = sIndex[1]; if (dOffset[1] > 0) { if (dOffset[1] < sOffset[1]) { save = (char) ((source[s] & ~(CHAR_DATA_MASK << sOffset[1])) >>> CHAR_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= CHAR_DATA_MASK << dOffset[1]; dest[d] |= save; } else /* dOffset[1] > sOffset[1] */ { if (sOffset[1] > 0) { save = (char) ((source[s] & ~(CHAR_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]); dest[d] &= CHAR_DATA_MASK << dOffset[1] | CHAR_DATA_MASK >>> CHAR_DATA_LINES - (dOffset[1] - sOffset[1]); dest[d] |= save; } s save = (char) (source[s] >>> CHAR_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= ~(CHAR_DATA_MASK >>> CHAR_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; } } while(--d > dIndex[0]) { save = (char) (source[s] << dOffset[0] - sOffset[0]); dest[d] &= CHAR_DATA_MASK >>> CHAR_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] |= save; --s; save = (char) (source[s] >>> CHAR_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= ~(CHAR_DATA_MASK >>> CHAR_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; } save = (char) (source[s] >>> sOffset[0] << dOffset[0]); dest[d] &= ~(CHAR_DATA_MASK << dOffset[0]); dest[d] |= save; } private static void copyLowerFrom0(char[] source, char[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { if (sIndex[0] == sIndex[1]) { int d = dIndex[0]; int s = sIndex[0]; // At this point sIndex[0] == sIndex[1] AND sOffset[0] > dOffset[0]. // This implies that dIndex[0] == dIndex[1] (so there is no need to copy more than 1 chunk). // I have discovered a truly marvelous proof of this, which this media is too clumsy to contain. char save = (char) (source[s] >>> (sOffset[0] - dOffset[0]) & ~(CHAR_DATA_MASK << dOffset[1]) & CHAR_DATA_MASK << dOffset[0]); dest[d] &= CHAR_DATA_MASK << dOffset[1] | ~(CHAR_DATA_MASK << dOffset[0]); dest[d] |= save; return; } if (dIndex[0] < sIndex[0]) copyLowerFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyLowerFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else copyLowerFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyLowerFromForwards0(char[] source, char[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them char save; int d = dIndex[0]; int s = sIndex[0]; save = (char) (source[s] >>> sOffset[0] << dOffset[0]); dest[d] &= ~((CHAR_DATA_MASK >>> sOffset[0]) << dOffset[0]); dest[d] |= save; while(++s < sIndex[1]) { save = (char) (source[s] << CHAR_DATA_LINES - (sOffset[0] - dOffset[0])); dest[d] &= CHAR_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; ++d; save = (char) (source[s] >>> sOffset[0] - dOffset[0]); dest[d] &= ~(CHAR_DATA_MASK >>> sOffset[0] - dOffset[0]); dest[d] |= save; } if (sOffset[1] > 0) { if (dOffset[1] > sOffset[1]) { // implies d == dIndex[1] [proof needed] save = (char) ((source[s] & ~(CHAR_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]); dest[d] &= ~(~(CHAR_DATA_MASK << sOffset[1]) << dOffset[1] - sOffset[1]); dest[d] |= save; } else /* dOffset[1] < sOffset[1] */ { save = (char) (source[s] << CHAR_DATA_LINES - (sOffset[0] - dOffset[0])); dest[d] &= CHAR_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; if (dOffset[1] > 0) { d++; save = (char) ((source[s] & ~(CHAR_DATA_MASK << sOffset[1])) >>> sOffset[0] - dOffset[0]); dest[d] &= ~(~(CHAR_DATA_MASK << sOffset[1]) >>> sOffset[0] - dOffset[0]); dest[d] |= save; } } } } private static void copyLowerFromBackwards0(char[] source, char[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them char save; int d = dIndex[1]; int s = sIndex[1]; if (sOffset[1] > 0) { if (dOffset[1] > sOffset[1]) { save = (char) ((source[s] & ~(CHAR_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]); dest[d] &= ~(~(CHAR_DATA_MASK << sOffset[1]) << dOffset[1] - sOffset[1]); dest[d] |= save; } else /* dOffset[1] < sOffset[1] */ { if (dOffset[1] > 0) { save = (char) ((source[s] & ~(CHAR_DATA_MASK << sOffset[1])) >>> sOffset[0] - dOffset[0]); dest[d] &= ~(~(CHAR_DATA_MASK << sOffset[1]) >>> sOffset[0] - dOffset[0]); dest[d] |= save; } d save = (char) (source[s] << CHAR_DATA_LINES - (sOffset[0] - dOffset[0])); dest[d] &= CHAR_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; } } while(--s > sIndex[0]) { save = (char) (source[s] >>> sOffset[0] - dOffset[0]); dest[d] &= ~(CHAR_DATA_MASK >>> sOffset[0] - dOffset[0]); dest[d] |= save; --d; save = (char) (source[s] << CHAR_DATA_LINES - (sOffset[0] - dOffset[0])); dest[d] &= CHAR_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; } save = (char) (source[s] >>> sOffset[0] << dOffset[0]); dest[d] &= ~((CHAR_DATA_MASK >>> sOffset[0]) << dOffset[0]); dest[d] |= save; } /** * Copies bits from the specified source storage, beginning at the * specified bit, to the specified bits of the destination storage. A * region of bits is copied from the source storage referenced by * {@code source} to the destination storage referenced by {@code dest}. * The number of bits copied is equal to the {@code length} argument. The * bits at offsets {@code srcPos} through {@code srcPos+length-1} in the * source storage are copied into positions {@code destPos} through * {@code destPos+length-1}, respectively, of the destination storage. * * <p>Offlimits bits are read as 0, and discarded when written to. * </p> * * @param source the source storage. * @param srcPos starting bit in the source storage. * @param dest the destination storage. * @param destPos starting bit in the destination storage. * @param length the number of bits to be copied. * * @since 1.0.0 */ public static void safeCopyFrom(short[] source, int srcPos, short[] dest, int destPos, int length) { safeCopyFrom0(source, byRef(srcPos), dest, byRef(destPos), byRef(length)); } private static void safeCopyFrom0(short[] source, IntRef srcPos, short[] dest, IntRef destPos, IntRef length) { IntRef fillLow = byRef(0); IntRef fillHigh = byRef(0); if (!prepareSafeCopy(srcPos, destPos, length, fillLow, fillHigh, dest.length << SHORT_ADDRESS_LINES, source.length << SHORT_ADDRESS_LINES)) return; copyFrom(source, srcPos.i, dest, destPos.i, length.i); Store.fill(dest, destPos.i + length.i, destPos.i + length.i + fillHigh.i, false); Store.fill(dest, destPos.i - fillLow.i, destPos.i, false); } /** * Copies bits from the specified source storage, beginning at the * specified bit, to the specified bits of the destination storage. A * region of bits is copied from the source storage referenced by * {@code source} to the destination storage referenced by {@code dest}. * The number of bits copied is equal to the {@code length} argument. The * bits at offsets {@code srcPos} through {@code srcPos+length-1} in the * source storage are copied into positions {@code destPos} through * {@code destPos+length-1}, respectively, of the destination storage. * * @param source the source storage. * @param srcPos starting bit in the source storage. * @param dest the destination storage. * @param destPos starting bit in the destination storage. * @param length the number of bits to be copied. * * @since 1.0.0 */ public static void copyFrom(short[] source, int srcPos, short[] dest, int destPos, int length) { if (!checkSafeIndices(srcPos, destPos, length, source.length << SHORT_ADDRESS_LINES, dest.length << SHORT_ADDRESS_LINES)) return; int[] sIndex = {srcPos >> SHORT_ADDRESS_LINES, (srcPos + length) >> SHORT_ADDRESS_LINES}; int[] sOffset = {srcPos & SHORT_ADDRESS_MASK, (srcPos + length) & SHORT_ADDRESS_MASK }; int[] dIndex = {destPos >> SHORT_ADDRESS_LINES, (destPos + length) >> SHORT_ADDRESS_LINES}; int[] dOffset = {destPos & SHORT_ADDRESS_MASK, (destPos + length) & SHORT_ADDRESS_MASK }; if (sOffset[0] == dOffset[0]) // FAST PATH: handle both ends specially, copy middle unchanged copyParallelFrom0(source, dest, sIndex, dIndex, dOffset); else if (sOffset[0] < dOffset[0]) copyHigherFrom0(source, dest, sIndex, sOffset, dIndex, dOffset); else /* if (sOffset[0] > dOffset[0]) */ copyLowerFrom0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyParallelFrom0(short[] source, short[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { if (dIndex[1] == dIndex[0]) { // special case: subword copy within word and neither offset is zero final int LOWEST_BITS_FROM = ~(SHORT_DATA_MASK << dOffset[0]); final int HIGHEST_BITS_TO = SHORT_DATA_MASK << dOffset[1]; short save = (short) (source[sIndex[0]] & ~(LOWEST_BITS_FROM | HIGHEST_BITS_TO)); dest[dIndex[0]] &= LOWEST_BITS_FROM | HIGHEST_BITS_TO; dest[dIndex[0]] |= save; return; } if (dIndex[0] < sIndex[0]) copyParallelFromForwards0(source, dest, sIndex, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyParallelFromForwards0(source, dest, sIndex, dIndex, dOffset); else copyParallelFromBackwards0(source, dest, sIndex, dIndex, dOffset); } private static void copyParallelFromForwards0(short[] source, short[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them short save; if (dOffset[0] != 0) { // handle "from" end specially final int HIGHEST_BITS = SHORT_DATA_MASK << dOffset[0]; final int LOWEST_BITS = ~HIGHEST_BITS; save = (short) (source[sIndex[0]] & HIGHEST_BITS); dest[dIndex[0]] &= LOWEST_BITS; dest[dIndex[0]] |= save; // first index already taken care of sIndex[0]++; dIndex[0]++; } if (dIndex[1] > dIndex[0]) // main bulk copy (FASTEST PATH if no end should be handled specially) System.arraycopy(source, sIndex[0], dest, dIndex[0], dIndex[1]-dIndex[0]); if (dOffset[1] != 0) { // handle "to" end specially final int HIGHEST_BITS = SHORT_DATA_MASK << dOffset[1]; final int LOWEST_BITS = ~HIGHEST_BITS; save = (short) (source[sIndex[1]] & LOWEST_BITS); dest[dIndex[1]] &= HIGHEST_BITS; dest[dIndex[1]] |= save; } } private static void copyParallelFromBackwards0(short[] source, short[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them short save; if (dOffset[1] != 0) { // handle "to" end specially final int HIGHEST_BITS = SHORT_DATA_MASK << dOffset[1]; final int LOWEST_BITS = ~HIGHEST_BITS; save = (short) (source[sIndex[1]] & LOWEST_BITS); dest[dIndex[1]] &= HIGHEST_BITS; dest[dIndex[1]] |= save; } if (dOffset[0] != 0) { // don't copy the first index if partial dIndex[0]++; sIndex[0]++; } if (dIndex[1] > dIndex[0]) // main bulk copy (FASTEST PATH if no end should be handled specially) System.arraycopy(source, sIndex[0], dest, dIndex[0], dIndex[1]-dIndex[0]); if (dOffset[0] != 0) { // handle "from" end specially sIndex[0] dIndex[0] final int HIGHEST_BITS = SHORT_DATA_MASK << dOffset[0]; final int LOWEST_BITS = ~HIGHEST_BITS; save = (short) (source[sIndex[0]] & HIGHEST_BITS); dest[dIndex[0]] &= LOWEST_BITS; dest[dIndex[0]] |= save; } } private static void copyHigherFrom0(short[] source, short[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { if (dIndex[0] == dIndex[1]) { int d = dIndex[0]; int s = sIndex[0]; // At this point dIndex[0] == dIndex[1] AND sOffset[0] < dOffset[0]. // This implies that sIndex[0] == sIndex[1] (so there is no need to copy more than 1 chunk). // I have discovered a truly marvelous proof of this, which this media is too clumsy to contain. short save = (short) ((source[s] << dOffset[0] - sOffset[0]) & ~(SHORT_DATA_MASK << dOffset[1]) & SHORT_DATA_MASK << dOffset[0]); dest[d] &= SHORT_DATA_MASK << dOffset[1] | ~(SHORT_DATA_MASK << dOffset[0]); dest[d] |= save; return; } if (dIndex[0] < sIndex[0]) copyHigherFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyHigherFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else copyHigherFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyHigherFromForwards0(short[] source, short[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them short save; int d = dIndex[0]; int s = sIndex[0]; save = (short) ((source[s] & SHORT_DATA_MASK) >>> sOffset[0] << dOffset[0]); dest[d] &= ~(SHORT_DATA_MASK << dOffset[0]); dest[d] |= save; while(++d < dIndex[1]) { save = (short) ((source[s] & SHORT_DATA_MASK) >>> SHORT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= ~(SHORT_DATA_MASK >>> SHORT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; ++s; save = (short) (source[s] << dOffset[0] - sOffset[0]); dest[d] &= SHORT_DATA_MASK >>> SHORT_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] |= save; } if (dOffset[1] > 0) { if (dOffset[1] < sOffset[1]) { // implies s == sIndex[1] [proof needed] save = (short) ((source[s] & SHORT_DATA_MASK & ~(SHORT_DATA_MASK << sOffset[1])) >>> SHORT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= SHORT_DATA_MASK << dOffset[1]; dest[d] |= save; } else /* dOffset[1] > sOffset[1] */ { save = (short) ((source[s] & SHORT_DATA_MASK) >>> SHORT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= ~(SHORT_DATA_MASK >>> SHORT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; if (sOffset[1] > 0) { s++; save = (short) ((source[s] & ~(SHORT_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]); dest[d] &= SHORT_DATA_MASK << dOffset[1] | SHORT_DATA_MASK >>> SHORT_DATA_LINES - (dOffset[1] - sOffset[1]); dest[d] |= save; } } } } private static void copyHigherFromBackwards0(short[] source, short[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them short save; int d = dIndex[1]; int s = sIndex[1]; if (dOffset[1] > 0) { if (dOffset[1] < sOffset[1]) { save = (short) ((source[s] & SHORT_DATA_MASK & ~(SHORT_DATA_MASK << sOffset[1])) >>> SHORT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= SHORT_DATA_MASK << dOffset[1]; dest[d] |= save; } else /* dOffset[1] > sOffset[1] */ { if (sOffset[1] > 0) { save = (short) ((source[s] & ~(SHORT_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]); dest[d] &= SHORT_DATA_MASK << dOffset[1] | SHORT_DATA_MASK >>> SHORT_DATA_LINES - (dOffset[1] - sOffset[1]); dest[d] |= save; } s save = (short) ((source[s] & SHORT_DATA_MASK) >>> SHORT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= ~(SHORT_DATA_MASK >>> SHORT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; } } while(--d > dIndex[0]) { save = (short) (source[s] << dOffset[0] - sOffset[0]); dest[d] &= SHORT_DATA_MASK >>> SHORT_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] |= save; --s; save = (short) ((source[s] & SHORT_DATA_MASK) >>> SHORT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] &= ~(SHORT_DATA_MASK >>> SHORT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; } save = (short) ((source[s] & SHORT_DATA_MASK) >>> sOffset[0] << dOffset[0]); dest[d] &= ~(SHORT_DATA_MASK << dOffset[0]); dest[d] |= save; } private static void copyLowerFrom0(short[] source, short[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { if (sIndex[0] == sIndex[1]) { int d = dIndex[0]; int s = sIndex[0]; // At this point sIndex[0] == sIndex[1] AND sOffset[0] > dOffset[0]. // This implies that dIndex[0] == dIndex[1] (so there is no need to copy more than 1 chunk). // I have discovered a truly marvelous proof of this, which this media is too clumsy to contain. short save = (short) ((source[s] & SHORT_DATA_MASK) >>> (sOffset[0] - dOffset[0]) & ~(SHORT_DATA_MASK << dOffset[1]) & SHORT_DATA_MASK << dOffset[0]); dest[d] &= SHORT_DATA_MASK << dOffset[1] | ~(SHORT_DATA_MASK << dOffset[0]); dest[d] |= save; return; } if (dIndex[0] < sIndex[0]) copyLowerFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyLowerFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else copyLowerFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyLowerFromForwards0(short[] source, short[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them short save; int d = dIndex[0]; int s = sIndex[0]; save = (short) ((source[s] & SHORT_DATA_MASK) >>> sOffset[0] << dOffset[0]); dest[d] &= ~((SHORT_DATA_MASK >>> sOffset[0]) << dOffset[0]); dest[d] |= save; while(++s < sIndex[1]) { save = (short) (source[s] << SHORT_DATA_LINES - (sOffset[0] - dOffset[0])); dest[d] &= SHORT_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; ++d; save = (short) ((source[s] & SHORT_DATA_MASK) >>> sOffset[0] - dOffset[0]); dest[d] &= ~(SHORT_DATA_MASK >>> sOffset[0] - dOffset[0]); dest[d] |= save; } if (sOffset[1] > 0) { if (dOffset[1] > sOffset[1]) { // implies d == dIndex[1] [proof needed] save = (short) ((source[s] & ~(SHORT_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]); dest[d] &= ~(~(SHORT_DATA_MASK << sOffset[1]) << dOffset[1] - sOffset[1]); dest[d] |= save; } else /* dOffset[1] < sOffset[1] */ { save = (short) (source[s] << SHORT_DATA_LINES - (sOffset[0] - dOffset[0])); dest[d] &= SHORT_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; if (dOffset[1] > 0) { d++; save = (short) ((source[s] & SHORT_DATA_MASK & ~(SHORT_DATA_MASK << sOffset[1])) >>> sOffset[0] - dOffset[0]); dest[d] &= ~(~(SHORT_DATA_MASK << sOffset[1]) >>> sOffset[0] - dOffset[0]); dest[d] |= save; } } } } private static void copyLowerFromBackwards0(short[] source, short[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them short save; int d = dIndex[1]; int s = sIndex[1]; if (sOffset[1] > 0) { if (dOffset[1] > sOffset[1]) { save = (short) ((source[s] & ~(SHORT_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]); dest[d] &= ~(~(SHORT_DATA_MASK << sOffset[1]) << dOffset[1] - sOffset[1]); dest[d] |= save; } else /* dOffset[1] < sOffset[1] */ { if (dOffset[1] > 0) { save = (short) ((source[s] & SHORT_DATA_MASK & ~(SHORT_DATA_MASK << sOffset[1])) >>> sOffset[0] - dOffset[0]); dest[d] &= ~(~(SHORT_DATA_MASK << sOffset[1]) >>> sOffset[0] - dOffset[0]); dest[d] |= save; } d save = (short) (source[s] << SHORT_DATA_LINES - (sOffset[0] - dOffset[0])); dest[d] &= SHORT_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; } } while(--s > sIndex[0]) { save = (short) ((source[s] & SHORT_DATA_MASK) >>> sOffset[0] - dOffset[0]); dest[d] &= ~(SHORT_DATA_MASK >>> sOffset[0] - dOffset[0]); dest[d] |= save; --d; save = (short) (source[s] << SHORT_DATA_LINES - (sOffset[0] - dOffset[0])); dest[d] &= SHORT_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; } save = (short) ((source[s] & SHORT_DATA_MASK) >>> sOffset[0] << dOffset[0]); dest[d] &= ~((SHORT_DATA_MASK >>> sOffset[0]) << dOffset[0]); dest[d] |= save; } /** * Copies bits from the specified source storage, beginning at the * specified bit, to the specified bits of the destination storage. A * region of bits is copied from the source storage referenced by * {@code source} to the destination storage referenced by {@code dest}. * The number of bits copied is equal to the {@code length} argument. The * bits at offsets {@code srcPos} through {@code srcPos+length-1} in the * source storage are copied into positions {@code destPos} through * {@code destPos+length-1}, respectively, of the destination storage. * * <p>Offlimits bits are read as 0, and discarded when written to. * </p> * * @param source the source storage. * @param srcPos starting bit in the source storage. * @param dest the destination storage. * @param destPos starting bit in the destination storage. * @param length the number of bits to be copied. * * @since 1.0.0 */ public static void safeCopyFrom(int[] source, int srcPos, int[] dest, int destPos, int length) { safeCopyFrom0(source, byRef(srcPos), dest, byRef(destPos), byRef(length)); } private static void safeCopyFrom0(int[] source, IntRef srcPos, int[] dest, IntRef destPos, IntRef length) { IntRef fillLow = byRef(0); IntRef fillHigh = byRef(0); if (!prepareSafeCopy(srcPos, destPos, length, fillLow, fillHigh, dest.length << INT_ADDRESS_LINES, source.length << INT_ADDRESS_LINES)) return; copyFrom(source, srcPos.i, dest, destPos.i, length.i); Store.fill(dest, destPos.i + length.i, destPos.i + length.i + fillHigh.i, false); Store.fill(dest, destPos.i - fillLow.i, destPos.i, false); } /** * Copies bits from the specified source storage, beginning at the * specified bit, to the specified bits of the destination storage. A * region of bits is copied from the source storage referenced by * {@code source} to the destination storage referenced by {@code dest}. * The number of bits copied is equal to the {@code length} argument. The * bits at offsets {@code srcPos} through {@code srcPos+length-1} in the * source storage are copied into positions {@code destPos} through * {@code destPos+length-1}, respectively, of the destination storage. * * @param source the source storage. * @param srcPos starting bit in the source storage. * @param dest the destination storage. * @param destPos starting bit in the destination storage. * @param length the number of bits to be copied. * * @since 1.0.0 */ public static void copyFrom(int[] source, int srcPos, int[] dest, int destPos, int length) { if (!checkSafeIndices(srcPos, destPos, length, source.length << INT_ADDRESS_LINES, dest.length << INT_ADDRESS_LINES)) return; int[] sIndex = {srcPos >> INT_ADDRESS_LINES, (srcPos + length) >> INT_ADDRESS_LINES}; int[] sOffset = {srcPos & INT_ADDRESS_MASK, (srcPos + length) & INT_ADDRESS_MASK }; int[] dIndex = {destPos >> INT_ADDRESS_LINES, (destPos + length) >> INT_ADDRESS_LINES}; int[] dOffset = {destPos & INT_ADDRESS_MASK, (destPos + length) & INT_ADDRESS_MASK }; if (sOffset[0] == dOffset[0]) // FAST PATH: handle both ends specially, copy middle unchanged copyParallelFrom0(source, dest, sIndex, dIndex, dOffset); else if (sOffset[0] < dOffset[0]) copyHigherFrom0(source, dest, sIndex, sOffset, dIndex, dOffset); else /* if (sOffset[0] > dOffset[0]) */ copyLowerFrom0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyParallelFrom0(int[] source, int[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { if (dIndex[1] == dIndex[0]) { // special case: subword copy within word and neither offset is zero final int LOWEST_BITS_FROM = ~(INT_DATA_MASK << dOffset[0]); final int HIGHEST_BITS_TO = INT_DATA_MASK << dOffset[1]; int save = source[sIndex[0]] & ~(LOWEST_BITS_FROM | HIGHEST_BITS_TO); dest[dIndex[0]] &= LOWEST_BITS_FROM | HIGHEST_BITS_TO; dest[dIndex[0]] |= save; return; } if (dIndex[0] < sIndex[0]) copyParallelFromForwards0(source, dest, sIndex, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyParallelFromForwards0(source, dest, sIndex, dIndex, dOffset); else copyParallelFromBackwards0(source, dest, sIndex, dIndex, dOffset); } private static void copyParallelFromForwards0(int[] source, int[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them int save; if (dOffset[0] != 0) { // handle "from" end specially final int HIGHEST_BITS = INT_DATA_MASK << dOffset[0]; final int LOWEST_BITS = ~HIGHEST_BITS; save = source[sIndex[0]] & HIGHEST_BITS; dest[dIndex[0]] &= LOWEST_BITS; dest[dIndex[0]] |= save; // first index already taken care of sIndex[0]++; dIndex[0]++; } if (dIndex[1] > dIndex[0]) // main bulk copy (FASTEST PATH if no end should be handled specially) System.arraycopy(source, sIndex[0], dest, dIndex[0], dIndex[1]-dIndex[0]); if (dOffset[1] != 0) { // handle "to" end specially final int HIGHEST_BITS = INT_DATA_MASK << dOffset[1]; final int LOWEST_BITS = ~HIGHEST_BITS; save = source[sIndex[1]] & LOWEST_BITS; dest[dIndex[1]] &= HIGHEST_BITS; dest[dIndex[1]] |= save; } } private static void copyParallelFromBackwards0(int[] source, int[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them int save; if (dOffset[1] != 0) { // handle "to" end specially final int HIGHEST_BITS = INT_DATA_MASK << dOffset[1]; final int LOWEST_BITS = ~HIGHEST_BITS; save = source[sIndex[1]] & LOWEST_BITS; dest[dIndex[1]] &= HIGHEST_BITS; dest[dIndex[1]] |= save; } if (dOffset[0] != 0) { // don't copy the first index if partial dIndex[0]++; sIndex[0]++; } if (dIndex[1] > dIndex[0]) // main bulk copy (FASTEST PATH if no end should be handled specially) System.arraycopy(source, sIndex[0], dest, dIndex[0], dIndex[1]-dIndex[0]); if (dOffset[0] != 0) { // handle "from" end specially sIndex[0] dIndex[0] final int HIGHEST_BITS = INT_DATA_MASK << dOffset[0]; final int LOWEST_BITS = ~HIGHEST_BITS; save = source[sIndex[0]] & HIGHEST_BITS; dest[dIndex[0]] &= LOWEST_BITS; dest[dIndex[0]] |= save; } } private static void copyHigherFrom0(int[] source, int[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { if (dIndex[0] == dIndex[1]) { int d = dIndex[0]; int s = sIndex[0]; // At this point dIndex[0] == dIndex[1] AND sOffset[0] < dOffset[0]. // This implies that sIndex[0] == sIndex[1] (so there is no need to copy more than 1 chunk). // I have discovered a truly marvelous proof of this, which this media is too clumsy to contain. int save = (source[s] << dOffset[0] - sOffset[0]) & ~(INT_DATA_MASK << dOffset[1]) & INT_DATA_MASK << dOffset[0]; dest[d] &= INT_DATA_MASK << dOffset[1] | ~(INT_DATA_MASK << dOffset[0]); dest[d] |= save; return; } if (dIndex[0] < sIndex[0]) copyHigherFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyHigherFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else copyHigherFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyHigherFromForwards0(int[] source, int[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them int save; int d = dIndex[0]; int s = sIndex[0]; save = source[s] >>> sOffset[0] << dOffset[0]; dest[d] &= ~(INT_DATA_MASK << dOffset[0]); dest[d] |= save; while(++d < dIndex[1]) { save = source[s] >>> INT_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] &= ~(INT_DATA_MASK >>> INT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; ++s; save = source[s] << dOffset[0] - sOffset[0]; dest[d] &= INT_DATA_MASK >>> INT_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] |= save; } if (dOffset[1] > 0) { if (dOffset[1] < sOffset[1]) { // implies s == sIndex[1] [proof needed] save = (source[s] & ~(INT_DATA_MASK << sOffset[1])) >>> INT_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] &= INT_DATA_MASK << dOffset[1]; dest[d] |= save; } else /* dOffset[1] > sOffset[1] */ { save = source[s] >>> INT_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] &= ~(INT_DATA_MASK >>> INT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; if (sOffset[1] > 0) { s++; save = (source[s] & ~(INT_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]; dest[d] &= INT_DATA_MASK << dOffset[1] | INT_DATA_MASK >>> INT_DATA_LINES - (dOffset[1] - sOffset[1]); dest[d] |= save; } } } } private static void copyHigherFromBackwards0(int[] source, int[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them int save; int d = dIndex[1]; int s = sIndex[1]; if (dOffset[1] > 0) { if (dOffset[1] < sOffset[1]) { save = (source[s] & ~(INT_DATA_MASK << sOffset[1])) >>> INT_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] &= INT_DATA_MASK << dOffset[1]; dest[d] |= save; } else /* dOffset[1] > sOffset[1] */ { if (sOffset[1] > 0) { save = (source[s] & ~(INT_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]; dest[d] &= INT_DATA_MASK << dOffset[1] | INT_DATA_MASK >>> INT_DATA_LINES - (dOffset[1] - sOffset[1]); dest[d] |= save; } s save = source[s] >>> INT_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] &= ~(INT_DATA_MASK >>> INT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; } } while(--d > dIndex[0]) { save = source[s] << dOffset[0] - sOffset[0]; dest[d] &= INT_DATA_MASK >>> INT_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] |= save; --s; save = source[s] >>> INT_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] &= ~(INT_DATA_MASK >>> INT_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; } save = source[s] >>> sOffset[0] << dOffset[0]; dest[d] &= ~(INT_DATA_MASK << dOffset[0]); dest[d] |= save; } private static void copyLowerFrom0(int[] source, int[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { if (sIndex[0] == sIndex[1]) { int d = dIndex[0]; int s = sIndex[0]; // At this point sIndex[0] == sIndex[1] AND sOffset[0] > dOffset[0]. // This implies that dIndex[0] == dIndex[1] (so there is no need to copy more than 1 chunk). // I have discovered a truly marvelous proof of this, which this media is too clumsy to contain. int save = source[s] >>> (sOffset[0] - dOffset[0]) & ~(INT_DATA_MASK << dOffset[1]) & INT_DATA_MASK << dOffset[0]; dest[d] &= INT_DATA_MASK << dOffset[1] | ~(INT_DATA_MASK << dOffset[0]); dest[d] |= save; return; } if (dIndex[0] < sIndex[0]) copyLowerFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyLowerFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else copyLowerFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyLowerFromForwards0(int[] source, int[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them int save; int d = dIndex[0]; int s = sIndex[0]; save = source[s] >>> sOffset[0] << dOffset[0]; dest[d] &= ~((INT_DATA_MASK >>> sOffset[0]) << dOffset[0]); dest[d] |= save; while(++s < sIndex[1]) { save = source[s] << INT_DATA_LINES - (sOffset[0] - dOffset[0]); dest[d] &= INT_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; ++d; save = source[s] >>> sOffset[0] - dOffset[0]; dest[d] &= ~(INT_DATA_MASK >>> sOffset[0] - dOffset[0]); dest[d] |= save; } if (sOffset[1] > 0) { if (dOffset[1] > sOffset[1]) { // implies d == dIndex[1] [proof needed] save = (source[s] & ~(INT_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]; dest[d] &= ~(~(INT_DATA_MASK << sOffset[1]) << dOffset[1] - sOffset[1]); dest[d] |= save; } else /* dOffset[1] < sOffset[1] */ { save = source[s] << INT_DATA_LINES - (sOffset[0] - dOffset[0]); dest[d] &= INT_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; if (dOffset[1] > 0) { d++; save = (source[s] & ~(INT_DATA_MASK << sOffset[1])) >>> sOffset[0] - dOffset[0]; dest[d] &= ~(~(INT_DATA_MASK << sOffset[1]) >>> sOffset[0] - dOffset[0]); dest[d] |= save; } } } } private static void copyLowerFromBackwards0(int[] source, int[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them int save; int d = dIndex[1]; int s = sIndex[1]; if (sOffset[1] > 0) { if (dOffset[1] > sOffset[1]) { save = (source[s] & ~(INT_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]; dest[d] &= ~(~(INT_DATA_MASK << sOffset[1]) << dOffset[1] - sOffset[1]); dest[d] |= save; } else /* dOffset[1] < sOffset[1] */ { if (dOffset[1] > 0) { save = (source[s] & ~(INT_DATA_MASK << sOffset[1])) >>> sOffset[0] - dOffset[0]; dest[d] &= ~(~(INT_DATA_MASK << sOffset[1]) >>> sOffset[0] - dOffset[0]); dest[d] |= save; } d save = source[s] << INT_DATA_LINES - (sOffset[0] - dOffset[0]); dest[d] &= INT_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; } } while(--s > sIndex[0]) { save = source[s] >>> sOffset[0] - dOffset[0]; dest[d] &= ~(INT_DATA_MASK >>> sOffset[0] - dOffset[0]); dest[d] |= save; --d; save = source[s] << INT_DATA_LINES - (sOffset[0] - dOffset[0]); dest[d] &= INT_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; } save = source[s] >>> sOffset[0] << dOffset[0]; dest[d] &= ~((INT_DATA_MASK >>> sOffset[0]) << dOffset[0]); dest[d] |= save; } /** * Copies bits from the specified source storage, beginning at the * specified bit, to the specified bits of the destination storage. A * region of bits is copied from the source storage referenced by * {@code source} to the destination storage referenced by {@code dest}. * The number of bits copied is equal to the {@code length} argument. The * bits at offsets {@code srcPos} through {@code srcPos+length-1} in the * source storage are copied into positions {@code destPos} through * {@code destPos+length-1}, respectively, of the destination storage. * * <p>Offlimits bits are read as 0, and discarded when written to. * </p> * * @param source the source storage. * @param srcPos starting bit in the source storage. * @param dest the destination storage. * @param destPos starting bit in the destination storage. * @param length the number of bits to be copied. * * @since 1.0.0 */ public static void safeCopyFrom(long[] source, int srcPos, long[] dest, int destPos, int length) { safeCopyFrom0(source, byRef(srcPos), dest, byRef(destPos), byRef(length)); } private static void safeCopyFrom0(long[] source, IntRef srcPos, long[] dest, IntRef destPos, IntRef length) { IntRef fillLow = byRef(0); IntRef fillHigh = byRef(0); if (!prepareSafeCopy(srcPos, destPos, length, fillLow, fillHigh, dest.length << LONG_ADDRESS_LINES, source.length << LONG_ADDRESS_LINES)) return; copyFrom(source, srcPos.i, dest, destPos.i, length.i); Store.fill(dest, destPos.i + length.i, destPos.i + length.i + fillHigh.i, false); Store.fill(dest, destPos.i - fillLow.i, destPos.i, false); } /** * Copies bits from the specified source storage, beginning at the * specified bit, to the specified bits of the destination storage. A * region of bits is copied from the source storage referenced by * {@code source} to the destination storage referenced by {@code dest}. * The number of bits copied is equal to the {@code length} argument. The * bits at offsets {@code srcPos} through {@code srcPos+length-1} in the * source storage are copied into positions {@code destPos} through * {@code destPos+length-1}, respectively, of the destination storage. * * @param source the source storage. * @param srcPos starting bit in the source storage. * @param dest the destination storage. * @param destPos starting bit in the destination storage. * @param length the number of bits to be copied. * * @since 1.0.0 */ public static void copyFrom(long[] source, int srcPos, long[] dest, int destPos, int length) { if (!checkSafeIndices(srcPos, destPos, length, source.length << LONG_ADDRESS_LINES, dest.length << LONG_ADDRESS_LINES)) return; int[] sIndex = {srcPos >> LONG_ADDRESS_LINES, (srcPos + length) >> LONG_ADDRESS_LINES}; int[] sOffset = {srcPos & LONG_ADDRESS_MASK, (srcPos + length) & LONG_ADDRESS_MASK }; int[] dIndex = {destPos >> LONG_ADDRESS_LINES, (destPos + length) >> LONG_ADDRESS_LINES}; int[] dOffset = {destPos & LONG_ADDRESS_MASK, (destPos + length) & LONG_ADDRESS_MASK }; if (sOffset[0] == dOffset[0]) // FAST PATH: handle both ends specially, copy middle unchanged copyParallelFrom0(source, dest, sIndex, dIndex, dOffset); else if (sOffset[0] < dOffset[0]) copyHigherFrom0(source, dest, sIndex, sOffset, dIndex, dOffset); else /* if (sOffset[0] > dOffset[0]) */ copyLowerFrom0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyParallelFrom0(long[] source, long[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { if (dIndex[1] == dIndex[0]) { // special case: subword copy within word and neither offset is zero final long LOWEST_BITS_FROM = ~(LONG_DATA_MASK << dOffset[0]); final long HIGHEST_BITS_TO = LONG_DATA_MASK << dOffset[1]; long save = source[sIndex[0]] & ~(LOWEST_BITS_FROM | HIGHEST_BITS_TO); dest[dIndex[0]] &= LOWEST_BITS_FROM | HIGHEST_BITS_TO; dest[dIndex[0]] |= save; return; } if (dIndex[0] < sIndex[0]) copyParallelFromForwards0(source, dest, sIndex, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyParallelFromForwards0(source, dest, sIndex, dIndex, dOffset); else copyParallelFromBackwards0(source, dest, sIndex, dIndex, dOffset); } private static void copyParallelFromForwards0(long[] source, long[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them long save; if (dOffset[0] != 0) { // handle "from" end specially final long HIGHEST_BITS = LONG_DATA_MASK << dOffset[0]; final long LOWEST_BITS = ~HIGHEST_BITS; save = source[sIndex[0]] & HIGHEST_BITS; dest[dIndex[0]] &= LOWEST_BITS; dest[dIndex[0]] |= save; // first index already taken care of sIndex[0]++; dIndex[0]++; } if (dIndex[1] > dIndex[0]) // main bulk copy (FASTEST PATH if no end should be handled specially) System.arraycopy(source, sIndex[0], dest, dIndex[0], dIndex[1]-dIndex[0]); if (dOffset[1] != 0) { // handle "to" end specially final long HIGHEST_BITS = LONG_DATA_MASK << dOffset[1]; final long LOWEST_BITS = ~HIGHEST_BITS; save = source[sIndex[1]] & LOWEST_BITS; dest[dIndex[1]] &= HIGHEST_BITS; dest[dIndex[1]] |= save; } } private static void copyParallelFromBackwards0(long[] source, long[] dest, int[] sIndex, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them long save; if (dOffset[1] != 0) { // handle "to" end specially final long HIGHEST_BITS = LONG_DATA_MASK << dOffset[1]; final long LOWEST_BITS = ~HIGHEST_BITS; save = source[sIndex[1]] & LOWEST_BITS; dest[dIndex[1]] &= HIGHEST_BITS; dest[dIndex[1]] |= save; } if (dOffset[0] != 0) { // don't copy the first index if partial dIndex[0]++; sIndex[0]++; } if (dIndex[1] > dIndex[0]) // main bulk copy (FASTEST PATH if no end should be handled specially) System.arraycopy(source, sIndex[0], dest, dIndex[0], dIndex[1]-dIndex[0]); if (dOffset[0] != 0) { // handle "from" end specially sIndex[0] dIndex[0] final long HIGHEST_BITS = LONG_DATA_MASK << dOffset[0]; final long LOWEST_BITS = ~HIGHEST_BITS; save = source[sIndex[0]] & HIGHEST_BITS; dest[dIndex[0]] &= LOWEST_BITS; dest[dIndex[0]] |= save; } } private static void copyHigherFrom0(long[] source, long[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { if (dIndex[0] == dIndex[1]) { int d = dIndex[0]; int s = sIndex[0]; // At this point dIndex[0] == dIndex[1] AND sOffset[0] < dOffset[0]. // This implies that sIndex[0] == sIndex[1] (so there is no need to copy more than 1 chunk). // I have discovered a truly marvelous proof of this, which this media is too clumsy to contain. long save = (source[s] << dOffset[0] - sOffset[0]) & ~(LONG_DATA_MASK << dOffset[1]) & LONG_DATA_MASK << dOffset[0]; dest[d] &= LONG_DATA_MASK << dOffset[1] | ~(LONG_DATA_MASK << dOffset[0]); dest[d] |= save; return; } if (dIndex[0] < sIndex[0]) copyHigherFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyHigherFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else copyHigherFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyHigherFromForwards0(long[] source, long[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them long save; int d = dIndex[0]; int s = sIndex[0]; save = source[s] >>> sOffset[0] << dOffset[0]; dest[d] &= ~(LONG_DATA_MASK << dOffset[0]); dest[d] |= save; while(++d < dIndex[1]) { save = source[s] >>> LONG_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] &= ~(LONG_DATA_MASK >>> LONG_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; ++s; save = source[s] << dOffset[0] - sOffset[0]; dest[d] &= LONG_DATA_MASK >>> LONG_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] |= save; } if (dOffset[1] > 0) { if (dOffset[1] < sOffset[1]) { // implies s == sIndex[1] [proof needed] save = (source[s] & ~(LONG_DATA_MASK << sOffset[1])) >>> LONG_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] &= LONG_DATA_MASK << dOffset[1]; dest[d] |= save; } else /* dOffset[1] > sOffset[1] */ { save = source[s] >>> LONG_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] &= ~(LONG_DATA_MASK >>> LONG_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; if (sOffset[1] > 0) { s++; save = (source[s] & ~(LONG_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]; dest[d] &= LONG_DATA_MASK << dOffset[1] | LONG_DATA_MASK >>> LONG_DATA_LINES - (dOffset[1] - sOffset[1]); dest[d] |= save; } } } } private static void copyHigherFromBackwards0(long[] source, long[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them long save; int d = dIndex[1]; int s = sIndex[1]; if (dOffset[1] > 0) { if (dOffset[1] < sOffset[1]) { save = (source[s] & ~(LONG_DATA_MASK << sOffset[1])) >>> LONG_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] &= LONG_DATA_MASK << dOffset[1]; dest[d] |= save; } else /* dOffset[1] > sOffset[1] */ { if (sOffset[1] > 0) { save = (source[s] & ~(LONG_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]; dest[d] &= LONG_DATA_MASK << dOffset[1] | LONG_DATA_MASK >>> LONG_DATA_LINES - (dOffset[1] - sOffset[1]); dest[d] |= save; } s save = source[s] >>> LONG_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] &= ~(LONG_DATA_MASK >>> LONG_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; } } while(--d > dIndex[0]) { save = source[s] << dOffset[0] - sOffset[0]; dest[d] &= LONG_DATA_MASK >>> LONG_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] |= save; --s; save = source[s] >>> LONG_DATA_LINES - (dOffset[0] - sOffset[0]); dest[d] &= ~(LONG_DATA_MASK >>> LONG_DATA_LINES - (dOffset[0] - sOffset[0])); dest[d] |= save; } save = source[s] >>> sOffset[0] << dOffset[0]; dest[d] &= ~(LONG_DATA_MASK << dOffset[0]); dest[d] |= save; } private static void copyLowerFrom0(long[] source, long[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { if (sIndex[0] == sIndex[1]) { int d = dIndex[0]; int s = sIndex[0]; // At this point sIndex[0] == sIndex[1] AND sOffset[0] > dOffset[0]. // This implies that dIndex[0] == dIndex[1] (so there is no need to copy more than 1 chunk). // I have discovered a truly marvelous proof of this, which this media is too clumsy to contain. long save = source[s] >>> (sOffset[0] - dOffset[0]) & ~(LONG_DATA_MASK << dOffset[1]) & LONG_DATA_MASK << dOffset[0]; dest[d] &= LONG_DATA_MASK << dOffset[1] | ~(LONG_DATA_MASK << dOffset[0]); dest[d] |= save; return; } if (dIndex[0] < sIndex[0]) copyLowerFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else if (dIndex[0] == sIndex[0]) copyLowerFromForwards0(source, dest, sIndex, sOffset, dIndex, dOffset); else copyLowerFromBackwards0(source, dest, sIndex, sOffset, dIndex, dOffset); } private static void copyLowerFromForwards0(long[] source, long[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them long save; int d = dIndex[0]; int s = sIndex[0]; save = source[s] >>> sOffset[0] << dOffset[0]; dest[d] &= ~((LONG_DATA_MASK >>> sOffset[0]) << dOffset[0]); dest[d] |= save; while(++s < sIndex[1]) { save = source[s] << LONG_DATA_LINES - (sOffset[0] - dOffset[0]); dest[d] &= LONG_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; ++d; save = source[s] >>> sOffset[0] - dOffset[0]; dest[d] &= ~(LONG_DATA_MASK >>> sOffset[0] - dOffset[0]); dest[d] |= save; } if (sOffset[1] > 0) { if (dOffset[1] > sOffset[1]) { // implies d == dIndex[1] [proof needed] save = (source[s] & ~(LONG_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]; dest[d] &= ~(~(LONG_DATA_MASK << sOffset[1]) << dOffset[1] - sOffset[1]); dest[d] |= save; } else /* dOffset[1] < sOffset[1] */ { save = source[s] << LONG_DATA_LINES - (sOffset[0] - dOffset[0]); dest[d] &= LONG_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; if (dOffset[1] > 0) { d++; save = (source[s] & ~(LONG_DATA_MASK << sOffset[1])) >>> sOffset[0] - dOffset[0]; dest[d] &= ~(~(LONG_DATA_MASK << sOffset[1]) >>> sOffset[0] - dOffset[0]); dest[d] |= save; } } } } private static void copyLowerFromBackwards0(long[] source, long[] dest, int[] sIndex, int[] sOffset, int[] dIndex, int[] dOffset) { // for the cases where source == dest, so save |red bits, before &ing them long save; int d = dIndex[1]; int s = sIndex[1]; if (sOffset[1] > 0) { if (dOffset[1] > sOffset[1]) { save = (source[s] & ~(LONG_DATA_MASK << sOffset[1])) << dOffset[1] - sOffset[1]; dest[d] &= ~(~(LONG_DATA_MASK << sOffset[1]) << dOffset[1] - sOffset[1]); dest[d] |= save; } else /* dOffset[1] < sOffset[1] */ { if (dOffset[1] > 0) { save = (source[s] & ~(LONG_DATA_MASK << sOffset[1])) >>> sOffset[0] - dOffset[0]; dest[d] &= ~(~(LONG_DATA_MASK << sOffset[1]) >>> sOffset[0] - dOffset[0]); dest[d] |= save; } d save = source[s] << LONG_DATA_LINES - (sOffset[0] - dOffset[0]); dest[d] &= LONG_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; } } while(--s > sIndex[0]) { save = source[s] >>> sOffset[0] - dOffset[0]; dest[d] &= ~(LONG_DATA_MASK >>> sOffset[0] - dOffset[0]); dest[d] |= save; --d; save = source[s] << LONG_DATA_LINES - (sOffset[0] - dOffset[0]); dest[d] &= LONG_DATA_MASK >>> sOffset[0] - dOffset[0]; dest[d] |= save; } save = source[s] >>> sOffset[0] << dOffset[0]; dest[d] &= ~((LONG_DATA_MASK >>> sOffset[0]) << dOffset[0]); dest[d] |= save; } }
package com.akiban.sql.aisddl; import com.akiban.server.api.DDLFunctions; import com.akiban.server.error.*; import com.akiban.server.service.session.Session; import com.akiban.sql.optimizer.AISBinderContext; import com.akiban.sql.optimizer.AISViewDefinition; import com.akiban.sql.parser.CreateViewNode; import com.akiban.sql.parser.DropViewNode; import com.akiban.sql.parser.ExistenceCheck; import com.akiban.sql.parser.NodeTypes; import com.akiban.sql.parser.ResultColumn; import com.akiban.sql.types.DataTypeDescriptor; import com.akiban.sql.types.TypeId; import com.akiban.ais.model.AISBuilder; import com.akiban.ais.model.AkibanInformationSchema; import com.akiban.ais.model.Columnar; import com.akiban.ais.model.TableName; import com.akiban.ais.model.View; import com.akiban.sql.pg.PostgresQueryContext; import java.util.Collection; import java.util.Map; /** DDL operations on Views */ public class ViewDDL { private ViewDDL() { } public static void createView(DDLFunctions ddlFunctions, Session session, String defaultSchemaName, CreateViewNode createView, AISBinderContext binderContext, PostgresQueryContext context) { com.akiban.sql.parser.TableName parserName = createView.getObjectName(); String schemaName = parserName.hasSchema() ? parserName.getSchemaName() : defaultSchemaName; String viewName = parserName.getTableName(); ExistenceCheck condition = createView.getExistenceCheck(); if (ddlFunctions.getAIS(session).getView(schemaName, viewName) != null) { switch(condition) { case IF_NOT_EXISTS: // view already exists. does nothing if (context != null) context.warnClient(new DuplicateViewException(schemaName, viewName)); return; case NO_CONDITION: throw new DuplicateViewException(schemaName, viewName); default: throw new IllegalStateException("Unexpected condition: " + condition); } } AISViewDefinition viewdef = binderContext.getViewDefinition(createView); Map<TableName,Collection<String>> tableColumnReferences = viewdef.getTableColumnReferences(); AISBuilder builder = new AISBuilder(); builder.view(schemaName, viewName, viewdef.getQueryExpression(), binderContext.getParserProperties(schemaName), tableColumnReferences); int colpos = 0; for (ResultColumn rc : viewdef.getResultColumns()) { DataTypeDescriptor type = rc.getType(); if (type == null) { if (rc.getExpression().getNodeType() != NodeTypes.UNTYPED_NULL_CONSTANT_NODE) throw new AkibanInternalException(rc.getName() + " has unknown type"); type = new DataTypeDescriptor(TypeId.CHAR_ID, true, 0); } TableDDL.addColumn(builder, schemaName, viewName, rc.getName(), colpos++, type, type.isNullable(), false, null); } View view = builder.akibanInformationSchema().getView(schemaName, viewName); ddlFunctions.createView(session, view); } public static void dropView (DDLFunctions ddlFunctions, Session session, String defaultSchemaName, DropViewNode dropView, AISBinderContext binderContext, PostgresQueryContext context) { com.akiban.sql.parser.TableName parserName = dropView.getObjectName(); String schemaName = parserName.hasSchema() ? parserName.getSchemaName() : defaultSchemaName; TableName viewName = TableName.create(schemaName, parserName.getTableName()); ExistenceCheck existenceCheck = dropView.getExistenceCheck(); if (ddlFunctions.getAIS(session).getView(viewName) == null) { if (existenceCheck == ExistenceCheck.IF_EXISTS) { if (context != null) context.warnClient(new UndefinedViewException(viewName)); return; } throw new UndefinedViewException(viewName); } checkDropTable(ddlFunctions, session, viewName); ddlFunctions.dropView(session, viewName); } public static void checkDropTable(DDLFunctions ddlFunctions, Session session, TableName name) { AkibanInformationSchema ais = ddlFunctions.getAIS(session); Columnar table = ais.getColumnar(name); if (table == null) return; for (View view : ais.getViews().values()) { if (view.referencesTable(table)) { throw new ViewReferencesExist(view.getName().getSchemaName(), view.getName().getTableName(), table.getName().getSchemaName(), table.getName().getTableName()); } } } }
package com.example.filelist; import com.example.Dialogs; import com.example.preview.FilePreview; import com.example.preview.FilePreviewFactory; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import static java.awt.event.KeyEvent.VK_ENTER; import static javax.swing.KeyStroke.getKeyStroke; /** * @author innokenty */ public abstract class FileList<T extends FileListEntry> extends JList<T> { public FileList(FileListModel<T> dataModel) { super(dataModel); setCellRenderer(new FileListEntryRenderer()); initOpeningSelectedOnEnter(); initOpeningSelectedOnDoubleClick(); } /* MODEL METHODS OVERRIDING */ @Override public void setModel(ListModel<T> model) { if (model instanceof FileListModel) { super.setModel(model); } else { throw new IllegalArgumentException("Only model of type " + "com.example.filelist.FileListModel is supported"); } } public FileListModel<T> getModel() { return (FileListModel<T>) super.getModel(); } public void openSelected() { T selectedFile = super.getSelectedValue(); if (selectedFile.isDirectory()) { try { getModel().openFolder(selectedFile); } catch (Exception e) { Dialogs.unexpectedError(e, this); } } else { try { showFilePreview(); } catch (IOException e) { Dialogs.unexpectedError(e, this); } } } /* GUI INITIALIZATION METHODS */ protected void initOpeningSelectedOnEnter() { final String openFolderKey = "openFolder"; KeyStroke enterKeyStroke = getKeyStroke(VK_ENTER, 0); super.getInputMap().put(enterKeyStroke, openFolderKey); super.getActionMap().put(openFolderKey, openSelectedAction()); } private AbstractAction openSelectedAction() { return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { openSelected(); } }; } protected void initOpeningSelectedOnDoubleClick() { addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { openSelected(); } } }); } protected void showFilePreview() throws IOException { FilePreview preview = FilePreviewFactory .getPreviewDialogFor(super.getSelectedValue()); if (preview != null) { preview.setLocationRelativeTo(this); preview.pack(); preview.setVisible(true); } else { Dialogs.sorryBro("Opening this type of files is not supported!", this); } } }
package com.fishercoder.solutions; import java.util.Arrays; import java.util.Deque; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; /** * 71. Simplify Path Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" Corner Cases: Did you consider the case where path = "/../"? In this case, you should return "/". Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo". */ public class _71 { public static class Solution1 { public String simplifyPath(String path) { Deque<String> stack = new LinkedList<>(); Set<String> skipSet = new HashSet<>(Arrays.asList("..", ".", "")); for (String dir : path.split("/")) { if (dir.equals("..") && !stack.isEmpty()) { stack.pop(); } else if (!skipSet.contains(dir)) { stack.push(dir); } } String result = ""; for (String dir : stack) { result = "/" + dir + result; } return result.isEmpty() ? "/" : result; } } }
package com.github.taojoe; import com.github.taojoe.core.BeanUtil; import com.google.protobuf.Descriptors; import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; import com.google.protobuf.MapEntry; import com.google.protobuf.Message; import com.google.protobuf.MessageOrBuilder; import java.math.BigDecimal; import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Transformer { protected Object javaValueToMessageValue(Object value, Descriptors.FieldDescriptor fieldDescriptor){ JavaType type=fieldDescriptor.getJavaType(); if(type.equals(JavaType.BOOLEAN)){ return value; }else if(type.equals(JavaType.INT) ||type.equals(JavaType.LONG)){ if(value instanceof BigInteger){ if(type.equals(JavaType.INT)){ return ((BigInteger) value).intValue(); }else{ return ((BigInteger) value).longValue(); } } return value; }else if(type.equals(JavaType.FLOAT) || type.equals(JavaType.DOUBLE)){ if(value instanceof BigDecimal){ if(type.equals(JavaType.FLOAT)){ return ((BigDecimal) value).floatValue(); }else{ return ((BigDecimal) value).doubleValue(); } } return value; }else if(type.equals(JavaType.STRING)){ return value.toString(); }else if(type.equals(JavaType.ENUM)){ if(value instanceof String) { return fieldDescriptor.getEnumType().findValueByName((String) value); }else if(value.getClass().isEnum()){ return fieldDescriptor.getEnumType().findValueByName(((Enum) value).name()); } } return null; } protected Object massageValueToJavaValue(Object value, Class clz){ String clzName=clz.getName(); if(clz.equals(Integer.class) || clz.equals(Long.class) || clz.equals(Float.class) || clz.equals(Double.class) ||clz.equals(Boolean.class) || clz.equals(int.class) || clz.equals(long.class) || clz.equals(float.class) || clz.equals(double.class) || clz.equals(boolean.class)){ // clz,boolean, boolean type, return value; }else if(clz.equals(String.class)){ if(value instanceof String){ return value; }else if(value instanceof Descriptors.EnumDescriptor){ return ((Descriptors.EnumDescriptor)value).getName(); } }else if(clz.isEnum()){ if(value instanceof String){ return Enum.valueOf(clz, (String) value); }else if(value instanceof Descriptors.EnumValueDescriptor){ return Enum.valueOf(clz, ((Descriptors.EnumValueDescriptor) value).getName() ); } }else if(clz.equals(BigDecimal.class)){ return new BigDecimal((double)value); }else if(clz.equals(LocalDateTime.class)){ return LocalDateTime.parse((String) value); }else if(clz.equals(LocalDate.class)){ return LocalDate.parse((String) value); } return null; } public <T> T messageToJava(MessageOrBuilder message, Class<T> clz){ List<Descriptors.FieldDescriptor> fields=message.getDescriptorForType().getFields(); try { T target=clz.newInstance(); for(Descriptors.FieldDescriptor fieldDescriptor:fields){ boolean hasValue=false; if(fieldDescriptor.isRepeated()){ hasValue=message.getRepeatedFieldCount(fieldDescriptor)>0; }else{ hasValue=message.hasField(fieldDescriptor) || fieldDescriptor.getJavaType().equals(JavaType.ENUM); } if(!hasValue){ continue; } Object oldValue=message.getField(fieldDescriptor); String name = fieldDescriptor.getName(); Object newValue=null; BeanUtil.FieldOrProperty objField=BeanUtil.fieldOrProperty(target, name); if(objField!=null && objField.typeDescriptor.mustValueClz()){ boolean isValueMessage=fieldDescriptor.getJavaType().equals(Descriptors.FieldDescriptor.JavaType.MESSAGE); if(fieldDescriptor.isMapField()){ //fieldDescriptor mapentry, entry message, entry valuefieldDescriptor if(fieldDescriptor.getMessageType()!=null) { List<Descriptors.FieldDescriptor> entryFields = fieldDescriptor.getMessageType().getFields(); if (entryFields != null && entryFields.size() == 2) { Descriptors.FieldDescriptor valueFieldDescriptor = entryFields.get(1); isValueMessage = valueFieldDescriptor.getJavaType().equals(Descriptors.FieldDescriptor.JavaType.MESSAGE); Map<Object, Object> destMap=new HashMap<>(); List<MapEntry<Object, MessageOrBuilder>> origList=(List)oldValue; for(com.google.protobuf.MapEntry<Object, MessageOrBuilder> entry: origList){ Object mapValue=null; if(isValueMessage){ mapValue=messageToJava(entry.getValue(), objField.typeDescriptor.valueClz); }else{ mapValue=massageValueToJavaValue(entry.getValue(), objField.typeDescriptor.valueClz); } destMap.put(entry.getKey(), mapValue); } newValue=destMap; } } }else if(fieldDescriptor.isRepeated()){ ArrayList<Object> destList=new ArrayList<>(); if(isValueMessage){ List<MessageOrBuilder> origList=(List) oldValue; for (MessageOrBuilder org : origList) { destList.add(messageToJava(org, objField.typeDescriptor.valueClz)); } }else{ List<Object> origList=(List) oldValue; for(Object obj:origList){ destList.add(massageValueToJavaValue(obj, objField.typeDescriptor.valueClz)); } } newValue=destList; }else { if(isValueMessage){ newValue=messageToJava((MessageOrBuilder) oldValue, objField.typeDescriptor.valueClz); }else{ newValue=massageValueToJavaValue(oldValue, objField.typeDescriptor.valueClz); } } if(newValue!=null){ objField.setValue(target, newValue); } } } return target; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } public <T extends Message.Builder> T javaToMessage(Object bean, T builder){ Class clz=bean.getClass(); List<Descriptors.FieldDescriptor> fields=builder.getDescriptorForType().getFields(); for (Descriptors.FieldDescriptor fieldDescriptor: fields) { String name=fieldDescriptor.getName(); BeanUtil.FieldOrProperty objField=BeanUtil.fieldOrProperty(bean, name); if(objField!=null){ Object oldValue=objField.getValue(bean); if(oldValue!=null){ boolean isValueMessage=fieldDescriptor.getJavaType().equals(Descriptors.FieldDescriptor.JavaType.MESSAGE); if(fieldDescriptor.isMapField()){ if(oldValue instanceof Map){ //fieldDescriptor mapentry, entry message, entry valuefieldDescriptor if(fieldDescriptor.getMessageType()!=null){ List<Descriptors.FieldDescriptor> entryFields=fieldDescriptor.getMessageType().getFields(); if(entryFields!=null && entryFields.size()==2) { Descriptors.FieldDescriptor valueFieldDescriptor = entryFields.get(1); isValueMessage=valueFieldDescriptor.getJavaType().equals(Descriptors.FieldDescriptor.JavaType.MESSAGE); for(Map.Entry<Object, Object> entry:((Map<Object, Object>) oldValue).entrySet()){ Message.Builder tmpBuilder=builder.newBuilderForField(fieldDescriptor); MapEntry.Builder entryBuilder=(MapEntry.Builder) tmpBuilder; entryBuilder.setKey(entry.getKey()); if(isValueMessage){ entryBuilder.setValue(javaToMessage(entry.getValue(), entryBuilder.newBuilderForField(valueFieldDescriptor)).build()); }else{ entryBuilder.setValue(javaValueToMessageValue(entry.getValue(), valueFieldDescriptor)); } } } } } }else if(fieldDescriptor.isRepeated()){ if(oldValue instanceof List){ if(isValueMessage){ for(Object tmp:(List) oldValue){ Message.Builder tmpBuilder=builder.newBuilderForField(fieldDescriptor); builder.addRepeatedField(fieldDescriptor, javaToMessage(tmp, tmpBuilder).build()); } }else{ for(Object tmp:(List) oldValue){ builder.addRepeatedField(fieldDescriptor, javaValueToMessageValue(tmp, fieldDescriptor)); } } } }else { if(isValueMessage){ Message.Builder tmpBuilder=builder.newBuilderForField(fieldDescriptor); builder.setField(fieldDescriptor, javaToMessage(oldValue, tmpBuilder).build()); }else{ builder.setField(fieldDescriptor, javaValueToMessageValue(oldValue, fieldDescriptor)); } } } } } return builder; } public Object getValueByFieldNameOrNull(MessageOrBuilder message, String fieldName, Object defaultValue){ Descriptors.FieldDescriptor field=message.getDescriptorForType().findFieldByName(fieldName); if(field!=null && message.hasField(field)){ return message.getField(field); } return defaultValue; } public Object getValueByFieldNameOrNull(MessageOrBuilder message, String fieldName){ return getValueByFieldNameOrNull(message, fieldName, null); } }
package com.jcabi.manifests; import com.jcabi.aspects.Immutable; import com.jcabi.log.Logger; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Enumeration; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.Manifest; import javax.servlet.ServletContext; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.SerializationUtils; @Immutable @SuppressWarnings("PMD.UseConcurrentHashMap") public final class Manifests { /** * Injected attributes. * @see #inject(String,String) */ private static final Map<String, String> INJECTED = new ConcurrentHashMap<String, String>(); /** * Attributes retrieved from all existing {@code MANIFEST.MF} files. * @see #load() */ private static Map<String, String> attributes = Manifests.load(); /** * Failures registered during loading. * @see #load() */ private static Map<URI, String> failures; /** * It's a utility class, can't be instantiated. */ private Manifests() { // intentionally empty } public static String read( @NotNull(message = "attribute name can't be NULL") @Pattern(regexp = ".+", message = "attribute name can't be empty") final String name) { if (Manifests.attributes == null) { throw new IllegalArgumentException( "Manifests haven't been loaded yet, internal error" ); } if (!Manifests.exists(name)) { final StringBuilder bldr = new StringBuilder( Logger.format( // @checkstyle LineLength (1 line) "Atribute '%s' not found in MANIFEST.MF file(s) among %d other attribute(s) %[list]s and %d injection(s)", name, Manifests.attributes.size(), new TreeSet<String>(Manifests.attributes.keySet()), Manifests.INJECTED.size() ) ); if (!Manifests.failures.isEmpty()) { bldr.append("; failures: ").append( Logger.format("%[list]s", Manifests.failures.keySet()) ); } throw new IllegalArgumentException(bldr.toString()); } String result; if (Manifests.INJECTED.containsKey(name)) { result = Manifests.INJECTED.get(name); } else { result = Manifests.attributes.get(name); } Logger.debug(Manifests.class, "#read('%s'): found '%s'", name, result); return result; } /** * Inject new attribute. * * <p>An attribute can be injected in runtime, mostly for the sake of * unit and integration testing. Once injected an attribute becomes * available with {@link #read(String)}. * * <p>The method is thread-safe. * * @param name Name of the attribute * @param value The value of the attribute being injected */ public static void inject( @NotNull(message = "injected name can't be NULL") @Pattern(regexp = ".+", message = "name of attribute can't be empty") final String name, @NotNull(message = "inected value can't be NULL") final String value) { if (Manifests.INJECTED.containsKey(name)) { Logger.info( Manifests.class, "#inject(%s, '%s'): replaced previous injection '%s'", name, value, Manifests.INJECTED.get(name) ); } else { Logger.info( Manifests.class, "#inject(%s, '%s'): injected", name, value ); } Manifests.INJECTED.put(name, value); } /** * Check whether attribute exists in any of {@code MANIFEST.MF} files. * * <p>Use this method before {@link #read(String)} to check whether an * attribute exists, in order to avoid a runtime exception. * * <p>The method is thread-safe. * * @param name Name of the attribute to check * @return Returns {@code TRUE} if it exists, {@code FALSE} otherwise */ public static boolean exists( @NotNull(message = "name of attribute can't be NULL") @Pattern(regexp = ".+", message = "name of attribute can't be empty") final String name) { final boolean exists = Manifests.attributes.containsKey(name) || Manifests.INJECTED.containsKey(name); Logger.debug(Manifests.class, "#exists('%s'): %B", name, exists); return exists; } /** * Make a snapshot of current attributes and their values. * * <p>The method is thread-safe. * * @return The snapshot, to be used later with {@link #revert(byte[])} */ public static byte[] snapshot() { byte[] snapshot; synchronized (Manifests.INJECTED) { snapshot = SerializationUtils.serialize( (Serializable) Manifests.INJECTED ); } Logger.debug( Manifests.class, "#snapshot(): created (%d bytes)", snapshot.length ); return snapshot; } /** * Revert to the state that was recorded by {@link #snapshot()}. * * <p>The method is thread-safe. * * @param snapshot The snapshot taken by {@link #snapshot()} */ @SuppressWarnings("unchecked") public static void revert(@NotNull final byte[] snapshot) { synchronized (Manifests.INJECTED) { Manifests.INJECTED.clear(); Manifests.INJECTED.putAll( (Map<String, String>) SerializationUtils.deserialize(snapshot) ); } Logger.debug( Manifests.class, "#revert(%d bytes): reverted", snapshot.length ); } /** * Append attributes from the web application {@code MANIFEST.MF}. * * <p>You can call this method in your own * {@link javax.servlet.Filter} or * {@link javax.servlet.ServletContextListener}, * in order to inject {@code MANIFEST.MF} attributes to the class. * * <p>The method is thread-safe. * * @param ctx Servlet context * @see #Manifests() * @throws IOException If some I/O problem inside */ public static void append(@NotNull final ServletContext ctx) throws IOException { final long start = System.currentTimeMillis(); URL main; try { main = ctx.getResource("/META-INF/MANIFEST.MF"); } catch (java.net.MalformedURLException ex) { throw new IOException(ex); } if (main == null) { Logger.warn( Manifests.class, "#append(%s): MANIFEST.MF not found in WAR package", ctx.getClass().getName() ); } else { final Map<String, String> attrs = Manifests.loadOneFile(main); Manifests.attributes.putAll(attrs); Logger.info( Manifests.class, // @checkstyle LineLength (1 line) "#append(%s): %d attribs loaded from %s in %[ms]s (%d total): %[list]s", ctx.getClass().getName(), attrs.size(), main, System.currentTimeMillis() - start, Manifests.attributes.size(), new TreeSet<String>(attrs.keySet()) ); } } /** * Append attributes from the file. * * <p>The method is thread-safe. * * @param file The file to load attributes from * @throws IOException If some I/O problem inside */ public static void append(@NotNull final File file) throws IOException { final long start = System.currentTimeMillis(); Map<String, String> attrs; try { attrs = Manifests.loadOneFile(file.toURI().toURL()); } catch (java.net.MalformedURLException ex) { throw new IOException(ex); } Manifests.attributes.putAll(attrs); Logger.info( Manifests.class, // @checkstyle LineLength (1 line) "#append('%s'): %d attributes loaded in %[ms]s (%d total): %[list]s", file, attrs.size(), System.currentTimeMillis() - start, Manifests.attributes.size(), new TreeSet<String>(attrs.keySet()) ); } /** * Load attributes from classpath. * * <p>This method doesn't throw any checked exceptions because it is called * from a static context above. It's just more convenient to catch all * exceptions here than above in a static call block. * * @return All found attributes */ private static Map<String, String> load() { final long start = System.currentTimeMillis(); Manifests.failures = new ConcurrentHashMap<URI, String>(); final Map<String, String> attrs = new ConcurrentHashMap<String, String>(); int count = 0; for (URI uri : Manifests.uris()) { try { attrs.putAll(Manifests.loadOneFile(uri.toURL())); } catch (IOException ex) { Manifests.failures.put(uri, ex.getMessage()); Logger.error( Manifests.class, "#load(): '%s' failed %[exception]s", uri, ex ); } ++count; } Logger.info( Manifests.class, "#load(): %d attribs loaded from %d URL(s) in %[ms]s: %[list]s", attrs.size(), count, System.currentTimeMillis() - start, new TreeSet<String>(attrs.keySet()) ); return attrs; } /** * Find all URLs. * * <p>This method doesn't throw any checked exceptions just for convenience * of calling of it (above in {@linke #load}), although it is clear that * {@link IOException} is a good candidate for being thrown out of it. * * @return The list of URLs * @see #load() */ private static Set<URI> uris() { Enumeration<URL> resources; try { resources = Thread.currentThread().getContextClassLoader() .getResources("META-INF/MANIFEST.MF"); } catch (IOException ex) { throw new IllegalStateException(ex); } final Set<URI> uris = new HashSet<URI>(); while (resources.hasMoreElements()) { try { uris.add(resources.nextElement().toURI()); } catch (URISyntaxException ex) { throw new IllegalStateException(ex); } } return uris; } /** * Load attributes from one file. * * <p>Inside the method we catch {@code RuntimeException} (which may look * suspicious) in order to protect our execution flow from expected (!) * exceptions from {@link Manifest#getMainAttributes()}. For some reason, * this JDK method doesn't throw checked exceptions if {@code MANIFEST.MF} * file format is broken. Instead, it throws a runtime exception (an * unchecked one), which we should catch in such an inconvenient way. * * @param url The URL of it * @return The attributes loaded * @see #load() * @see tickets #193 and #323 * @throws IOException If some problem happens */ @SuppressWarnings("PMD.AvoidCatchingGenericException") private static Map<String, String> loadOneFile(final URL url) throws IOException { final Map<String, String> props = new ConcurrentHashMap<String, String>(); final InputStream stream = url.openStream(); try { final Manifest manifest = new Manifest(stream); final Attributes attrs = manifest.getMainAttributes(); for (Object key : attrs.keySet()) { final String value = attrs.getValue((Name) key); props.put(key.toString(), value); } Logger.debug( Manifests.class, "#loadOneFile('%s'): %d attributes loaded (%[list]s)", url, props.size(), new TreeSet<String>(props.keySet()) ); } catch (RuntimeException ex) { Logger.error( Manifests.class, "#getMainAttributes(): '%s' failed %[exception]s", url, ex ); } finally { IOUtils.closeQuietly(stream); } return props; } }
package com.queen.counter.domain; import javafx.animation.Animation; import javafx.animation.TranslateTransition; import javafx.beans.binding.When; import javafx.beans.property.*; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import org.reactfx.EventSource; import org.reactfx.EventStream; import org.reactfx.EventStreams; import org.reactfx.util.Tuple2; import java.time.LocalTime; public class Cell { private VBox rectangle; private Location location; private Text label; private TranslateTransition translateTransition; private BooleanProperty edgeTopRectangle = new SimpleBooleanProperty(false); private BooleanProperty hasTextRectangle = new SimpleBooleanProperty(false); private IntegerProperty currentDelta = new SimpleIntegerProperty(0); private EventSource deltaStream; public Cell(VBox rectangle, Location location, Text label, TranslateTransition translateTransition, EventSource<Tuple2<Integer, ColumnType>> deltaStream) { this.rectangle = rectangle; this.location = location; this.label = label; this.translateTransition = translateTransition; this.deltaStream = deltaStream; this.edgeTopRectangle.bind(new When(rectangle.translateYProperty().isEqualTo(0)).then(true).otherwise(false)); this.hasTextRectangle.bind(new When(rectangle.translateYProperty().greaterThan(180).and(rectangle.translateYProperty().lessThan(240)).and(currentDelta.lessThan(0))).then(true).otherwise( new When(rectangle.translateYProperty().greaterThan(0).and(rectangle.translateYProperty().lessThan(60)).and(currentDelta.greaterThan(0))).then(true).otherwise(false) )); EventStream<Number> translateY = EventStreams.valuesOf(rectangle.translateYProperty()); currentDelta.bind(deltaStream.map(Tuple2::get1).toBinding(0)); EventStream<Tuple2<Tuple2<Integer, ColumnType>, Double>> combo = EventStreams.combine( this.deltaStream, translateY ); combo.map(change -> { Integer currDelta = change.get1().get1(); Double transY = change.get2(); if (currDelta == 0 || currDelta < 0) { if (transY == 0) { return 240; } else { return transY; } } else { if (transY == 240) { return 0; } else { return transY; } } }).feedTo(translateTransition.fromYProperty()); combo.map(change -> { Integer currDelta = change.get1().get1(); Double transY = change.get2(); if (currDelta == 0 || currDelta < 0) { if (transY == 0) { return 180; } else { return transY - 60; } } else { if (transY == 240) { return 60; } else { return transY + 60; } } }).feedTo(translateTransition.toYProperty()); } public void animate() { translateTransition.play(); } public BooleanProperty hasTopEdgeRectangle() { return this.edgeTopRectangle; } public BooleanProperty hasChangeTextRectangle() { return this.hasTextRectangle; } public void setLabel(String newLabel) { if (label.getId().contains(rectangle.getId())) { this.label.setText(newLabel); } } public void setLabel(boolean topEdgeExists, LocalTime clock, ColumnType columnType) { if (columnType.equals(ColumnType.SECONDS)) { if (topEdgeExists) { if (rectangle.translateYProperty().get() == 0) { label.setText(Integer.toString(clock.plusSeconds(2).getSecond())); } if (rectangle.translateYProperty().get() == 60) { label.setText(Integer.toString(clock.plusSeconds(1).getSecond())); } if (rectangle.translateYProperty().get() == 120) { label.setText(Integer.toString(clock.getSecond())); } if (rectangle.translateYProperty().get() == 180) { label.setText(Integer.toString(clock.minusSeconds(1).getSecond())); } } if (!topEdgeExists) { if (rectangle.translateYProperty().get() == 60) { label.setText(Integer.toString(clock.plusSeconds(2).getSecond())); } if (rectangle.translateYProperty().get() == 120) { label.setText(Integer.toString(clock.plusSeconds(1).getSecond())); } if (rectangle.translateYProperty().get() == 180) { label.setText(Integer.toString(clock.getSecond())); } if (rectangle.translateYProperty().get() == 240) { label.setText(Integer.toString(clock.minusSeconds(1).getSecond())); } } } if (columnType.equals(ColumnType.MINUTES)) { if (topEdgeExists) { if (rectangle.translateYProperty().get() == 0) { label.setText(Integer.toString(clock.plusMinutes(2).getMinute())); } if (rectangle.translateYProperty().get() == 60) { label.setText(Integer.toString(clock.plusMinutes(1).getMinute())); } if (rectangle.translateYProperty().get() == 120) { label.setText(Integer.toString(clock.getMinute())); } if (rectangle.translateYProperty().get() == 180) { label.setText(Integer.toString(clock.minusMinutes(1).getMinute())); } } if (!topEdgeExists) { if (rectangle.translateYProperty().get() == 60) { label.setText(Integer.toString(clock.plusMinutes(2).getMinute())); } if (rectangle.translateYProperty().get() == 120) { label.setText(Integer.toString(clock.plusMinutes(1).getMinute())); } if (rectangle.translateYProperty().get() == 180) { label.setText(Integer.toString(clock.getMinute())); } if (rectangle.translateYProperty().get() == 240) { label.setText(Integer.toString(clock.minusMinutes(1).getMinute())); } } } if (columnType.equals(ColumnType.HOURS)) { if (topEdgeExists) { if (rectangle.translateYProperty().get() == 0) { label.setText(Integer.toString(clock.plusHours(2).getHour())); } if (rectangle.translateYProperty().get() == 60) { label.setText(Integer.toString(clock.plusHours(1).getHour())); } if (rectangle.translateYProperty().get() == 120) { label.setText(Integer.toString(clock.getHour())); } if (rectangle.translateYProperty().get() == 180) { label.setText(Integer.toString(clock.minusHours(1).getHour())); } } if (!topEdgeExists) { if (rectangle.translateYProperty().get() == 60) { label.setText(Integer.toString(clock.plusHours(2).getHour())); } if (rectangle.translateYProperty().get() == 120) { label.setText(Integer.toString(clock.plusHours(1).getHour())); } if (rectangle.translateYProperty().get() == 180) { label.setText(Integer.toString(clock.getHour())); } if (rectangle.translateYProperty().get() == 240) { label.setText(Integer.toString(clock.minusHours(1).getHour())); } } } } public ReadOnlyObjectProperty<Animation.Status> isRunning() { return translateTransition.statusProperty(); } public int getDelta() { return this.currentDelta.get(); } }
package com.untamedears.humbug; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.logging.Level; import java.util.logging.Logger; import net.minecraft.server.v1_8_R2.EntityEnderPearl; import net.minecraft.server.v1_8_R2.EntityTypes; import net.minecraft.server.v1_8_R2.Item; import net.minecraft.server.v1_8_R2.ItemEnderPearl; import net.minecraft.server.v1_8_R2.MinecraftKey; import net.minecraft.server.v1_8_R2.RegistryID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.Hopper; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Arrow; import org.bukkit.entity.Boat; import org.bukkit.entity.Damageable; import org.bukkit.entity.Enderman; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Horse; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Minecart; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.entity.Skeleton.SkeletonType; import org.bukkit.entity.Vehicle; import org.bukkit.entity.minecart.HopperMinecart; import org.bukkit.entity.minecart.StorageMinecart; 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.block.BlockBreakEvent; import org.bukkit.event.block.BlockFromToEvent; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.enchantment.EnchantItemEvent; import org.bukkit.event.enchantment.PrepareItemEnchantEvent; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityCreatePortalEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityInteractEvent; import org.bukkit.event.entity.EntityPortalEvent; import org.bukkit.event.entity.EntityShootBowEvent; import org.bukkit.event.entity.ExpBottleEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.entity.PotionSplashEvent; import org.bukkit.event.entity.SheepDyeWoolEvent; import org.bukkit.event.inventory.InventoryMoveItemEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.PlayerBucketEmptyEvent; import org.bukkit.event.player.PlayerExpChangeEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemConsumeEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.vehicle.VehicleDestroyEvent; import org.bukkit.event.vehicle.VehicleEnterEvent; import org.bukkit.event.vehicle.VehicleExitEvent; import org.bukkit.event.vehicle.VehicleMoveEvent; import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.event.world.PortalCreateEvent; import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; import org.bukkit.util.Vector; import com.untamedears.humbug.annotations.BahHumbug; import com.untamedears.humbug.annotations.BahHumbugs; import com.untamedears.humbug.annotations.ConfigOption; import com.untamedears.humbug.annotations.OptType; public class Humbug extends JavaPlugin implements Listener { public static void severe(String message) { log_.severe("[Humbug] " + message); } public static void warning(String message) { log_.warning("[Humbug] " + message); } public static void info(String message) { log_.info("[Humbug] " + message); } public static void debug(String message) { if (config_.getDebug()) { log_.info("[Humbug] " + message); } } public static Humbug getPlugin() { return global_instance_; } private static final Logger log_ = Logger.getLogger("Humbug"); private static Humbug global_instance_ = null; private static Config config_ = null; private static int max_golden_apple_stack_ = 1; static { max_golden_apple_stack_ = Material.GOLDEN_APPLE.getMaxStackSize(); if (max_golden_apple_stack_ > 64) { max_golden_apple_stack_ = 64; } } private Random prng_ = new Random(); private CombatTagManager combatTag_ = new CombatTagManager(); public Humbug() {} // Reduce registered PlayerInteractEvent count. onPlayerInteractAll handles // cancelled events. @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onPlayerInteract(PlayerInteractEvent event) { onAnvilOrEnderChestUse(event); if (!event.isCancelled()) { onCauldronInteract(event); } if (!event.isCancelled()) { onRecordInJukebox(event); } if (!event.isCancelled()) { onEnchantingTableUse(event); } if (!event.isCancelled()) { onChangingSpawners(event); } } @BahHumbug(opt="changing_spawners_with_eggs", def="true") public void onChangingSpawners(PlayerInteractEvent event) { if (!config_.get("changing_spawners_with_eggs").getBool()) { return; } if ((event.getClickedBlock() != null) && (event.getItem() != null) && (event.getClickedBlock().getType()==Material.MOB_SPAWNER) && (event.getItem().getType() == Material.MONSTER_EGG)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.LOWEST) // ignoreCancelled=false public void onPlayerInteractAll(PlayerInteractEvent event) { onPlayerEatGoldenApple(event); throttlePearlTeleport(event); } // Stops people from dying sheep @BahHumbug(opt="allow_dye_sheep", def="true") @EventHandler public void onDyeWool(SheepDyeWoolEvent event) { if (!config_.get("allow_dye_sheep").getBool()) { event.setCancelled(true); } } // Configurable bow buff @EventHandler public void onEntityShootBowEventAlreadyIntializedSoIMadeThisUniqueName(EntityShootBowEvent event) { Integer power = event.getBow().getEnchantmentLevel(Enchantment.ARROW_DAMAGE); MetadataValue metadata = new FixedMetadataValue(this, power); event.getProjectile().setMetadata("power", metadata); } @BahHumbug(opt="bow_buff", type=OptType.Double, def="1.000000") @EventHandler public void onArrowHitEntity(EntityDamageByEntityEvent event) { Double multiplier = config_.get("bow_buff").getDouble(); if(multiplier <= 1.000001 && multiplier >= 0.999999) { return; } if (event.getEntity() instanceof LivingEntity) { Entity damager = event.getDamager(); if (damager instanceof Arrow) { Arrow arrow = (Arrow) event.getDamager(); Double damage = event.getDamage() * config_.get("bow_buff").getDouble(); Integer power = 0; if(arrow.hasMetadata("power")) { power = arrow.getMetadata("power").get(0).asInt(); } damage *= Math.pow(1.25, power - 5); // f(x) = 1.25^(x - 5) event.setDamage(damage); } } } // Fixes Teleporting through walls and doors // ** and ** // Ender Pearl Teleportation disabling // ** and ** // Ender pearl cooldown timer private class PearlTeleportInfo { public long last_teleport; public long last_notification; } private Map<String, PearlTeleportInfo> pearl_teleport_info_ = new TreeMap<String, PearlTeleportInfo>(); private final static int PEARL_THROTTLE_WINDOW = 10000; // 10 sec private final static int PEARL_NOTIFICATION_WINDOW = 1000; // 1 sec // EventHandler registered in onPlayerInteractAll @BahHumbug(opt="ender_pearl_teleportation_throttled", def="true") public void throttlePearlTeleport(PlayerInteractEvent event) { if (!config_.get("ender_pearl_teleportation_throttled").getBool()) { return; } if (event.getItem() == null || !event.getItem().getType().equals(Material.ENDER_PEARL)) { return; } final Action action = event.getAction(); if (action != Action.RIGHT_CLICK_AIR && action != Action.RIGHT_CLICK_BLOCK) { return; } final Block clickedBlock = event.getClickedBlock(); BlockState clickedState = null; Material clickedMaterial = null; if (clickedBlock != null) { clickedState = clickedBlock.getState(); clickedMaterial = clickedState.getType(); } if (clickedState != null && ( clickedState instanceof InventoryHolder || clickedMaterial.equals(Material.ANVIL) || clickedMaterial.equals(Material.ENCHANTMENT_TABLE) || clickedMaterial.equals(Material.ENDER_CHEST) || clickedMaterial.equals(Material.WORKBENCH))) { // Prevent Combat Tag/Pearl cooldown on inventory access return; } final long current_time = System.currentTimeMillis(); final Player player = event.getPlayer(); final String player_name = player.getName(); PearlTeleportInfo teleport_info = pearl_teleport_info_.get(player_name); long time_diff = 0; if (teleport_info == null) { // New pearl thrown outside of throttle window teleport_info = new PearlTeleportInfo(); teleport_info.last_teleport = current_time; teleport_info.last_notification = current_time - (PEARL_NOTIFICATION_WINDOW + 100); // Force notify combatTag_.tagPlayer(player); } else { time_diff = current_time - teleport_info.last_teleport; if (PEARL_THROTTLE_WINDOW > time_diff) { // Pearl throw throttled event.setCancelled(true); } else { // New pearl thrown outside of throttle window combatTag_.tagPlayer(player); teleport_info.last_teleport = current_time; teleport_info.last_notification = current_time - (PEARL_NOTIFICATION_WINDOW + 100); // Force notify time_diff = 0; } } final long notify_diff = current_time - teleport_info.last_notification; if (notify_diff > PEARL_NOTIFICATION_WINDOW) { teleport_info.last_notification = current_time; Integer tagCooldown = combatTag_.remainingSeconds(player); if (tagCooldown != null) { player.sendMessage(String.format( "Pearl in %d seconds. Combat Tag in %d seconds.", (PEARL_THROTTLE_WINDOW - time_diff + 500) / 1000, tagCooldown)); } else { player.sendMessage(String.format( "Pearl Teleport Cooldown: %d seconds", (PEARL_THROTTLE_WINDOW - time_diff + 500) / 1000)); } } pearl_teleport_info_.put(player_name, teleport_info); return; } @BahHumbugs({ @BahHumbug(opt="ender_pearl_teleportation", def="true"), @BahHumbug(opt="fix_teleport_glitch", def="true") }) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onTeleport(PlayerTeleportEvent event) { TeleportCause cause = event.getCause(); if (cause != TeleportCause.ENDER_PEARL) { return; } else if (!config_.get("ender_pearl_teleportation").getBool()) { event.setCancelled(true); return; } if (!config_.get("fix_teleport_glitch").getBool()) { return; } Location to = event.getTo(); World world = to.getWorld(); // From and To are feet positions. Check and make sure we can teleport to a location with air // above the To location. Block toBlock = world.getBlockAt(to); Block aboveBlock = world.getBlockAt(to.getBlockX(), to.getBlockY()+1, to.getBlockZ()); Block belowBlock = world.getBlockAt(to.getBlockX(), to.getBlockY()-1, to.getBlockZ()); boolean lowerBlockBypass = false; double height = 0.0; switch( toBlock.getType() ) { case CHEST: // Probably never will get hit directly case ENDER_CHEST: // Probably never will get hit directly height = 0.875; break; case STEP: lowerBlockBypass = true; height = 0.5; break; case WATER_LILY: height = 0.016; break; case ENCHANTMENT_TABLE: lowerBlockBypass = true; height = 0.75; break; case BED: case BED_BLOCK: // This one is tricky, since even with a height offset of 2.5, it still glitches. //lowerBlockBypass = true; //height = 0.563; // Disabling teleporting on top of beds for now by leaving lowerBlockBypass false. break; case FLOWER_POT: case FLOWER_POT_ITEM: height = 0.375; break; case SKULL: // Probably never will get hit directly height = 0.5; break; default: break; } // Check if the below block is difficult // This is added because if you face downward directly on a gate, it will // teleport your feet INTO the gate, thus bypassing the gate until you leave that block. switch( belowBlock.getType() ) { case FENCE: case FENCE_GATE: case NETHER_FENCE: case COBBLE_WALL: height = 0.5; break; default: break; } boolean upperBlockBypass = false; if( height >= 0.5 ) { Block aboveHeadBlock = world.getBlockAt(aboveBlock.getX(), aboveBlock.getY()+1, aboveBlock.getZ()); if( false == aboveHeadBlock.getType().isSolid() ) { height = 0.5; } else { upperBlockBypass = true; // Cancel this event. What's happening is the user is going to get stuck due to the height. } } // Normalize teleport to the center of the block. Feet ON the ground, plz. // Leave Yaw and Pitch alone to.setX(Math.floor(to.getX()) + 0.5000); to.setY(Math.floor(to.getY()) + height); to.setZ(Math.floor(to.getZ()) + 0.5000); if(aboveBlock.getType().isSolid() || (toBlock.getType().isSolid() && !lowerBlockBypass) || upperBlockBypass ) { // One last check because I care about Top Nether. (someone build me a shrine up there) boolean bypass = false; if ((world.getEnvironment() == Environment.NETHER) && (to.getBlockY() > 124) && (to.getBlockY() < 129)) { bypass = true; } if (!bypass) { event.setCancelled(true); } } } // Villager Trading @BahHumbug(opt="villager_trades") @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { if (config_.get("villager_trades").getBool()) { return; } Entity npc = event.getRightClicked(); if (npc == null) { return; } if (npc.getType() == EntityType.VILLAGER) { event.setCancelled(true); } } // Anvil and Ender Chest usage // EventHandler registered in onPlayerInteract @BahHumbugs({ @BahHumbug(opt="anvil"), @BahHumbug(opt="ender_chest") }) public void onAnvilOrEnderChestUse(PlayerInteractEvent event) { if (config_.get("anvil").getBool() && config_.get("ender_chest").getBool()) { return; } Action action = event.getAction(); Material material = event.getClickedBlock().getType(); boolean anvil = !config_.get("anvil").getBool() && action == Action.RIGHT_CLICK_BLOCK && material.equals(Material.ANVIL); boolean ender_chest = !config_.get("ender_chest").getBool() && action == Action.RIGHT_CLICK_BLOCK && material.equals(Material.ENDER_CHEST); if (anvil || ender_chest) { event.setCancelled(true); } } @BahHumbug(opt="enchanting_table", def = "false") public void onEnchantingTableUse(PlayerInteractEvent event) { if(!config_.get("enchanting_table").getBool()) { return; } Action action = event.getAction(); Material material = event.getClickedBlock().getType(); boolean enchanting_table = action == Action.RIGHT_CLICK_BLOCK && material.equals(Material.ENCHANTMENT_TABLE); if(enchanting_table) { event.setCancelled(true); } } @BahHumbug(opt="ender_chests_placeable", def="true") @EventHandler(ignoreCancelled=true) public void onEnderChestPlace(BlockPlaceEvent e) { Material material = e.getBlock().getType(); if (!config_.get("ender_chests_placeable").getBool() && material == Material.ENDER_CHEST) { e.setCancelled(true); } } public void EmptyEnderChest(HumanEntity human) { if (config_.get("ender_backpacks").getBool()) { dropInventory(human.getLocation(), human.getEnderChest()); } } public void dropInventory(Location loc, Inventory inv) { final World world = loc.getWorld(); final int end = inv.getSize(); for (int i = 0; i < end; ++i) { try { final ItemStack item = inv.getItem(i); if (item != null) { world.dropItemNaturally(loc, item); inv.clear(i); } } catch (Exception ex) {} } } // Unlimited Cauldron water // EventHandler registered in onPlayerInteract @BahHumbug(opt="unlimitedcauldron") public void onCauldronInteract(PlayerInteractEvent e) { if (!config_.get("unlimitedcauldron").getBool()) { return; } // block water going down on cauldrons if(e.getClickedBlock().getType() == Material.CAULDRON && e.getMaterial() == Material.GLASS_BOTTLE && e.getAction() == Action.RIGHT_CLICK_BLOCK) { Block block = e.getClickedBlock(); if(block.getData() > 0) { block.setData((byte)(block.getData()+1)); } } } // Quartz from Gravel @BahHumbug(opt="quartz_gravel_percentage", type=OptType.Int) @EventHandler(ignoreCancelled=true, priority = EventPriority.HIGHEST) public void onGravelBreak(BlockBreakEvent e) { if(e.getBlock().getType() != Material.GRAVEL || config_.get("quartz_gravel_percentage").getInt() <= 0) { return; } if(prng_.nextInt(100) < config_.get("quartz_gravel_percentage").getInt()) { e.setCancelled(true); e.getBlock().setType(Material.AIR); e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation(), new ItemStack(Material.QUARTZ, 1)); } } // Portals @BahHumbug(opt="portalcreate", def="true") @EventHandler(ignoreCancelled=true) public void onPortalCreate(PortalCreateEvent e) { if (!config_.get("portalcreate").getBool()) { e.setCancelled(true); } } @EventHandler(ignoreCancelled=true) public void onEntityPortalCreate(EntityCreatePortalEvent e) { if (!config_.get("portalcreate").getBool()) { e.setCancelled(true); } } // EnderDragon @BahHumbug(opt="enderdragon", def="true") @EventHandler(ignoreCancelled=true) public void onDragonSpawn(CreatureSpawnEvent e) { if (e.getEntityType() == EntityType.ENDER_DRAGON && !config_.get("enderdragon").getBool()) { e.setCancelled(true); } } // Join/Quit/Kick messages @BahHumbug(opt="joinquitkick", def="true") @EventHandler(priority=EventPriority.HIGHEST) public void onJoin(PlayerJoinEvent e) { if (!config_.get("joinquitkick").getBool()) { e.setJoinMessage(null); } } @EventHandler(priority=EventPriority.HIGHEST) public void onQuit(PlayerQuitEvent e) { EmptyEnderChest(e.getPlayer()); if (!config_.get("joinquitkick").getBool()) { e.setQuitMessage(null); } } @EventHandler(priority=EventPriority.HIGHEST) public void onKick(PlayerKickEvent e) { EmptyEnderChest(e.getPlayer()); if (!config_.get("joinquitkick").getBool()) { e.setLeaveMessage(null); } } // Death Messages @BahHumbugs({ @BahHumbug(opt="deathannounce", def="true"), @BahHumbug(opt="deathlog"), @BahHumbug(opt="deathpersonal"), @BahHumbug(opt="deathred"), @BahHumbug(opt="ender_backpacks") }) @EventHandler(priority=EventPriority.HIGHEST) public void onDeath(PlayerDeathEvent e) { final boolean logMsg = config_.get("deathlog").getBool(); final boolean sendPersonal = config_.get("deathpersonal").getBool(); final Player player = e.getEntity(); EmptyEnderChest(player); if (logMsg || sendPersonal) { Location location = player.getLocation(); String msg = String.format( "%s ([%s] %d, %d, %d)", e.getDeathMessage(), location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); if (logMsg) { info(msg); } if (sendPersonal) { e.getEntity().sendMessage(ChatColor.RED + msg); } } if (!config_.get("deathannounce").getBool()) { e.setDeathMessage(null); } else if (config_.get("deathred").getBool()) { e.setDeathMessage(ChatColor.RED + e.getDeathMessage()); } } // Endermen Griefing @BahHumbug(opt="endergrief", def="true") @EventHandler(ignoreCancelled=true) public void onEndermanGrief(EntityChangeBlockEvent e) { if (!config_.get("endergrief").getBool() && e.getEntity() instanceof Enderman) { e.setCancelled(true); } } // Wither Insta-breaking and Explosions @BahHumbug(opt="wither_insta_break") @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onEntityChangeBlock(EntityChangeBlockEvent event) { if (config_.get("wither_insta_break").getBool()) { return; } Entity npc = event.getEntity(); if (npc == null) { return; } EntityType npc_type = npc.getType(); if (npc_type.equals(EntityType.WITHER)) { event.setCancelled(true); } } @BahHumbug(opt="wither_explosions") @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onEntityExplode(EntityExplodeEvent event) { if (config_.get("wither_explosions").getBool()) { return; } Entity npc = event.getEntity(); if (npc == null) { return; } EntityType npc_type = npc.getType(); if ((npc_type.equals(EntityType.WITHER) || npc_type.equals(EntityType.WITHER_SKULL))) { event.blockList().clear(); } } @BahHumbug(opt="wither", def="true") @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onWitherSpawn(CreatureSpawnEvent event) { if (config_.get("wither").getBool()) { return; } if (!event.getEntityType().equals(EntityType.WITHER)) { return; } event.setCancelled(true); } // Prevent specified items from dropping off mobs public void removeItemDrops(EntityDeathEvent event) { if (!config_.doRemoveItemDrops()) { return; } if (event.getEntity() instanceof Player) { return; } Set<Integer> remove_ids = config_.getRemoveItemDrops(); List<ItemStack> drops = event.getDrops(); ItemStack item; int i = drops.size() - 1; while (i >= 0) { item = drops.get(i); if (remove_ids.contains(item.getTypeId())) { drops.remove(i); } --i; } } // Spawn more Wither Skeletons and Ghasts @BahHumbugs ({ @BahHumbug(opt="extra_ghast_spawn_rate", type=OptType.Int), @BahHumbug(opt="extra_wither_skele_spawn_rate", type=OptType.Int), @BahHumbug(opt="portal_extra_ghast_spawn_rate", type=OptType.Int), @BahHumbug(opt="portal_extra_wither_skele_spawn_rate", type=OptType.Int), @BahHumbug(opt="portal_pig_spawn_multiplier", type=OptType.Int) }) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled=true) public void spawnMoreHellMonsters(CreatureSpawnEvent e) { final Location loc = e.getLocation(); final World world = loc.getWorld(); boolean portalSpawn = false; final int blockType = world.getBlockTypeIdAt(loc); if (blockType == 90 || blockType == 49) { // >= because we are preventing instead of spawning if(prng_.nextInt(1000000) >= config_.get("portal_pig_spawn_multiplier").getInt()) { e.setCancelled(true); return; } portalSpawn = true; } if (config_.get("extra_wither_skele_spawn_rate").getInt() <= 0 && config_.get("extra_ghast_spawn_rate").getInt() <= 0) { return; } if (e.getEntityType() == EntityType.PIG_ZOMBIE) { int adjustedwither; int adjustedghast; if (portalSpawn) { adjustedwither = config_.get("portal_extra_wither_skele_spawn_rate").getInt(); adjustedghast = config_.get("portal_extra_ghast_spawn_rate").getInt(); } else { adjustedwither = config_.get("extra_wither_skele_spawn_rate").getInt(); adjustedghast = config_.get("extra_ghast_spawn_rate").getInt(); } if(prng_.nextInt(1000000) < adjustedwither) { e.setCancelled(true); world.spawnEntity(loc, EntityType.SKELETON); } else if(prng_.nextInt(1000000) < adjustedghast) { e.setCancelled(true); int x = loc.getBlockX(); int z = loc.getBlockZ(); List<Integer> heights = new ArrayList<Integer>(16); int lastBlockHeight = 2; int emptyCount = 0; int maxHeight = world.getMaxHeight(); for (int y = 2; y < maxHeight; ++y) { Block block = world.getBlockAt(x, y, z); if (block.isEmpty()) { ++emptyCount; if (emptyCount == 11) { heights.add(lastBlockHeight + 2); } } else { lastBlockHeight = y; emptyCount = 0; } } if (heights.size() <= 0) { return; } loc.setY(heights.get(prng_.nextInt(heights.size()))); world.spawnEntity(loc, EntityType.GHAST); } } else if (e.getEntityType() == EntityType.SKELETON && e.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM) { Entity entity = e.getEntity(); if (entity instanceof Skeleton) { Skeleton skele = (Skeleton)entity; skele.setSkeletonType(SkeletonType.WITHER); EntityEquipment entity_equip = skele.getEquipment(); entity_equip.setItemInHand(new ItemStack(Material.STONE_SWORD)); entity_equip.setItemInHandDropChance(0.0F); } } } // Wither Skull drop rate public static final int skull_id_ = Material.SKULL_ITEM.getId(); public static final byte wither_skull_data_ = 1; @BahHumbug(opt="wither_skull_drop_rate", type=OptType.Int) public void adjustWitherSkulls(EntityDeathEvent event) { Entity entity = event.getEntity(); if (!(entity instanceof Skeleton)) { return; } int rate = config_.get("wither_skull_drop_rate").getInt(); if (rate < 0 || rate > 1000000) { return; } Skeleton skele = (Skeleton)entity; if (skele.getSkeletonType() != SkeletonType.WITHER) { return; } List<ItemStack> drops = event.getDrops(); ItemStack item; int i = drops.size() - 1; while (i >= 0) { item = drops.get(i); if (item.getTypeId() == skull_id_ && item.getData().getData() == wither_skull_data_) { drops.remove(i); } --i; } if (rate - prng_.nextInt(1000000) <= 0) { return; } item = new ItemStack(Material.SKULL_ITEM); item.setAmount(1); item.setDurability((short)wither_skull_data_); drops.add(item); } // Fix a few issues with pearls, specifically pearls in unloaded chunks and slime blocks. @BahHumbug(opt="remove_pearls_chunks", type=OptType.Bool, def = "true") @EventHandler() public void onChunkUnloadEvent(ChunkUnloadEvent event){ Entity[] entities = event.getChunk().getEntities(); for (Entity ent: entities) if (ent.getType() == EntityType.ENDER_PEARL) ent.remove(); } private void registerTimerForPearlCheck(){ Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){ @Override public void run() { for (Entity ent: pearlTime.keySet()){ if (pearlTime.get(ent).booleanValue()){ ent.remove(); } else pearlTime.put(ent, true); } } }, 100, 200); } private Map<Entity, Boolean> pearlTime = new HashMap<Entity, Boolean>(); public void onPearlLastingTooLong(EntityInteractEvent event){ if (event.getEntityType() != EntityType.ENDER_PEARL) return; Entity ent = event.getEntity(); pearlTime.put(ent, false); } // Generic mob drop rate adjustment @BahHumbug(opt="disable_xp_orbs", type=OptType.Bool, def = "true") public void adjustMobItemDrops(EntityDeathEvent event){ Entity mob = event.getEntity(); if (mob instanceof Player){ return; } // Try specific multiplier, if that doesn't exist use generic EntityType mob_type = mob.getType(); int multiplier = config_.getLootMultiplier(mob_type.toString()); if (multiplier < 0) { multiplier = config_.getLootMultiplier("generic"); } //set entity death xp to zero so they don't drop orbs if(config_.get("disable_xp_orbs").getBool()){ event.setDroppedExp(0); } //if a dropped item was in the mob's inventory, drop only one, otherwise drop the amount * the multiplier LivingEntity liveMob = (LivingEntity) mob; EntityEquipment mobEquipment = liveMob.getEquipment(); ItemStack[] eeItem = mobEquipment.getArmorContents(); for (ItemStack item : event.getDrops()) { boolean armor = false; boolean hand = false; for(ItemStack i : eeItem){ if(i.isSimilar(item)){ armor = true; item.setAmount(1); } } if(item.isSimilar(mobEquipment.getItemInHand())){ hand = true; item.setAmount(1); } if(!hand && !armor){ int amount = item.getAmount() * multiplier; item.setAmount(amount); } } } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onEntityDeathEvent(EntityDeathEvent event) { removeItemDrops(event); adjustWitherSkulls(event); adjustMobItemDrops(event); } // Enchanted Golden Apple public boolean isEnchantedGoldenApple(ItemStack item) { // Golden Apples are GOLDEN_APPLE with 0 durability // Enchanted Golden Apples are GOLDEN_APPLE with 1 durability if (item == null) { return false; } if (item.getDurability() != 1) { return false; } Material material = item.getType(); return material.equals(Material.GOLDEN_APPLE); } public void replaceEnchantedGoldenApple( String player_name, ItemStack item, int inventory_max_stack_size) { if (!isEnchantedGoldenApple(item)) { return; } int stack_size = max_golden_apple_stack_; if (inventory_max_stack_size < max_golden_apple_stack_) { stack_size = inventory_max_stack_size; } info(String.format( "Replaced %d Enchanted with %d Normal Golden Apples for %s", item.getAmount(), stack_size, player_name)); item.setDurability((short)0); item.setAmount(stack_size); } @BahHumbug(opt="ench_gold_app_craftable", def = "false") public void removeRecipies() { if (config_.get("ench_gold_app_craftable").getBool()) { return; } Iterator<Recipe> it = getServer().recipeIterator(); while (it.hasNext()) { Recipe recipe = it.next(); ItemStack resulting_item = recipe.getResult(); if (!config_.get("ench_gold_app_craftable").getBool() && isEnchantedGoldenApple(resulting_item)) { it.remove(); info("Enchanted Golden Apple Recipe disabled"); } } } // EventHandler registered in onPlayerInteractAll @BahHumbug(opt="ench_gold_app_edible") public void onPlayerEatGoldenApple(PlayerInteractEvent event) { // The event when eating is cancelled before even LOWEST fires when the // player clicks on AIR. if (config_.get("ench_gold_app_edible").getBool()) { return; } Player player = event.getPlayer(); Inventory inventory = player.getInventory(); ItemStack item = event.getItem(); replaceEnchantedGoldenApple( player.getName(), item, inventory.getMaxStackSize()); } // Fix entities going through portals // This needs to be removed when updated to citadel 3.0 @BahHumbug(opt="disable_entities_portal", type = OptType.Bool, def = "true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void entityPortalEvent(EntityPortalEvent event){ event.setCancelled(config_.get("disable_entities_portal").getBool()); } // Enchanted Book public boolean isNormalBook(ItemStack item) { if (item == null) { return false; } Material material = item.getType(); return material.equals(Material.BOOK); } @BahHumbug(opt="ench_book_craftable") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onPrepareItemEnchantEvent(PrepareItemEnchantEvent event) { if (config_.get("ench_book_craftable").getBool()) { return; } ItemStack item = event.getItem(); if (isNormalBook(item)) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onEnchantItemEvent(EnchantItemEvent event) { if (config_.get("ench_book_craftable").getBool()) { return; } ItemStack item = event.getItem(); if (isNormalBook(item)) { event.setCancelled(true); Player player = event.getEnchanter(); warning( "Prevented book enchant. This should not trigger. Watch player " + player.getName()); } } // Stop Cobble generation from lava+water private static final BlockFace[] faces_ = new BlockFace[] { BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN }; private BlockFace WaterAdjacentLava(Block lava_block) { for (BlockFace face : faces_) { Block block = lava_block.getRelative(face); Material material = block.getType(); if (material.equals(Material.WATER) || material.equals(Material.STATIONARY_WATER)) { return face; } } return BlockFace.SELF; } public void ConvertLava(final Block block) { int data = (int)block.getData(); if (data == 0) { return; } Material material = block.getType(); if (!material.equals(Material.LAVA) && !material.equals(Material.STATIONARY_LAVA)) { return; } if (isLavaSourceNear(block, 3)) { return; } BlockFace face = WaterAdjacentLava(block); if (face == BlockFace.SELF) { return; } Bukkit.getScheduler().runTask(this, new Runnable() { @Override public void run() { block.setType(Material.AIR); } }); } public boolean isLavaSourceNear(Block block, int ttl) { int data = (int)block.getData(); if (data == 0) { Material material = block.getType(); if (material.equals(Material.LAVA) || material.equals(Material.STATIONARY_LAVA)) { return true; } } if (ttl <= 0) { return false; } for (BlockFace face : faces_) { Block child = block.getRelative(face); if (isLavaSourceNear(child, ttl - 1)) { return true; } } return false; } public void LavaAreaCheck(Block block, int ttl) { ConvertLava(block); if (ttl <= 0) { return; } for (BlockFace face : faces_) { Block child = block.getRelative(face); LavaAreaCheck(child, ttl - 1); } } @BahHumbugs ({ @BahHumbug(opt="cobble_from_lava"), @BahHumbug(opt="cobble_from_lava_scan_radius", type=OptType.Int, def="0") }) @EventHandler(priority = EventPriority.LOWEST) public void onBlockPhysicsEvent(BlockPhysicsEvent event) { if (config_.get("cobble_from_lava").getBool()) { return; } Block block = event.getBlock(); LavaAreaCheck(block, config_.get("cobble_from_lava_scan_radius").getInt()); } // Counteract 1.4.6 protection enchant nerf @BahHumbug(opt="scale_protection_enchant", def="true") @EventHandler(priority = EventPriority.LOWEST) // ignoreCancelled=false public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { if (!config_.get("scale_protection_enchant").getBool()) { return; } double damage = event.getDamage(); if (damage <= 0.0000001D) { return; } DamageCause cause = event.getCause(); if (!cause.equals(DamageCause.ENTITY_ATTACK) && !cause.equals(DamageCause.PROJECTILE)) { return; } Entity entity = event.getEntity(); if (!(entity instanceof Player)) { return; } Player defender = (Player)entity; PlayerInventory inventory = defender.getInventory(); int enchant_level = 0; for (ItemStack armor : inventory.getArmorContents()) { enchant_level += armor.getEnchantmentLevel(Enchantment.PROTECTION_ENVIRONMENTAL); } int damage_adjustment = 0; if (enchant_level >= 3 && enchant_level <= 6) { // 0 to 2 damage_adjustment = prng_.nextInt(3); } else if (enchant_level >= 7 && enchant_level <= 10) { // 0 to 3 damage_adjustment = prng_.nextInt(4); } else if (enchant_level >= 11 && enchant_level <= 14) { // 1 to 4 damage_adjustment = prng_.nextInt(4) + 1; } else if (enchant_level >= 15) { // 2 to 4 damage_adjustment = prng_.nextInt(3) + 2; } damage = Math.max(damage - (double)damage_adjustment, 0.0D); event.setDamage(damage); } @BahHumbug(opt="player_max_health", type=OptType.Int, def="20") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onPlayerJoinEvent(PlayerJoinEvent event) { Player player = event.getPlayer(); player.setMaxHealth((double)config_.get("player_max_health").getInt()); } // Fix dupe bug with chests and other containers @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void blockExplodeEvent(EntityExplodeEvent event) { List<HumanEntity> humans = new ArrayList<HumanEntity>(); for (Block block: event.blockList()) { if (block.getState() instanceof InventoryHolder) { InventoryHolder holder = (InventoryHolder) block.getState(); for (HumanEntity ent: holder.getInventory().getViewers()) { humans.add(ent); } } } for (HumanEntity human: humans) { human.closeInventory(); } } // Prevent entity dup bug @BahHumbug(opt="fix_rail_dup_bug", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onPistonPushRail(BlockPistonExtendEvent e) { if (!config_.get("fix_rail_dup_bug").getBool()) { return; } for (Block b : e.getBlocks()) { Material t = b.getType(); if (t == Material.RAILS || t == Material.POWERED_RAIL || t == Material.DETECTOR_RAIL) { e.setCancelled(true); return; } } } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onRailPlace(BlockPlaceEvent e) { if (!config_.get("fix_rail_dup_bug").getBool()) { return; } Block b = e.getBlock(); Material t = b.getType(); if (t == Material.RAILS || t == Material.POWERED_RAIL || t == Material.DETECTOR_RAIL) { for (BlockFace face : faces_) { t = b.getRelative(face).getType(); if (t == Material.PISTON_STICKY_BASE || t == Material.PISTON_EXTENSION || t == Material.PISTON_MOVING_PIECE || t == Material.PISTON_BASE) { e.setCancelled(true); return; } } } } // Combat Tag players on server join @BahHumbug(opt="tag_on_join", def="true") @EventHandler public void tagOnJoin(PlayerJoinEvent event){ if(!config_.get("tag_on_join").getBool()) { return; } // Delay two ticks to tag after secure login has been denied. // This opens a 1 tick window for a cheater to login and grab // server info, which should be detectable and bannable. final Player loginPlayer = event.getPlayer(); Bukkit.getScheduler().runTaskLater(this, new Runnable() { @Override public void run() { combatTag_.tagPlayer(loginPlayer.getName()); loginPlayer.sendMessage("You have been Combat Tagged on Login"); } }, 2L); } // Give introduction book to n00bs private Set<String> playersWithN00bBooks_ = new TreeSet<String>(); @BahHumbug(opt="drop_newbie_book", def="true") @EventHandler(priority=EventPriority.HIGHEST) public void onPlayerDeathBookDrop(PlayerDeathEvent e) { if (!config_.get("drop_newbie_book").getBool()) { return; } final String playerName = e.getEntity().getName(); List<ItemStack> dropList = e.getDrops(); for (int i = 0; i < dropList.size(); ++i) { final ItemStack item = dropList.get(i); if (item.getType().equals(Material.WRITTEN_BOOK)) { final BookMeta bookMeta = (BookMeta)item.getItemMeta(); if (bookMeta.getTitle().equals(config_.getTitle())) { playersWithN00bBooks_.add(playerName); dropList.remove(i); return; } } } playersWithN00bBooks_.remove(playerName); } @EventHandler public void onGiveBookOnRespawn(PlayerRespawnEvent event) { if (!config_.get("drop_newbie_book").getBool()) { return; } final Player player = event.getPlayer(); final String playerName = player.getName(); if (!playersWithN00bBooks_.contains(playerName)) { return; } playersWithN00bBooks_.remove(playerName); giveN00bBook(player); } @EventHandler public void onGiveBookOnJoin(PlayerJoinEvent event) { if (!config_.get("drop_newbie_book").getBool()) { return; } final Player player = event.getPlayer(); final String playerName = player.getName(); if (player.hasPlayedBefore() && !playersWithN00bBooks_.contains(playerName)) { return; } playersWithN00bBooks_.remove(playerName); giveN00bBook(player); } public void giveN00bBook(Player player) { Inventory inv = player.getInventory(); inv.addItem(createN00bBook()); } public ItemStack createN00bBook() { ItemStack book = new ItemStack(Material.WRITTEN_BOOK); BookMeta sbook = (BookMeta)book.getItemMeta(); sbook.setTitle(config_.getTitle()); sbook.setAuthor(config_.getAuthor()); sbook.setPages(config_.getPages()); book.setItemMeta(sbook); return book; } public boolean checkForInventorySpace(Inventory inv, int emptySlots) { int foundEmpty = 0; final int end = inv.getSize(); for (int slot = 0; slot < end; ++slot) { ItemStack item = inv.getItem(slot); if (item == null) { ++foundEmpty; } else if (item.getType().equals(Material.AIR)) { ++foundEmpty; } } return foundEmpty >= emptySlots; } public void giveHolidayPackage(Player player) { int count = 0; Inventory inv = player.getInventory(); while (checkForInventorySpace(inv, 4)) { inv.addItem(createHolidayBook()); inv.addItem(createFruitcake()); inv.addItem(createTurkey()); inv.addItem(createCoal()); ++count; } info(String.format("%s generated %d packs of holiday cheer.", player.getName(), count)); } public ItemStack createHolidayBook() { ItemStack book = new ItemStack(Material.WRITTEN_BOOK); BookMeta sbook = (BookMeta)book.getItemMeta(); sbook.setTitle(config_.getHolidayTitle()); sbook.setAuthor(config_.getHolidayAuthor()); sbook.setPages(config_.getHolidayPages()); List<String> lore = new ArrayList<String>(1); lore.add("December 25th, 2013"); sbook.setLore(lore); book.setItemMeta(sbook); return book; } public ItemStack createFruitcake() { ItemStack cake = new ItemStack(Material.CAKE); ItemMeta meta = cake.getItemMeta(); meta.setDisplayName("Fruitcake"); List<String> lore = new ArrayList<String>(1); lore.add("Deliciously stale"); meta.setLore(lore); cake.setItemMeta(meta); return cake; } private String[] turkey_names_ = new String[] { "Turkey", "Turkey", "Turkey", "Turducken", "Tofurkey", "Cearc Frangach", "Dinde", "Kalkoen", "Indeyka", "Pollo d'India", "Pelehu", "Chilmyeonjo" }; public ItemStack createTurkey() { String turkey_name = turkey_names_[prng_.nextInt(turkey_names_.length)]; ItemStack turkey = new ItemStack(Material.COOKED_CHICKEN); ItemMeta meta = turkey.getItemMeta(); meta.setDisplayName(turkey_name); List<String> lore = new ArrayList<String>(1); lore.add("Tastes like chicken"); meta.setLore(lore); turkey.setItemMeta(meta); return turkey; } public ItemStack createCoal() { ItemStack coal = new ItemStack(Material.COAL); ItemMeta meta = coal.getItemMeta(); List<String> lore = new ArrayList<String>(1); lore.add("You've been naughty"); meta.setLore(lore); coal.setItemMeta(meta); return coal; } // Playing records in jukeboxen? Gone // EventHandler registered in onPlayerInteract @BahHumbug(opt="disallow_record_playing", def="true") public void onRecordInJukebox(PlayerInteractEvent event) { if (!config_.get("disallow_record_playing").getBool()) { return; } Block cb = event.getClickedBlock(); if (cb == null || cb.getType() != Material.JUKEBOX) { return; } ItemStack his = event.getItem(); if(his != null && his.getType().isRecord()) { event.setCancelled(true); } } // Water in the nether? Nope. @BahHumbugs ({ @BahHumbug(opt="allow_water_in_nether"), @BahHumbug(opt="indestructible_end_portals", def="true") }) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerBucketEmptyEvent(PlayerBucketEmptyEvent e) { if(!config_.get("allow_water_in_nether").getBool()) { if( ( e.getBlockClicked().getBiome() == Biome.HELL ) && ( e.getBucket() == Material.WATER_BUCKET ) ) { e.setCancelled(true); e.getItemStack().setType(Material.BUCKET); e.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING, 5, 1)); } } if (config_.get("indestructible_end_portals").getBool()) { Block baseBlock = e.getBlockClicked(); BlockFace face = e.getBlockFace(); Block block = baseBlock.getRelative(face); if (block.getType() == Material.ENDER_PORTAL) { e.setCancelled(true); } } } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockFromToEvent(BlockFromToEvent e) { if(!config_.get("allow_water_in_nether").getBool()) { if( e.getToBlock().getBiome() == Biome.HELL ) { if( ( e.getBlock().getType() == Material.WATER ) || ( e.getBlock().getType() == Material.STATIONARY_WATER ) ) { e.setCancelled(true); } } } if (config_.get("indestructible_end_portals").getBool()) { if (e.getToBlock().getType() == Material.ENDER_PORTAL) { e.setCancelled(true); } } if(!e.isCancelled() && config_.get("obsidian_generator").getBool()) { generateObsidian(e); } } // Generates obsidian like it did in 1.7. // Note that this does not change anything in versions where obsidian generation exists. @BahHumbug(opt="obsidian_generator", def="false") public void generateObsidian(BlockFromToEvent event) { if(!event.getBlock().getType().equals(Material.STATIONARY_LAVA)) { return; } if(!event.getToBlock().getType().equals(Material.TRIPWIRE)) { return; } Block string = event.getToBlock(); if(!(string.getRelative(BlockFace.NORTH).getType().equals(Material.STATIONARY_WATER) || string.getRelative(BlockFace.EAST).getType().equals(Material.STATIONARY_WATER) || string.getRelative(BlockFace.WEST).getType().equals(Material.STATIONARY_WATER) || string.getRelative(BlockFace.SOUTH).getType().equals(Material.STATIONARY_WATER))) { return; } string.setType(Material.OBSIDIAN); } // Stops perculators private Map<Chunk, Integer> waterChunks = new HashMap<Chunk, Integer>(); BukkitTask waterSchedule = null; @BahHumbugs ({ @BahHumbug(opt="max_water_lava_height", def="100", type=OptType.Int), @BahHumbug(opt="max_water_lava_amount", def = "400", type=OptType.Int), @BahHumbug(opt="max_water_lava_timer", def = "1200", type=OptType.Int) }) @EventHandler(priority = EventPriority.LOWEST) public void stopLiquidMoving(BlockFromToEvent event){ try { Block to = event.getToBlock(); Block from = event.getBlock(); if (to.getLocation().getBlockY() < config_.get("max_water_lava_height").getInt()) { return; } Material mat = from.getType(); if (!(mat.equals(Material.WATER) || mat.equals(Material.STATIONARY_WATER) || mat.equals(Material.LAVA) || mat.equals(Material.STATIONARY_LAVA))) { return; } Chunk c = to.getChunk(); if (!waterChunks.containsKey(c)){ waterChunks.put(c, 0); } Integer i = waterChunks.get(c); i = i + 1; waterChunks.put(c, i); int amount = getWaterInNearbyChunks(c); if (amount > config_.get("max_water_lava_amount").getInt()) { event.setCancelled(true); } if (waterSchedule != null) { return; } waterSchedule = Bukkit.getScheduler().runTaskLater(this, new Runnable(){ @Override public void run() { waterChunks.clear(); waterSchedule = null; } }, config_.get("max_water_lava_timer").getInt()); } catch (Exception e){ getLogger().log(Level.INFO, "Tried getting info from a chunk before it generated, skipping."); return; } } public int getWaterInNearbyChunks(Chunk chunk){ World world = chunk.getWorld(); Chunk[] chunks = { world.getChunkAt(chunk.getX(), chunk.getZ()), world.getChunkAt(chunk.getX()-1, chunk.getZ()), world.getChunkAt(chunk.getX(), chunk.getZ()-1), world.getChunkAt(chunk.getX()-1, chunk.getZ()-1), world.getChunkAt(chunk.getX()+1, chunk.getZ()), world.getChunkAt(chunk.getX(), chunk.getZ()+1), world.getChunkAt(chunk.getX()+1, chunk.getZ()+1), world.getChunkAt(chunk.getX()-1, chunk.getZ()+1), world.getChunkAt(chunk.getX()+1, chunk.getZ()-1) }; int count = 0; for (Chunk c: chunks){ Integer amount = waterChunks.get(c); if (amount == null) continue; count += amount; } return count; } // Changes Strength Potions, strength_multiplier 3 is roughly Pre-1.6 Level @BahHumbugs ({ @BahHumbug(opt="nerf_strength", def="true"), @BahHumbug(opt="strength_multiplier", type=OptType.Int, def="3") }) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPlayerDamage(EntityDamageByEntityEvent event) { if (!config_.get("nerf_strength").getBool()) { return; } if (!(event.getDamager() instanceof Player)) { return; } Player player = (Player)event.getDamager(); final int strengthMultiplier = config_.get("strength_multiplier").getInt(); if (player.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) { for (PotionEffect effect : player.getActivePotionEffects()) { if (effect.getType().equals(PotionEffectType.INCREASE_DAMAGE)) { final int potionLevel = effect.getAmplifier() + 1; final double unbuffedDamage = event.getDamage() / (1.3 * potionLevel + 1); final double newDamage = unbuffedDamage + (potionLevel * strengthMultiplier); event.setDamage(newDamage); break; } } } } // Buffs health splash to pre-1.6 levels @BahHumbug(opt="buff_health_pots", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPotionSplash(PotionSplashEvent event) { if (!config_.get("buff_health_pots").getBool()) { return; } for (PotionEffect effect : event.getEntity().getEffects()) { if (!(effect.getType().getName().equalsIgnoreCase("heal"))) { // Splash potion of poison return; } } for (LivingEntity entity : event.getAffectedEntities()) { if (entity instanceof Player) { if(((Damageable)entity).getHealth() > 0d) { final double newHealth = Math.min( ((Damageable)entity).getHealth() + 4.0D, ((Damageable)entity).getMaxHealth()); entity.setHealth(newHealth); } } } } // Bow shots cause slow debuff @BahHumbugs ({ @BahHumbug(opt="projectile_slow_chance", type=OptType.Int, def="30"), @BahHumbug(opt="projectile_slow_ticks", type=OptType.Int, def="100") }) @EventHandler public void onEDBE(EntityDamageByEntityEvent event) { int rate = config_.get("projectile_slow_chance").getInt(); if (rate <= 0 || rate > 100) { return; } if (!(event.getEntity() instanceof Player)) { return; } boolean damager_is_player_arrow = false; int chance_scaling = 0; Entity damager_entity = event.getDamager(); if (damager_entity != null) { // public LivingEntity CraftArrow.getShooter() // Playing this game to not have to take a hard dependency on // craftbukkit internals. try { Class<?> damager_class = damager_entity.getClass(); if (damager_class.getName().endsWith(".CraftArrow")) { Method getShooter = damager_class.getMethod("getShooter"); Object result = getShooter.invoke(damager_entity); if (result instanceof Player) { damager_is_player_arrow = true; String player_name = ((Player)result).getName(); if (bow_level_.containsKey(player_name)) { chance_scaling = bow_level_.get(player_name); } } } } catch(Exception ex) {} } if (!damager_is_player_arrow) { return; } rate += chance_scaling * 5; int percent = prng_.nextInt(100); if (percent < rate){ int ticks = config_.get("projectile_slow_ticks").getInt(); Player player = (Player)event.getEntity(); player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, ticks, 1, false)); } } // Used to track bow enchantment levels per player private Map<String, Integer> bow_level_ = new TreeMap<String, Integer>(); @EventHandler public void onEntityShootBow(EntityShootBowEvent event) { if (!(event.getEntity() instanceof Player)) { return; } int ench_level = 0; ItemStack bow = event.getBow(); Map<Enchantment, Integer> enchants = bow.getEnchantments(); for (Enchantment ench : enchants.keySet()) { int tmp_ench_level = 0; if (ench.equals(Enchantment.KNOCKBACK) || ench.equals(Enchantment.ARROW_KNOCKBACK)) { tmp_ench_level = enchants.get(ench) * 2; } else if (ench.equals(Enchantment.ARROW_DAMAGE)) { tmp_ench_level = enchants.get(ench); } if (tmp_ench_level > ench_level) { ench_level = tmp_ench_level; } } bow_level_.put( ((Player)event.getEntity()).getName(), ench_level); } // BottleO refugees // Changes the yield from an XP bottle @BahHumbugs ({ @BahHumbug(opt="disable_experience", def="true"), @BahHumbug(opt="xp_per_bottle", type=OptType.Int, def="10") }) @EventHandler(priority=EventPriority.HIGHEST) public void onExpBottleEvent(ExpBottleEvent event) { final int bottle_xp = config_.get("xp_per_bottle").getInt(); if (config_.get("disable_experience").getBool()) { ((Player) event.getEntity().getShooter()).giveExp(bottle_xp); event.setExperience(0); } else { event.setExperience(bottle_xp); } } // Diables all XP gain except when manually changed via code. @EventHandler public void onPlayerExpChangeEvent(PlayerExpChangeEvent event) { if (config_.get("disable_experience").getBool()) { event.setAmount(0); } } // Find the end portals public static final int ender_portal_id_ = Material.ENDER_PORTAL.getId(); public static final int ender_portal_frame_id_ = Material.ENDER_PORTAL_FRAME.getId(); private Set<Long> end_portal_scanned_chunks_ = new TreeSet<Long>(); @BahHumbug(opt="find_end_portals", type=OptType.String) @EventHandler public void onFindEndPortals(ChunkLoadEvent event) { String scanWorld = config_.get("find_end_portals").getString(); if (scanWorld.isEmpty()) { return; } World world = event.getWorld(); if (!world.getName().equalsIgnoreCase(scanWorld)) { return; } Chunk chunk = event.getChunk(); long chunk_id = (long)chunk.getX() << 32L + (long)chunk.getZ(); if (end_portal_scanned_chunks_.contains(chunk_id)) { return; } end_portal_scanned_chunks_.add(chunk_id); int chunk_x = chunk.getX() * 16; int chunk_end_x = chunk_x + 16; int chunk_z = chunk.getZ() * 16; int chunk_end_z = chunk_z + 16; int max_height = 0; for (int x = chunk_x; x < chunk_end_x; x += 3) { for (int z = chunk_z; z < chunk_end_z; ++z) { int height = world.getMaxHeight(); if (height > max_height) { max_height = height; } } } for (int y = 1; y <= max_height; ++y) { int z_adj = 0; for (int x = chunk_x; x < chunk_end_x; ++x) { for (int z = chunk_z + z_adj; z < chunk_end_z; z += 3) { int block_type = world.getBlockTypeIdAt(x, y, z); if (block_type == ender_portal_id_ || block_type == ender_portal_frame_id_) { info(String.format("End portal found at %d,%d", x, z)); return; } } // This funkiness results in only searching 48 of the 256 blocks on // each y-level. 81.25% fewer blocks checked. ++z_adj; if (z_adj >= 3) { z_adj = 0; x += 2; } } } } // Prevent inventory access while in a vehicle, unless it's the Player's @BahHumbugs ({ @BahHumbug(opt="prevent_opening_container_carts", def="true"), @BahHumbug(opt="prevent_vehicle_inventory_open", def="true") }) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPreventVehicleInvOpen(InventoryOpenEvent event) { // Cheap break-able conditional statement while (config_.get("prevent_vehicle_inventory_open").getBool()) { HumanEntity human = event.getPlayer(); if (!(human instanceof Player)) { break; } if (!human.isInsideVehicle()) { break; } InventoryHolder holder = event.getInventory().getHolder(); if (holder == human) { break; } event.setCancelled(true); break; } if (config_.get("prevent_opening_container_carts").getBool() && !event.isCancelled()) { InventoryHolder holder = event.getInventory().getHolder(); if (holder instanceof StorageMinecart || holder instanceof HopperMinecart) { event.setCancelled(true); } } } // Disable outbound hopper transfers @BahHumbug(opt="disable_hopper_out_transfers", def="false") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onInventoryMoveItem(InventoryMoveItemEvent event) { if (!config_.get("disable_hopper_out_transfers").getBool()) { return; } final Inventory src = event.getSource(); final InventoryHolder srcHolder = src.getHolder(); if (srcHolder instanceof Hopper) { event.setCancelled(true); return; } } // Adjust horse speeds @BahHumbug(opt="horse_speed", type=OptType.Double, def="0.170000") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onVehicleEnter(VehicleEnterEvent event) { // 0.17 is just a tad slower than minecarts Vehicle vehicle = event.getVehicle(); if (!(vehicle instanceof Horse)) { return; } Versioned.setHorseSpeed((Entity)vehicle, config_.get("horse_speed").getDouble()); } // Admins can view player inventories @SuppressWarnings("deprecation") public void onInvseeCommand(Player admin, String playerName) { final Player player = Bukkit.getPlayerExact(playerName); if (player == null) { admin.sendMessage("Player not found"); return; } final Inventory pl_inv = player.getInventory(); final Inventory inv = Bukkit.createInventory( admin, 36, playerName + "'s Inventory"); for (int slot = 0; slot < 36; slot++) { final ItemStack it = pl_inv.getItem(slot); inv.setItem(slot, it); } admin.openInventory(inv); admin.updateInventory(); } // Fix boats @BahHumbug(opt="prevent_self_boat_break", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPreventLandBoats(VehicleDestroyEvent event) { if (!config_.get("prevent_land_boats").getBool()) { return; } final Vehicle vehicle = event.getVehicle(); if (vehicle == null || !(vehicle instanceof Boat)) { return; } final Entity passenger = vehicle.getPassenger(); if (passenger == null || !(passenger instanceof Player)) { return; } final Entity attacker = event.getAttacker(); if (attacker == null) { return; } if (!attacker.getUniqueId().equals(passenger.getUniqueId())) { return; } final Player player = (Player)passenger; Humbug.info(String.format( "Player '%s' kicked for self damaging boat at %s", player.getName(), vehicle.getLocation().toString())); vehicle.eject(); vehicle.getWorld().dropItem(vehicle.getLocation(), new ItemStack(Material.BOAT)); vehicle.remove(); ((Player)passenger).kickPlayer("Nope"); } @BahHumbug(opt="prevent_land_boats", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPreventLandBoats(VehicleMoveEvent event) { if (!config_.get("prevent_land_boats").getBool()) { return; } final Vehicle vehicle = event.getVehicle(); if (vehicle == null || !(vehicle instanceof Boat)) { return; } final Entity passenger = vehicle.getPassenger(); if (passenger == null || !(passenger instanceof Player)) { return; } final Location to = event.getTo(); final Material boatOn = to.getBlock().getRelative(BlockFace.DOWN).getType(); if (boatOn.equals(Material.STATIONARY_WATER) || boatOn.equals(Material.WATER)) { return; } Humbug.info(String.format( "Player '%s' removed from land-boat at %s", ((Player)passenger).getName(), to.toString())); vehicle.eject(); vehicle.getWorld().dropItem(vehicle.getLocation(), new ItemStack(Material.BOAT)); vehicle.remove(); } // Fix minecarts public boolean checkForTeleportSpace(Location loc) { final Block block = loc.getBlock(); final Material mat = block.getType(); if (mat.isSolid()) { return false; } final Block above = block.getRelative(BlockFace.UP); if (above.getType().isSolid()) { return false; } return true; } public boolean tryToTeleport(Player player, Location location, String reason) { Location loc = location.clone(); loc.setX(Math.floor(loc.getX()) + 0.500000D); loc.setY(Math.floor(loc.getY()) + 0.02D); loc.setZ(Math.floor(loc.getZ()) + 0.500000D); final Location baseLoc = loc.clone(); final World world = baseLoc.getWorld(); // Check if teleportation here is viable boolean performTeleport = checkForTeleportSpace(loc); if (!performTeleport) { loc.setY(loc.getY() + 1.000000D); performTeleport = checkForTeleportSpace(loc); } if (performTeleport) { player.setVelocity(new Vector()); player.teleport(loc); Humbug.info(String.format( "Player '%s' %s: Teleported to %s", player.getName(), reason, loc.toString())); return true; } loc = baseLoc.clone(); // Create a sliding window of block types and track how many of those // are solid. Keep fetching the block below the current block to move down. int air_count = 0; LinkedList<Material> air_window = new LinkedList<Material>(); loc.setY((float)world.getMaxHeight() - 2); Block block = world.getBlockAt(loc); for (int i = 0; i < 4; ++i) { Material block_mat = block.getType(); if (!block_mat.isSolid()) { ++air_count; } air_window.addLast(block_mat); block = block.getRelative(BlockFace.DOWN); } // Now that the window is prepared, scan down the Y-axis. while (block.getY() >= 1) { Material block_mat = block.getType(); if (block_mat.isSolid()) { if (air_count == 4) { player.setVelocity(new Vector()); loc = block.getLocation(); loc.setX(Math.floor(loc.getX()) + 0.500000D); loc.setY(loc.getY() + 1.02D); loc.setZ(Math.floor(loc.getZ()) + 0.500000D); player.teleport(loc); Humbug.info(String.format( "Player '%s' %s: Teleported to %s", player.getName(), reason, loc.toString())); return true; } } else { // !block_mat.isSolid() ++air_count; } air_window.addLast(block_mat); if (!air_window.removeFirst().isSolid()) { --air_count; } block = block.getRelative(BlockFace.DOWN); } return false; } @BahHumbug(opt="prevent_ender_pearl_save", def="true") @EventHandler public void enderPearlSave(EnderPearlUnloadEvent event) { if(!config_.get("prevent_ender_pearl_save").getBool()) return; event.setCancelled(true); } @BahHumbug(opt="fix_vehicle_logout_bug", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true) public void onDisallowVehicleLogout(PlayerQuitEvent event) { if (!config_.get("fix_vehicle_logout_bug").getBool()) { return; } kickPlayerFromVehicle(event.getPlayer()); } public void kickPlayerFromVehicle(Player player) { Entity vehicle = player.getVehicle(); if (vehicle == null || !(vehicle instanceof Minecart || vehicle instanceof Horse || vehicle instanceof Arrow)) { return; } Location vehicleLoc = vehicle.getLocation(); // Vehicle data has been cached, now safe to kick the player out player.leaveVehicle(); if (!tryToTeleport(player, vehicleLoc, "logged out")) { player.setHealth(0.000000D); Humbug.info(String.format( "Player '%s' logged out in vehicle: Killed", player.getName())); } } @BahHumbug(opt="fix_minecart_reenter_bug", def="true") @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onFixMinecartReenterBug(VehicleExitEvent event) { if (!config_.get("fix_minecart_reenter_bug").getBool()) { return; } final Vehicle vehicle = event.getVehicle(); if (vehicle == null || !(vehicle instanceof Minecart)) { return; } final Entity passengerEntity = event.getExited(); if (passengerEntity == null || !(passengerEntity instanceof Player)) { return; } // Must delay the teleport 2 ticks or else the player's mis-managed // movement still occurs. With 1 tick it could still occur. final Player player = (Player)passengerEntity; final Location vehicleLoc = vehicle.getLocation(); Bukkit.getScheduler().runTaskLater(this, new Runnable() { @Override public void run() { if (!tryToTeleport(player, vehicleLoc, "exiting vehicle")) { player.setHealth(0.000000D); Humbug.info(String.format( "Player '%s' exiting vehicle: Killed", player.getName())); } } }, 2L); } @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onFixMinecartReenterBug(VehicleDestroyEvent event) { if (!config_.get("fix_minecart_reenter_bug").getBool()) { return; } final Vehicle vehicle = event.getVehicle(); if (vehicle == null || !(vehicle instanceof Minecart || vehicle instanceof Horse)) { return; } final Entity passengerEntity = vehicle.getPassenger(); if (passengerEntity == null || !(passengerEntity instanceof Player)) { return; } // Must delay the teleport 2 ticks or else the player's mis-managed // movement still occurs. With 1 tick it could still occur. final Player player = (Player)passengerEntity; final Location vehicleLoc = vehicle.getLocation(); Bukkit.getScheduler().runTaskLater(this, new Runnable() { @Override public void run() { if (!tryToTeleport(player, vehicleLoc, "in destroyed vehicle")) { player.setHealth(0.000000D); Humbug.info(String.format( "Player '%s' in destroyed vehicle: Killed", player.getName())); } } }, 2L); } // Adjust ender pearl gravity public final static int pearlId = 368; public final static MinecraftKey pearlKey = new MinecraftKey("ender_pearl"); @SuppressWarnings({ "rawtypes", "unchecked" }) @BahHumbug(opt="ender_pearl_gravity", type=OptType.Double, def="0.060000") private void hookEnderPearls() { try { // They thought they could stop us by preventing us from registering an // item. We'll show them Field idRegistryField = Item.REGISTRY.getClass().getDeclaredField("a"); idRegistryField.setAccessible(true); Object idRegistry = idRegistryField.get(Item.REGISTRY); Field idRegistryMapField = idRegistry.getClass().getDeclaredField("a"); idRegistryMapField.setAccessible(true); Object idRegistryMap = idRegistryMapField.get(idRegistry); Field idRegistryItemsField = idRegistry.getClass().getDeclaredField("b"); idRegistryItemsField.setAccessible(true); Object idRegistryItemList = idRegistryItemsField.get(idRegistry); // Remove ItemEnderPearl from the ID Registry Item idItem = null; Iterator<Item> itemListIter = ((List<Item>)idRegistryItemList).iterator(); while (itemListIter.hasNext()) { idItem = itemListIter.next(); if (idItem == null) { continue; } if (!(idItem instanceof ItemEnderPearl)) { continue; } itemListIter.remove(); break; } if (idItem != null) { ((Map<Item, Integer>)idRegistryMap).remove(idItem); } // Register our custom pearl Item. Item.REGISTRY.a(pearlId, pearlKey, new CustomNMSItemEnderPearl(config_)); // Setup the custom entity Field fieldStringToClass = EntityTypes.class.getDeclaredField("c"); Field fieldClassToString = EntityTypes.class.getDeclaredField("d"); fieldStringToClass.setAccessible(true); fieldClassToString.setAccessible(true); Field fieldClassToId = EntityTypes.class.getDeclaredField("f"); Field fieldStringToId = EntityTypes.class.getDeclaredField("g"); fieldClassToId.setAccessible(true); fieldStringToId.setAccessible(true); Map mapStringToClass = (Map)fieldStringToClass.get(null); Map mapClassToString = (Map)fieldClassToString.get(null); Map mapClassToId = (Map)fieldClassToId.get(null); Map mapStringToId = (Map)fieldStringToId.get(null); mapStringToClass.put("ThrownEnderpearl",CustomNMSEntityEnderPearl.class); mapStringToId.put("ThrownEnderpearl", Integer.valueOf(14)); mapClassToString.put(CustomNMSEntityEnderPearl.class, "ThrownEnderpearl"); mapClassToId.put(CustomNMSEntityEnderPearl.class, Integer.valueOf(14)); } catch (Exception e) { Humbug.severe("Exception while overriding MC's ender pearl class"); e.printStackTrace(); } } // Hunger Changes // Keep track if the player just ate. private Map<Player, Double> playerLastEat_ = new HashMap<Player, Double>(); @BahHumbug(opt="saturation_multiplier", type=OptType.Double, def="0.0") @EventHandler public void setSaturationOnFoodEat(PlayerItemConsumeEvent event) { // Each food sets a different saturation. final Player player = event.getPlayer(); ItemStack item = event.getItem(); Material mat = item.getType(); double multiplier = config_.get("saturation_multiplier").getDouble(); if (multiplier <= 0.000001 && multiplier >= -0.000001) { return; } switch(mat) { case APPLE: playerLastEat_.put(player, multiplier*2.4); case BAKED_POTATO: playerLastEat_.put(player, multiplier*7.2); case BREAD: playerLastEat_.put(player, multiplier*6); case CAKE: playerLastEat_.put(player, multiplier*0.4); case CARROT_ITEM: playerLastEat_.put(player, multiplier*4.8); case COOKED_FISH: playerLastEat_.put(player, multiplier*6); case GRILLED_PORK: playerLastEat_.put(player, multiplier*12.8); case COOKIE: playerLastEat_.put(player, multiplier*0.4); case GOLDEN_APPLE: playerLastEat_.put(player, multiplier*9.6); case GOLDEN_CARROT: playerLastEat_.put(player, multiplier*14.4); case MELON: playerLastEat_.put(player, multiplier*1.2); case MUSHROOM_SOUP: playerLastEat_.put(player, multiplier*7.2); case POISONOUS_POTATO: playerLastEat_.put(player, multiplier*1.2); case POTATO: playerLastEat_.put(player, multiplier*0.6); case RAW_FISH: playerLastEat_.put(player, multiplier*1); case PUMPKIN_PIE: playerLastEat_.put(player, multiplier*4.8); case RAW_BEEF: playerLastEat_.put(player, multiplier*1.8); case RAW_CHICKEN: playerLastEat_.put(player, multiplier*1.2); case PORK: playerLastEat_.put(player, multiplier*1.8); case ROTTEN_FLESH: playerLastEat_.put(player, multiplier*0.8); case SPIDER_EYE: playerLastEat_.put(player, multiplier*3.2); case COOKED_BEEF: playerLastEat_.put(player, multiplier*12.8); default: playerLastEat_.put(player, multiplier); Bukkit.getServer().getScheduler().runTaskLater(this, new Runnable() { // In case the player ingested a potion, this removes the // saturation from the list. Unsure if I have every item // listed. There is always the other cases of like food // that shares same id @Override public void run() { playerLastEat_.remove(player); } }, 80); } } @BahHumbug(opt="hunger_slowdown", type=OptType.Double, def="0.0") @EventHandler public void onFoodLevelChange(FoodLevelChangeEvent event) { final Player player = (Player) event.getEntity(); final double mod = config_.get("hunger_slowdown").getDouble(); Double saturation; if (playerLastEat_.containsKey(player)) { // if the player just ate saturation = playerLastEat_.get(player); if (saturation == null) { saturation = ((Float)player.getSaturation()).doubleValue(); } } else { saturation = Math.min( player.getSaturation() + mod, 20.0D + (mod * 2.0D)); } player.setSaturation(saturation.floatValue()); } //Remove Book Copying @BahHumbug(opt="copy_book_enable", def= "false") public void removeBooks() { if (config_.get("copy_book_enable").getBool()) { return; } Iterator<Recipe> it = getServer().recipeIterator(); while (it.hasNext()) { Recipe recipe = it.next(); ItemStack resulting_item = recipe.getResult(); if ( // !copy_book_enable_ && isWrittenBook(resulting_item)) { it.remove(); info("Copying Books disabled"); } } } public boolean isWrittenBook(ItemStack item) { if (item == null) { return false; } Material material = item.getType(); return material.equals(Material.WRITTEN_BOOK); } // Prevent tree growth wrap-around @BahHumbug(opt="prevent_tree_wraparound", def="true") @EventHandler(priority=EventPriority.LOWEST, ignoreCancelled = true) public void onStructureGrowEvent(StructureGrowEvent event) { if (!config_.get("prevent_tree_wraparound").getBool()) { return; } int maxY = 0, minY = 257; for (BlockState bs : event.getBlocks()) { final int y = bs.getLocation().getBlockY(); maxY = Math.max(maxY, y); minY = Math.min(minY, y); } if (maxY - minY > 240) { event.setCancelled(true); final Location loc = event.getLocation(); info(String.format("Prevented structure wrap-around at %d, %d, %d", loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); } } // General public void onLoad() { loadConfiguration(); //hookEnderPearls(); info("Loaded"); } public void onEnable() { registerEvents(); registerCommands(); removeRecipies(); removeBooks(); registerTimerForPearlCheck(); global_instance_ = this; info("Enabled"); } public void onDisable() { if (config_.get("fix_vehicle_logout_bug").getBool()) { for (World world: getServer().getWorlds()) { for (Player player: world.getPlayers()) { kickPlayerFromVehicle(player); } } } } public boolean isInitiaized() { return global_instance_ != null; } public boolean toBool(String value) { if (value.equals("1") || value.equalsIgnoreCase("true")) { return true; } return false; } public int toInt(String value, int default_value) { try { return Integer.parseInt(value); } catch(Exception e) { return default_value; } } public double toDouble(String value, double default_value) { try { return Double.parseDouble(value); } catch(Exception e) { return default_value; } } public int toMaterialId(String value, int default_value) { try { return Integer.parseInt(value); } catch(Exception e) { Material mat = Material.matchMaterial(value); if (mat != null) { return mat.getId(); } } return default_value; } public boolean onCommand( CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player && command.getName().equals("invsee")) { if (args.length < 1) { sender.sendMessage("Provide a name"); return false; } onInvseeCommand((Player)sender, args[0]); return true; } if (sender instanceof Player && command.getName().equals("introbook")) { if (!config_.get("drop_newbie_book").getBool()) { return true; } Player sendBookTo = (Player)sender; if (args.length >= 1) { Player possible = Bukkit.getPlayerExact(args[0]); if (possible != null) { sendBookTo = possible; } } giveN00bBook(sendBookTo); return true; } if (sender instanceof Player && command.getName().equals("bahhumbug")) { giveHolidayPackage((Player)sender); return true; } if (!(sender instanceof ConsoleCommandSender) || !command.getName().equals("humbug") || args.length < 1) { return false; } String option = args[0]; String value = null; String subvalue = null; boolean set = false; boolean subvalue_set = false; String msg = ""; if (args.length > 1) { value = args[1]; set = true; } if (args.length > 2) { subvalue = args[2]; subvalue_set = true; } ConfigOption opt = config_.get(option); if (opt != null) { if (set) { opt.set(value); } msg = String.format("%s = %s", option, opt.getString()); } else if (option.equals("debug")) { if (set) { config_.setDebug(toBool(value)); } msg = String.format("debug = %s", config_.getDebug()); } else if (option.equals("loot_multiplier")) { String entity_type = "generic"; if (set && subvalue_set) { entity_type = value; value = subvalue; } if (set) { config_.setLootMultiplier( entity_type, toInt(value, config_.getLootMultiplier(entity_type))); } msg = String.format( "loot_multiplier(%s) = %d", entity_type, config_.getLootMultiplier(entity_type)); } else if (option.equals("remove_mob_drops")) { if (set && subvalue_set) { if (value.equals("add")) { config_.addRemoveItemDrop(toMaterialId(subvalue, -1)); } else if (value.equals("del")) { config_.removeRemoveItemDrop(toMaterialId(subvalue, -1)); } } msg = String.format("remove_mob_drops = %s", config_.toDisplayRemoveItemDrops()); } else if (option.equals("save")) { config_.save(); msg = "Configuration saved"; } else if (option.equals("reload")) { config_.reload(); msg = "Configuration loaded"; } else { msg = String.format("Unknown option %s", option); } sender.sendMessage(msg); return true; } public void registerCommands() { ConsoleCommandSender console = getServer().getConsoleSender(); console.addAttachment(this, "humbug.console", true); } private void registerEvents() { getServer().getPluginManager().registerEvents(this, this); } private void loadConfiguration() { config_ = Config.initialize(this); } }
package csci432.camera; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import static java.lang.Runtime.getRuntime; public class RaspberryPiCam implements Camera{ private Integer picNumber; private final String saveLocation; public RaspberryPiCam(String saveLocation){ this.saveLocation = saveLocation; this.picNumber = 0; } @Override public void takePicture() { try { Process p = Runtime.getRuntime().exec("raspistill -o "+saveLocation + picNumber + ".jpg --nopreview --timeout 1"); p.waitFor(); } catch (IOException ex) { ex.printStackTrace(); } catch (InterruptedException ix) { ix.printStackTrace(); } picNumber++; } @Override public void takePictureOnInterval(Long pause, Long duration) { try { getRuntime().exec("raspistill -w 500 -h 500 -tl " + pause + " -t " + duration + " -o " + saveLocation + "original_%03d.jpg --nopreview"); } catch (IOException ex) { ex.printStackTrace(); } } /** * Gets an unfiltered image to filter * * @return an unfiltered image */ public BufferedImage getUnfilteredImage() { String location = String.format(saveLocation+"original_%1$03d.jpg", picNumber); BufferedImage image = null; try { image = ImageIO.read(new File(location)); picNumber++; } catch (IOException e) { System.out.println(location+ " image not taking yet, waiting..."); } finally { return image; } } }
package edu.ics.game.server; import java.util.HashMap; import java.util.UUID; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; public class GameLobby { private Class<? extends Game> gameClass; private HashMap<String,GameRoom> rooms = new HashMap<>(); private HashMap<UUID,GamePlayer> players = new HashMap<>(); public GameLobby(Class<? extends Game> gameClass) { this.gameClass = gameClass; } public Class<? extends Game> getGameClass() { return this.gameClass; } public JsonNode getState() { ObjectMapper mapper = new ObjectMapper(); ObjectNode state = mapper.createObjectNode(); state.put("name", this.gameClass.getSimpleName()); ArrayNode rooms = state.putArray("rooms"); for (GameRoom room : this.rooms.values()) { rooms.add(room.getState(false)); } ArrayNode players = state.putArray("players"); for (GamePlayer player : this.players.values()) { players.add(player.getState()); } return state; } public GamePlayer addPlayerByUUID(UUID uuid) { GamePlayer player = new GamePlayer(uuid); this.players.put(uuid, player); return player; } public GamePlayer getPlayerByUUID(UUID uuid) { return this.players.get(uuid); } public void removePlayerByUUID(UUID uuid) { this.players.remove(uuid); } public GameRoom addRoomByName(String name) { GameRoom room = new GameRoom(this.gameClass, name); this.rooms.put(name, room); return room; } public GameRoom getRoomByName(String name) { return this.rooms.get(name); } public void removeRoomByName(String name) { this.rooms.remove(name); } public void joinRoom(UUID uuid, String name) { GamePlayer player = this.getPlayerByUUID(uuid); GameRoom room = this.getRoomByName(name); if (room == null) { room = this.addRoomByName(name); } room.addPlayer(player); player.enterRoom(room); } public void leaveRoom(UUID uuid, String name) { GamePlayer player = this.getPlayerByUUID(uuid); GameRoom room = this.getRoomByName(name); if (room != null) { room.removePlayer(player); player.leaveRoom(room); // Destroy the room if no one is in it. if (room.getPlayers().size() == 0) { this.removeRoomByName(name); } } } }
package info.freelibrary.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.jar.JarFile; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.ImageOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utilities for working with IO streams. * * @author <a href="mailto:ksclarke@ksclarke.io">Kevin S. Clarke</a> */ public class IOUtils { private static final Logger LOGGER = LoggerFactory.getLogger(IOUtils.class); private IOUtils() { } /** * Closes a reader, catching and logging any exceptions. * * @param aReader A supplied reader to close */ public static final void closeQuietly(final Reader aReader) { if (aReader != null) { try { aReader.close(); } catch (final IOException details) { LOGGER.error(details.getMessage(), details); } } } /** * Closes a writer, catching and logging any exceptions. * * @param aWriter A supplied writer to close */ public static final void closeQuietly(final Writer aWriter) { if (aWriter != null) { try { aWriter.close(); } catch (final IOException details) { LOGGER.error(details.getMessage(), details); } } } /** * Closes an input stream, catching and logging any exceptions. * * @param aInputStream A supplied input stream to close */ public static final void closeQuietly(final InputStream aInputStream) { if (aInputStream != null) { try { aInputStream.close(); } catch (final IOException details) { LOGGER.error(details.getMessage(), details); } } } /** * Closes an image input stream, catching and logging any exceptions * * @param aImageInputStream A supplied image input stream to close */ public static final void closeQuietly(final ImageInputStream aImageInputStream) { if (aImageInputStream != null) { try { aImageInputStream.close(); } catch (final IOException details) { LOGGER.error(details.getMessage(), details); } } } /** * Closes an image output stream, catching and logging any exceptions. * * @param aImageOutputStream A supplied image output stream to close */ public static final void closeQuietly(final ImageOutputStream aImageOutputStream) { if (aImageOutputStream != null) { try { aImageOutputStream.close(); } catch (final IOException details) { LOGGER.error(details.getMessage(), details); } } } /** * Closes an output stream, catching and logging any exceptions. * * @param aOutputStream A supplied output stream to close */ public static final void closeQuietly(final OutputStream aOutputStream) { if (aOutputStream != null) { try { aOutputStream.close(); } catch (final IOException details) { LOGGER.error(details.getMessage(), details); } } } /** * Closes a {@link JarFile}, catching and logging any exceptions. * * @param aJarFile A supplied {@link JarFile} to close */ public static final void closeQuietly(final JarFile aJarFile) { if (aJarFile != null) { try { aJarFile.close(); } catch (final IOException details) { LOGGER.error(details.getMessage(), details); } } } /** * Writes from an input stream to an output stream; you're responsible for closing the <code>InputStream</code> and * <code>OutputStream</code>. * * @param aInStream The stream from which to read * @param aOutStream The stream from which to write * @throws IOException If there is trouble reading or writing */ public static final void copyStream(final InputStream aInStream, final OutputStream aOutStream) throws IOException { final BufferedOutputStream outStream = new BufferedOutputStream(aOutStream); final BufferedInputStream inStream = new BufferedInputStream(aInStream); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int bytesRead = 0; while (true) { bytesRead = inStream.read(buffer); if (bytesRead == -1) { break; } byteStream.write(buffer, 0, bytesRead); } outStream.write(byteStream.toByteArray()); outStream.flush(); } /** * Writes a file to an output stream. You're responsible for closing the <code>OutputStream</code>; the input stream * is closed for you since just a <code>File</code> was passed in. * * @param aFile A file from which to read * @param aOutStream An output stream to which to write * @throws IOException If there is a problem reading or writing */ public static final void copyStream(final File aFile, final OutputStream aOutStream) throws IOException { final FileInputStream input = new FileInputStream(aFile); final FileChannel channel = input.getChannel(); final byte[] buffer = new byte[256 * 1024]; final ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); try { for (int length = 0; (length = channel.read(byteBuffer)) != -1;) { aOutStream.write(buffer, 0, length); byteBuffer.clear(); } } finally { input.close(); } } /** * Reads an InputStream into a byte array. * * @param aInputStream The input stream from which to read * @return The array of bytes * @throws IOException If there is trouble reading from the input stream */ public static final byte[] readBytes(final InputStream aInputStream) throws IOException { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final byte[] buffer = new byte[4096]; int read = 0; while (read != -1) { read = aInputStream.read(buffer); if (read > 0) { baos.write(buffer, 0, read); } } closeQuietly(aInputStream); return baos.toByteArray(); } }
// This file is part of the OpenNMS(R) Application. // OpenNMS(R) is a derivative work, containing both original code, included code and modified // and included code are below. // OpenNMS(R) is a registered trademark of Blast Internet Services, Inc. // Modifications: // Jul 8, 2004: Created this file. // This program is free software; you can redistribute it and/or modify // (at your option) any later version. // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // For more information contact: // Tab Size = 8 package org.opennms.netmgt.rrd; import java.awt.Color; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.apache.log4j.Category; import org.jrobin.core.FetchData; import org.jrobin.core.RrdDb; import org.jrobin.core.RrdDef; import org.jrobin.core.RrdException; import org.jrobin.core.Sample; import org.jrobin.graph.RrdGraph; import org.jrobin.graph.RrdGraphDef; import org.opennms.core.utils.ThreadCategory; /** * Provides a JRobin based implementation of RrdStrategy. It uses JRobin 1.4 in * FILE mode (NIO is too memory consuming for the large number of files that we * open) */ public class JRobinRrdStrategy implements RrdStrategy { /** * Closes the JRobin RrdDb. */ public void closeFile(Object rrdFile) throws Exception { ((RrdDb) rrdFile).close(); } /** * Creates and returns a RrdDef represented by the parameters. */ public Object createDefinition(String creator, String directory, String dsName, int step, String dsType, int dsHeartbeat, String dsMin, String dsMax, List rraList) throws Exception { File f = new File(directory); f.mkdirs(); String fileName = directory + File.separator + dsName + ".rrd"; RrdDef def = new RrdDef(fileName); //def.setStartTime(System.currentTimeMillis()/1000L - 2592000L); def.setStartTime(1000); def.setStep(step); double min = (dsMin == null || "U".equals(dsMin) ? Double.NaN : Double.parseDouble(dsMin)); double max = (dsMax == null || "U".equals(dsMax) ? Double.NaN : Double.parseDouble(dsMax)); def.addDatasource(dsName, dsType, dsHeartbeat, min, max); for (Iterator it = rraList.iterator(); it.hasNext();) { String rra = (String) it.next(); def.addArchive(rra); } return def; } /** * Creates the JRobin RrdDb from the def by opening the file and then * closing. TODO: Change the interface here to create the file and return it * opened. */ public void createFile(Object rrdDef) throws Exception { RrdDb rrd = new RrdDb((RrdDef) rrdDef); rrd.close(); } /** * Opens the JRobin RrdDb by name and returns it. */ public Object openFile(String fileName) throws Exception { RrdDb rrd = new RrdDb(fileName); return rrd; } /** * Creates a sample from the JRobin RrdDb and passes in the data provided. */ public void updateFile(Object rrdFile, String data) throws Exception { Sample sample = ((RrdDb) rrdFile).createSample(); sample.setAndUpdate(data); } /** * Initialized the RrdDb to use the FILE factory because the NIO factory * uses too much memory for our implementation. */ public void initialize() throws Exception { RrdDb.setDefaultFactory("FILE"); } /* (non-Javadoc) * @see org.opennms.netmgt.rrd.RrdStrategy#graphicsInitialize() */ public void graphicsInitialize() throws Exception { initialize(); } /** * Fetch the last value from the JRobin RrdDb file. */ public Double fetchLastValue(String fileName, int interval) throws NumberFormatException, org.opennms.netmgt.rrd.RrdException { try { long now = System.currentTimeMillis(); long collectTime = (now - (now % interval)) / 1000L; RrdDb rrd = new RrdDb(fileName); FetchData data = rrd.createFetchRequest("AVERAGE", collectTime, collectTime).fetchData(); double[] vals = data.getValues(0); if (vals.length > 0) { return new Double(vals[vals.length - 1]); } return null; } catch (IOException e) { throw new org.opennms.netmgt.rrd.RrdException("Exception occurred fetching data from " + fileName, e); } catch (RrdException e) { throw new org.opennms.netmgt.rrd.RrdException("Exception occurred fetching data from " + fileName, e); } } private Color getColor(String colorValue) { int colorVal = Integer.parseInt(colorValue, 16); return new Color(colorVal); } private String[] tokenize(String line, String delims) { Category log = ThreadCategory.getInstance(getClass()); List tokenList = new LinkedList(); StringBuffer currToken = new StringBuffer(); boolean quoting = false; boolean escaping = false; boolean debugTokens = Boolean.getBoolean("org.opennms.netmgt.rrd.debugTokens"); if (debugTokens) log.debug("tokenize: line=" + line + " delims=" + delims); for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); if (debugTokens) log.debug("tokenize: checking char: " + ch); if (escaping) { if (ch == 'n') { currToken.append('\n'); } else if (ch == 'r') { currToken.append('\r'); } else if (ch == 't') { currToken.append('\t'); } else { currToken.append(ch); } escaping = false; if (debugTokens) log.debug("tokenize: escaped. appended to " + currToken); } else if (ch == '\\') { if (debugTokens) log.debug("tokenize: found a backslash... escaping currToken = " + currToken); escaping = true; } else if (ch == '\"') { if (quoting) { if (debugTokens) log.debug("tokenize: found a quote ending quotation currToken = " + currToken); quoting = false; } else { if (debugTokens) log.debug("tokenize: found a quote beginning quotation currToke =" + currToken); quoting = true; } } else if (!quoting && delims.indexOf(ch) >= 0) { if (debugTokens) log.debug("tokenize: found a token: " + ch + " ending token [" + currToken + "] and starting a new one"); tokenList.add(currToken.toString()); currToken = new StringBuffer(); } else { if (debugTokens) log.debug("tokenize: appending " + ch + " to token: " + currToken); currToken.append(ch); } } if (escaping || quoting) { if (debugTokens) log.debug("tokenize: ended string but escaping = " + escaping + " and quoting = " + quoting); throw new IllegalArgumentException("unable to tokenize string " + line + " with token chars " + delims); } if (debugTokens) log.debug("tokenize: reached end of string. completing token " + currToken); tokenList.add(currToken.toString()); return (String[]) tokenList.toArray(new String[tokenList.size()]); } /** * This constructs a graphDef by parsing the rrdtool style command and using * the values to create the JRobin graphDef. It does not understand the 'AT * style' time arguments however. Also there may be some rrdtool parameters * that it does not understand. These will be ignored. The graphDef will be * used to construct an RrdGraph and a PNG image will be created. An input * stream returning the bytes of the PNG image is returned. */ public InputStream createGraph(String command, File workDir) throws IOException, org.opennms.netmgt.rrd.RrdException { Category log = ThreadCategory.getInstance(getClass()); try { InputStream tempIn = null; String[] commandArray = tokenize(command, " \t"); RrdGraphDef graphDef = new RrdGraphDef(); long start = 0; long end = 0; for (int i = 0; i < commandArray.length; i++) { String arg = commandArray[i]; if (arg.startsWith("--start=")) { start = Long.parseLong(arg.substring("--start=".length())); log.debug("JRobin start time: " + start); } else if (arg.equals("--start")) { if (i + 1 < commandArray.length) { start = Long.parseLong(commandArray[++i]); log.debug("JRobin start time: " + start); } else { throw new IllegalArgumentException("--start must be followed by a start time"); } } else if (arg.startsWith("--end=")) { end = Long.parseLong(arg.substring("--end=".length())); log.debug("JRobin end time: " + end); } else if (arg.equals("--end")) { if (i + 1 < commandArray.length) { end = Long.parseLong(commandArray[++i]); log.debug("JRobin end time: " + start); } else { throw new IllegalArgumentException("--end must be followed by an end time"); } } else if (arg.startsWith("--title=")) { String[] title = tokenize(arg, "="); graphDef.setTitle(title[1]); } else if (arg.equals("--title")) { if (i + 1 < commandArray.length) { graphDef.setTitle(commandArray[++i]); } else { throw new IllegalArgumentException("--title must be followed by a title"); } } else if (arg.startsWith("DEF:")) { String definition = arg.substring("DEF:".length()); String[] def = tokenize(definition, ":"); String[] ds = tokenize(def[0], "="); File dsFile = new File(workDir, ds[1]); graphDef.datasource(ds[0], dsFile.getAbsolutePath(), def[1], def[2]); } else if (arg.startsWith("CDEF:")) { String definition = arg.substring("CDEF:".length()); String[] cdef = tokenize(definition, "="); graphDef.datasource(cdef[0], cdef[1]); } else if (arg.startsWith("LINE1:")) { String definition = arg.substring("LINE1:".length()); String[] line1 = tokenize(definition, ":"); String[] color = tokenize(line1[0], " graphDef.line(color[0], getColor(color[1]), line1[1]); } else if (arg.startsWith("LINE2:")) { String definition = arg.substring("LINE2:".length()); String[] line2 = tokenize(definition, ":"); String[] color = tokenize(line2[0], " graphDef.line(color[0], getColor(color[1]), line2[1], 2); } else if (arg.startsWith("LINE3:")) { String definition = arg.substring("LINE3:".length()); String[] line3 = tokenize(definition, ":"); String[] color = tokenize(line3[0], " graphDef.line(color[0], getColor(color[1]), line3[1], 3); } else if (arg.startsWith("GPRINT:")) { String definition = arg.substring("GPRINT:".length()); String gprint[] = tokenize(definition, ":"); String format = gprint[2]; format = format.replaceAll("%(\\d*\\.\\d*)lf", "@$1"); format = format.replaceAll("%s", "@s"); log.debug("gprint: oldformat = " + gprint[2] + " newformat = " + format); graphDef.gprint(gprint[0], gprint[1], format); } else if (arg.startsWith("AREA:")) { String definition = arg.substring("AREA:".length()); String area[] = tokenize(definition, ":"); String[] color = tokenize(area[0], " graphDef.area(color[0], getColor(color[1]), area[1]); } else if (arg.startsWith("STACK:")) { String definition = arg.substring("STACK:".length()); String stack[] = tokenize(definition, ":"); String[] color = tokenize(stack[0], " graphDef.stack(color[0], getColor(color[1]), stack[1]); } else { log.warn("JRobin: Unrecognized graph argument: " + arg); } } graphDef.setTimePeriod(start, end); log.debug("JRobin Finished tokenizing checking: start time: " + start + "; end time: " + end); RrdGraph graph = new RrdGraph(graphDef, false); byte[] bytes = graph.getPNGBytes(); tempIn = new ByteArrayInputStream(bytes); return tempIn; } catch (Exception e) { log.error("JRobin:exception occurred creating graph", e); throw new org.opennms.netmgt.rrd.RrdException("An exception occurred creating the graph.", e); } } /** * This implementation does not track and stats. */ public String getStats() { return ""; } }
package io.kaitai.struct; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.zip.DataFormatException; import java.util.zip.Inflater; public class KaitaiStream { private FileChannel fc; private ByteBuffer bb; private int bitsLeft = 0; private long bits = 0; /** * Initializes a stream, reading from a local file with specified fileName. * Internally, FileChannel + MappedByteBuffer will be used. * @param fileName file to read * @throws IOException if file can't be read */ public KaitaiStream(String fileName) throws IOException { fc = FileChannel.open(Paths.get(fileName), StandardOpenOption.READ); bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); } /** * Initializes a stream that will get data from given byte array when read. * Internally, ByteBuffer wrapping given array will be used. * @param arr byte array to read */ public KaitaiStream(byte[] arr) { fc = null; bb = ByteBuffer.wrap(arr); } /** * Closes the stream safely. If there was an open file associated with it, closes that file. * For streams that were reading from in-memory array, does nothing. * @throws IOException if FileChannel can't be closed */ public void close() throws IOException { if (fc != null) fc.close(); } //region Stream positioning /** * Check if stream pointer is at the end of stream. * @return true if we are located at the end of the stream * @throws IOException if stream can't be read */ public boolean isEof() throws IOException { return !bb.hasRemaining(); } /** * Set stream pointer to designated position. * @param newPos new position (offset in bytes from the beginning of the stream) * @throws IOException if stream can't be read */ public void seek(int newPos) throws IOException { bb.position(newPos); } public void seek(long newPos) throws IOException { if (newPos > Integer.MAX_VALUE) { throw new RuntimeException("Java ByteBuffer can't be seeked past Integer.MAX_VALUE"); } bb.position((int) newPos); } /** * Get current position of a stream pointer. * @return pointer position, number of bytes from the beginning of the stream * @throws IOException if stream can't be read */ public int pos() throws IOException { return bb.position(); } /** * Get total size of the stream in bytes. * @return size of the stream in bytes * @throws IOException if stream can't be read */ public long size() throws IOException { return bb.limit(); } //endregion //region Integer numbers //region Signed /** * Reads one signed 1-byte integer, returning it properly as Java's "byte" type. * @return 1-byte integer read from a stream */ public byte readS1() { return bb.get(); } //region Big-endian public short readS2be() throws IOException { bb.order(ByteOrder.BIG_ENDIAN); return bb.getShort(); } public int readS4be() throws IOException { bb.order(ByteOrder.BIG_ENDIAN); return bb.getInt(); } public long readS8be() throws IOException { bb.order(ByteOrder.BIG_ENDIAN); return bb.getLong(); } //endregion //region Little-endian public short readS2le() { bb.order(ByteOrder.LITTLE_ENDIAN); return bb.getShort(); } public int readS4le() throws IOException { bb.order(ByteOrder.LITTLE_ENDIAN); return bb.getInt(); } public long readS8le() throws IOException { bb.order(ByteOrder.LITTLE_ENDIAN); return bb.getLong(); } //endregion //endregion //region Unsigned public int readU1() throws IOException { return bb.get() & 0xff; } //region Big-endian public int readU2be() throws IOException { bb.order(ByteOrder.BIG_ENDIAN); return bb.getShort() & 0xffff; } public long readU4be() throws IOException { bb.order(ByteOrder.BIG_ENDIAN); return bb.getInt() & 0xffffffffL; } public long readU8be() throws IOException { return readS8be(); } //endregion //region Little-endian public int readU2le() throws IOException { bb.order(ByteOrder.LITTLE_ENDIAN); return bb.getShort() & 0xffff; } public long readU4le() throws IOException { bb.order(ByteOrder.LITTLE_ENDIAN); return bb.getInt() & 0xffffffffL; } public long readU8le() throws IOException { return readS8le(); } //endregion //endregion //endregion //region Floating point numbers //region Big-endian public float readF4be() throws IOException { bb.order(ByteOrder.BIG_ENDIAN); return bb.getFloat(); } public double readF8be() throws IOException { bb.order(ByteOrder.BIG_ENDIAN); return bb.getDouble(); } //endregion //region Little-endian public float readF4le() throws IOException { bb.order(ByteOrder.LITTLE_ENDIAN); return bb.getFloat(); } public double readF8le() throws IOException { bb.order(ByteOrder.LITTLE_ENDIAN); return bb.getDouble(); } //endregion //endregion //region Unaligned bit values public long readBitsInt(int n) throws IOException { int bitsNeeded = n - bitsLeft; if (bitsNeeded > 0) { // 1 bit => 1 byte // 8 bits => 1 byte // 9 bits => 2 bytes int bytesNeeded = ((bitsNeeded - 1) / 8) + 1; byte[] buf = readBytes(bytesNeeded); for (byte b : buf) { bits <<= 8; bits |= b; bitsLeft += 8; } } // raw mask with required number of 1s, starting from lowest bit long mask = (1 << n) - 1; // shift mask to align with highest bits available in "bits" int shiftBits = bitsLeft - n; mask <<= shiftBits; // derive reading result long res = (bits & mask) >> shiftBits; // clear top bits that we've just read => AND with 1s bitsLeft -= n; mask = (1 << bitsLeft) - 1; bits &= mask; return res; } //endregion //region Byte arrays /** * Reads designated number of bytes from the stream. * @param n number of bytes to read * @return read bytes as byte array * @throws IOException if stream can't be read * @throws EOFException if there were less bytes than requested available in the stream */ public byte[] readBytes(long n) throws IOException { if (n > Integer.MAX_VALUE) { throw new RuntimeException( "Java byte arrays can be indexed only up to 31 bits, but " + n + " size was requested" ); } byte[] buf = new byte[(int) n]; bb.get(buf); return buf; } /** * Reads all the remaining bytes in a stream as byte array. * @return all remaining bytes in a stream as byte array * @throws IOException if stream can't be read */ public byte[] readBytesFull() throws IOException { byte[] buf = new byte[bb.remaining()]; bb.get(buf); return buf; } /** * Checks that next bytes in the stream match match expected fixed byte array. * It does so by determining number of bytes to compare, reading them, and doing * the actual comparison. If they differ, throws a {@link UnexpectedDataError} * runtime exception. * @param expected contents to be expected * @return read bytes as byte array, which are guaranteed to equal to expected * @throws IOException if stream can't be read * @throws UnexpectedDataError if read data from stream isn't equal to given data */ public byte[] ensureFixedContents(byte[] expected) throws IOException { byte[] actual = readBytes(expected.length); if (!Arrays.equals(actual, expected)) throw new UnexpectedDataError(actual, expected); return actual; } //endregion //region Strings public String readStrEos(String encoding) throws IOException { return new String(readBytesFull(), Charset.forName(encoding)); } public String readStrByteLimit(long len, String encoding) throws IOException { return new String(readBytes(len), Charset.forName(encoding)); } public String readStrz(String encoding, int term, boolean includeTerm, boolean consumeTerm, boolean eosError) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); Charset cs = Charset.forName(encoding); while (true) { if (!bb.hasRemaining()) { if (eosError) { throw new RuntimeException("End of stream reached, but no terminator " + term + " found"); } else { return new String(buf.toByteArray(), cs); } } int c = bb.get(); if (c == term) { if (includeTerm) buf.write(c); if (!consumeTerm) bb.position(bb.position() - 1); return new String(buf.toByteArray(), cs); } buf.write(c); } } //endregion //region Byte array processing /** * Performs a XOR processing with given data, XORing every byte of input with a single * given value. * @param data data to process * @param key value to XOR with * @return processed data */ public static byte[] processXor(byte[] data, int key) { int dataLen = data.length; byte[] r = new byte[dataLen]; for (int i = 0; i < dataLen; i++) r[i] = (byte) (data[i] ^ key); return r; } /** * Performs a XOR processing with given data, XORing every byte of input with a key * array, repeating key array many times, if necessary (i.e. if data array is longer * than key array). * @param data data to process * @param key array of bytes to XOR with * @return processed data */ public static byte[] processXor(byte[] data, byte[] key) { int dataLen = data.length; int valueLen = key.length; byte[] r = new byte[dataLen]; int j = 0; for (int i = 0; i < dataLen; i++) { r[i] = (byte) (data[i] ^ key[j]); j = (j + 1) % valueLen; } return r; } /** * Performs a circular left rotation shift for a given buffer by a given amount of bits, * using groups of groupSize bytes each time. Right circular rotation should be performed * using this procedure with corrected amount. * @param data source data to process * @param amount number of bits to shift by * @param groupSize number of bytes per group to shift * @return copy of source array with requested shift applied */ public static byte[] processRotateLeft(byte[] data, int amount, int groupSize) { byte[] r = new byte[data.length]; switch (groupSize) { case 1: for (int i = 0; i < data.length; i++) { byte bits = data[i]; r[i] = (byte) (((bits & 0xff) << amount) | ((bits & 0xff) >>> (8 - amount))); } break; default: throw new UnsupportedOperationException("unable to rotate group of " + groupSize + " bytes yet"); } return r; } private final static int ZLIB_BUF_SIZE = 4096; /** * Performs an unpacking ("inflation") of zlib-compressed data with usual zlib headers. * @param data data to unpack * @return unpacked data * @throws IOException if data can't be decoded */ public static byte[] processZlib(byte[] data) throws IOException { Inflater ifl = new Inflater(); ifl.setInput(data); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[ZLIB_BUF_SIZE]; while (!ifl.finished()) { try { int decBytes = ifl.inflate(buf); baos.write(buf, 0, decBytes); } catch (DataFormatException e) { throw new IOException(e); } } ifl.end(); return baos.toByteArray(); } //endregion //region Misc runtime operations /** * Performs modulo operation between two integers: dividend `a` * and divisor `b`. Divisor `b` is expected to be positive. The * result is always 0 &lt;= x &lt;= b - 1. * @param a dividend * @param b divisor * @return result */ public static int mod(int a, int b) { if (b <= 0) throw new ArithmeticException("mod divisor <= 0"); int r = a % b; if (r < 0) r += b; return r; } /** * Performs modulo operation between two integers: dividend `a` * and divisor `b`. Divisor `b` is expected to be positive. The * result is always 0 &lt;= x &lt;= b - 1. * @param a dividend * @param b divisor * @return result */ public static long mod(long a, long b) { if (b <= 0) throw new ArithmeticException("mod divisor <= 0"); long r = a % b; if (r < 0) r += b; return r; } //endregion /** * Exception class for an error that occurs when some fixed content * was expected to appear, but actual data read was different. */ public static class UnexpectedDataError extends RuntimeException { public UnexpectedDataError(byte[] actual, byte[] expected) { super( "Unexpected fixed contents: got " + byteArrayToHex(actual) + " , was waiting for " + byteArrayToHex(expected) ); } private static String byteArrayToHex(byte[] arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { if (i > 0) sb.append(' '); sb.append(String.format("%02x", arr[i])); } return sb.toString(); } } }
package io.kaitai.struct; import java.io.IOException; /** * Common base class for all structured generated by Kaitai Struct. * Stores stream object that this object was parsed from in {@link #_io}. */ public class KaitaiStruct { /** * Stream object that this KaitaiStruct-based structure was parsed from. */ protected KaitaiStream _io; public KaitaiStruct(KaitaiStream _io) throws IOException { this._io = _io; } public KaitaiStream _io() { return _io; } }
package io.redlink.sdk.util; import org.apache.commons.lang3.StringUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Helper around Maven stuff * * @author sergio.fernandez@redlink.co */ public class ApiHelper { public static final Pattern VERSION_PATTERN = Pattern.compile("(\\d)+\\.(\\d)+(\\.\\d+)?\\-([A-Z]+)(\\-SNAPSHOT)?"); public static String getApiVersion() { String version = getApiVersion(ApiHelper.class.getPackage().getImplementationVersion()); return (version != null ? version : "1.0-ALPHA"); //FIXME } public static String getApiVersion(String version) { if (StringUtils.isBlank(version)) { return null; } else { final Matcher matcher = VERSION_PATTERN.matcher(version); if (matcher.matches()) { if (StringUtils.isBlank(matcher.group(4))) { return String.format("%s.%s", matcher.group(1), matcher.group(2)); } else { return String.format("%s.%s-%s", matcher.group(1), matcher.group(2), matcher.group(4)); } } else { return null; } } } }
package junitparams; import java.util.ArrayList; import java.util.List; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import junitparams.internal.ParameterisedTestClassRunner; import junitparams.internal.ParametrizedTestMethodsFilter; import junitparams.internal.TestMethod; /** * <h1>JUnitParams</h1><br> * <p> * This is a JUnit runner for parameterised tests that don't suck. Annotate your test class with * <code>&#064;RunWith(JUnitParamsRunner.class)</code> and place * <code>&#064;Parameters</code> annotation on each test method which requires * parameters. Nothing more needed - no special structure, no dirty tricks. * </p> * <br> * <h2>Contents</h2> <b> <a href="#p1">1. Parameterising tests</a><br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#a">a. Parameterising tests via values * in annotation</a><br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#b">b. Parameterising tests via a * method that returns parameter values</a><br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#c">c. Parameterising tests via * external classes</a><br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#d">d. Loading parameters from files</a><br> * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#d">e. Converting parameter values</a><br> * <a href="#p2">2. Usage with Spring</a><br> * <a href="#p3">3. Other options</a><br> * </b><br> * <h3 id="p1">1. Parameterising tests</h3> Parameterised tests are a great way * to limit the amount of test code when you need to test the same code under * different conditions. Ever tried to do it with standard JUnit tools like * Parameterized runner or Theories? I always thought they're so awkward to use, * that I've written this library to help all those out there who'd like to have * a handy tool. * * So here we go. There are a few different ways to use JUnitParams, I will try * to show you all of them here. * * <h4 id="a">a. Parameterising tests via values in annotation</h4> * <p> * You can parameterise your test with values defined in annotations. Just pass * sets of test method argument values as an array of Strings, where each string * contains the argument values separated by a comma or a pipe "|". * * <pre> * &#064;Test * &#064;Parameters({ "20, Tarzan", "0, Jane" }) * public void cartoonCharacters(int yearsInJungle, String person) { * ... * } * </pre> * * Sometimes you may be interested in passing enum values as parameters, then * you can just write them as Strings like this: * * <pre> * &#064;Test * &#064;Parameters({ &quot;FROM_JUNGLE&quot;, &quot;FROM_CITY&quot; }) * public void passEnumAsParam(PersonType person) { * } * </pre> * * <h4 id="b">b. Parameterising tests via a method that returns parameter values * </h4> * <p> * Obviously passing parameters as strings is handy only for trivial situations, * that's why for normal cases you have a method that gives you a collection of * parameters: * * <pre> * &#064;Test * &#064;Parameters(method = "cartoonCharacters") * public void cartoonCharacters(int yearsInJungle, String person) { * ... * } * private Object[] cartoonCharacters() { * return $( * $(0, "Tarzan"), * $(20, "Jane") * ); * } * </pre> * * Where <code>$(...)</code> is a static method defined in * <code>JUnitParamsRunner</code> class, which returns its parameters as a * <code>Object[]</code> array. Just a shortcut, so that you don't need to write the ugly <code>new Object[] {}</code> kind of stuff. * * <p> * <code>method</code> can take more than one method name - you can pass as many * of them as you want, separated by commas. This enables you to divide your * test cases e.g. into categories. * <pre> * &#064;Test * &#064;Parameters(method = "menCharactes, womenCharacters") * public void cartoonCharacters(int yearsInJungle, String person) { * ... * } * private Object[] menCharacters() { * return $( * $(20, "Tarzan"), * $(2, "Chip"), * $(2, "Dale") * ); * } * private Object[] womenCharacters() { * return $( * $(0, "Jane"), * $(18, "Pocahontas") * ); * } * </pre> * <p> * The <code>method</code> argument of a <code>@Parameters</code> annotation can * be ommited if the method that provides parameters has a the same name as the * test, but prefixed by <code>parametersFor</code>. So our example would look * like this: * * <pre> * &#064;Test * &#064;Parameters * public void cartoonCharacters(int yearsInJungle, String person) { * ... * } * private Object[] parametersForCartoonCharacters() { * return $( * $(0, "Tarzan"), * $(20, "Jane") * ); * } * </pre> * * <p> * If you don't like returning untyped values and arrays, you can equally well * return any Iterable of concrete objects: * * <pre> * &#064;Test * &#064;Parameters * public void cartoonCharacters(Person character) { * ... * } * private List&lt;Person&gt; parametersForCartoonCharacters() { * return Arrays.asList( * new Person(0, "Tarzan"), * new Person(20, "Jane") * ); * } * </pre> * * If we had more than just two Person's to make, we would get redundant, * so JUnitParams gives you a simplified way of creating objects to be passed as * params. You can omit the creation of the objects and just return their constructor * argument values like this: * * <pre> * &#064;Test * &#064;Parameters * public void cartoonCharacters(Person character) { * ... * } * private List&lt;?&gt; parametersForCartoonCharacters() { * return Arrays.asList( * $(0, "Tarzan"), * $(20, "Jane") * ); * } * </pre> * And JUnitParams will invoke the appropriate constructor (<code>new Person(int age, String name)</code> in this case.) * <b>If you want to use it, watch out! Automatic refactoring of constructor * arguments won't be working here!</b> * * <p> * You can also define methods that provide parameters in subclasses and use * them in test methods defined in superclasses, as well as redefine data * providing methods in subclasses to be used by test method defined in a * superclass. That you can doesn't mean you should. Inheritance in tests is * usually a code smell (readability hurts), so make sure you know what you're * doing. * * <h4 id="c">c. Parameterising tests via external classes</h4> * <p> * For more complex cases you may want to externalise the method that provides * parameters or use more than one method to provide parameters to a single test * method. You can easily do that like this: * * <pre> * &#064;Test * &#064;Parameters(source = CartoonCharactersProvider.class) * public void testReadyToLiveInJungle(int yearsInJungle, String person) { * ... * } * ... * class CartoonCharactersProvider { * public static Object[] provideCartoonCharactersManually() { * return $( * $(0, "Tarzan"), * $(20, "Jane") * ); * } * public static Object[] provideCartoonCharactersFromDB() { * return cartoonsRepository.loadCharacters(); * } * } * </pre> * * All methods starting with <code>provide</code> are used as parameter * providers. * * <p> * Sometimes though you may want to use just one or few methods of some class to * provide you parameters. This can be done as well like this: * * <pre> * &#064;Test * &#064;Parameters(source = CartoonCharactersProvider.class, method = "cinderellaCharacters,snowwhiteCharacters") * public void testPrincesses(boolean isAPrincess, String characterName) { * ... * } * </pre> * * * <h4 id="d">d. Loading parameters from files</h4> You may be interested in * loading parameters from a file. This is very easy if it's a CSV file with * columns in the same order as test method parameters: * * <pre> * &#064;Test * &#064;FileParameters("cartoon-characters.csv") * public void shouldSurviveInJungle(int yearsInJungle, String person) { * ... * } * </pre> * * But if you want to process the data from the CSV file a bit to use it in the * test method arguments, you * need to use an <code>IdentityMapper</code>. Look: * * <pre> * &#064;Test * &#064;FileParameters(value = "cartoon-characters.csv", mapper = CartoonMapper.class) * public void shouldSurviveInJungle(Person person) { * ... * } * * public class CartoonMapper extends IdentityMapper { * &#064;Override * public Object[] map(Reader reader) { * Object[] map = super.map(reader); * List&lt;Object[]&gt; result = new LinkedList&lt;Object[]&gt;(); * for (Object lineObj : map) { * String line = (String) lineObj; // line in a format just like in the file * result.add(new Object[] { ..... }); // some format edible by the test method * } * return result.toArray(); * } * * } * </pre> * * A CSV files with a header are also supported with the use of <code>CsvWithHeaderMapper</code> class. * * You may also want to use a completely different file format, like excel or * something. Then just parse it yourself: * * <pre> * &#064;Test * &#064;FileParameters(value = "cartoon-characters.xsl", mapper = ExcelCartoonMapper.class) * public void shouldSurviveInJungle(Person person) { * ... * } * * public class CartoonMapper implements DataMapper { * &#064;Override * public Object[] map(Reader fileReader) { * ... * } * } * </pre> * * As you see, you don't need to open or close the file. Just read it from the * reader and parse it the way you wish. * * By default the file is loaded from the file system, relatively to where you start the tests from. But you can also use a resource from * the classpath by prefixing the file name with <code>classpath:</code> * * <h4 id="e">e. Converting parameter values</h4> * Sometimes you want to pass some parameter in one form, but use it in the test in another. Dates are a good example. It's handy to * specify them in the parameters as a String like "2013.01.01", but you'd like to use a Jodatime's LocalDate or JDKs Date in the test * without manually converting the value in the test. This is where the converters become handy. It's enough to annotate a parameter with * a <code>&#064;ConvertParam</code> annotation, give it a converter class and possibly some options (like date format in this case) and * you're done. Here's an example: * <pre> * &#064;Test * &#064;Parameters({ "01.12.2012, A" }) * public void convertMultipleParams( * &#064;ConvertParam(value = StringToDateConverter.class, options = "dd.MM.yyyy") Date date, * &#064;ConvertParam(LetterToASCIIConverter.class) int num) { * * Calendar calendar = Calendar.getInstance(); * calendar.setTime(date); * * assertEquals(2012, calendar.get(Calendar.YEAR)); * assertEquals(11, calendar.get(Calendar.MONTH)); * assertEquals(1, calendar.get(Calendar.DAY_OF_MONTH)); * * assertEquals(65, num); * } * </pre> * * <h3 id="p2">2. Usage with Spring</h3> * <p> * You can easily use JUnitParams together with Spring. The only problem is that * Spring's test framework is based on JUnit runners, and JUnit allows only one * runner to be run at once. Which would normally mean that you could use only * one of Spring or JUnitParams. Luckily we can cheat Spring a little by adding * this to your test class: * * <pre> * private TestContextManager testContextManager; * * &#064;Before * public void init() throws Exception { * this.testContextManager = new TestContextManager(getClass()); * this.testContextManager.prepareTestInstance(this); * } * </pre> * * This lets you use in your tests anything that Spring provides in its test * framework. * * <h3 id="p3">3. Other options</h3> * <h4> Enhancing test case description</h4> * You can use <code>TestCaseName</code> annotation to provide template of the individual test case name: * <pre> * &#064;TestCaseName("factorial({0}) = {1}") * &#064;Parameters({ "1,1"}) * public void fractional_test(int argument, int result) { } * </pre> * Will be displayed as 'fractional(1)=1' * <h4>Customizing how parameter objects are shown in IDE</h4> * <p> * Tests show up in your IDE as a tree with test class name being the root, test * methods being nodes, and parameter sets being the leaves. If you want to * customize the way an parameter object is shown, create a <b>toString</b> * method for it. * <h4>Empty parameter sets</h4> * <p> * If you create a parameterised test, but won't give it any parameter sets, it * will be ignored and you'll be warned about it. * <h4>Parameterised test with no parameters</h4> * <p> * If for some reason you want to have a normal non-parameterised method to be * annotated with @Parameters, then fine, you can do it. But it will be ignored * then, since there won't be any params for it, and parameterised tests need * parameters to execute properly (parameters are a part of test setup, right?) * <h4>JUnit Rules</h4> * <p> * The runner for parameterised test is trying to keep all the @Rule's running, * but if something doesn't work - let me know. It's pretty tricky, since the * rules in JUnit are chained, but the chain is kind of... unstructured, so * sometimes I need to guess how to call the next element in chain. If you have * your own rule, make sure it has a field of type Statement which is the next * statement in chain to call. * <h4>Test inheritance</h4> * <p> * Although usually a bad idea, since it makes tests less readable, sometimes * inheritance is the best way to remove repetitions from tests. JUnitParams is * fine with inheritance - you can define a common test in the superclass, and * have separate parameters provider methods in the subclasses. Also the other * way around is ok, you can define parameter providers in superclass and have * tests in subclasses uses them as their input. * * @author Pawel Lipinski (lipinski.pawel@gmail.com) */ public class JUnitParamsRunner extends BlockJUnit4ClassRunner { private ParametrizedTestMethodsFilter parametrizedTestMethodsFilter = new ParametrizedTestMethodsFilter(this); private ParameterisedTestClassRunner parameterisedRunner; private Description description; public JUnitParamsRunner(Class<?> klass) throws InitializationError { super(klass); parameterisedRunner = new ParameterisedTestClassRunner(getTestClass()); } @Override public void filter(Filter filter) throws NoTestsRemainException { super.filter(filter); this.parametrizedTestMethodsFilter = new ParametrizedTestMethodsFilter(this,filter); } protected void collectInitializationErrors(List<Throwable> errors) { for (Throwable throwable : errors) throwable.printStackTrace(); } @Override protected void runChild(FrameworkMethod method, RunNotifier notifier) { if (handleIgnored(method, notifier)) return; TestMethod testMethod = parameterisedRunner.testMethodFor(method); if (parameterisedRunner.shouldRun(testMethod)){ parameterisedRunner.runParameterisedTest(testMethod, methodBlock(method), notifier); } else{ verifyMethodCanBeRunByStandardRunner(testMethod); super.runChild(method, notifier); } } private void verifyMethodCanBeRunByStandardRunner(TestMethod testMethod) { List<Throwable> errors = new ArrayList<Throwable>(); testMethod.frameworkMethod().validatePublicVoidNoArg(false, errors); if (!errors.isEmpty()) { throw new RuntimeException(errors.get(0)); } } private boolean handleIgnored(FrameworkMethod method, RunNotifier notifier) { TestMethod testMethod = parameterisedRunner.testMethodFor(method); if (testMethod.isIgnored()) notifier.fireTestIgnored(describeMethod(method)); return testMethod.isIgnored(); } @Override protected List<FrameworkMethod> computeTestMethods() { return parameterisedRunner.computeFrameworkMethods(); } @Override protected Statement methodInvoker(FrameworkMethod method, Object test) { Statement methodInvoker = parameterisedRunner.parameterisedMethodInvoker(method, test); if (methodInvoker == null) methodInvoker = super.methodInvoker(method, test); return methodInvoker; } @Override public Description getDescription() { if (description == null) { description = Description.createSuiteDescription(getName(), getTestClass().getAnnotations()); List<FrameworkMethod> resultMethods = getListOfMethods(); for (FrameworkMethod method : resultMethods) description.addChild(describeMethod(method)); } return description; } private List<FrameworkMethod> getListOfMethods() { List<FrameworkMethod> frameworkMethods = parameterisedRunner.returnListOfMethods(); return parametrizedTestMethodsFilter.filteredMethods(frameworkMethods); } public Description describeMethod(FrameworkMethod method) { Description child = parameterisedRunner.describeParameterisedMethod(method); if (child == null) child = describeChild(method); return child; } /** * Shortcut for returning an array of objects. All parameters passed to this * method are returned in an <code>Object[]</code> array. * * Should not be used to create var-args arrays, because of the way Java resolves * var-args for objects and primitives. * * @deprecated This method is no longer supported. It might be removed in future * as it does not support all cases (especially var-args). Create arrays using * <code>new Object[]{}</code> instead. * * @param params * Values to be returned in an <code>Object[]</code> array. * @return Values passed to this method. */ @Deprecated public static Object[] $(Object... params) { return params; } }
package authzadmin.model; import authzadmin.OauthClientDetails; import org.junit.Before; import org.junit.Test; import org.springframework.security.core.GrantedAuthority; import java.util.*; import static authzadmin.OauthClientDetails.AUTO_APPROVE_SCOPE; import static authzadmin.WebApplication.*; import static org.junit.Assert.*; public class OauthClientDetailsTest { private OauthSettings oauthSettings; @Before public void before() { oauthSettings = new OauthSettings("secret", "client_id", "http://ignore"); } @Test public void test_is_client_credentials_allowed() { oauthSettings.setClientCredentialsAllowed(true); OauthClientDetails detail = new OauthClientDetails(oauthSettings); assertTrue(detail.getAuthorizedGrantTypes().contains(CLIENT_CREDENTIALS)); } @Test public void test_has_scopes() { List<Scope> scopes = Arrays.asList(new Scope("read"), new Scope("write")); oauthSettings.setScopes(scopes); OauthClientDetails detail = new OauthClientDetails(oauthSettings); assertTrue(detail.getScope().equals(new TreeSet<>(Arrays.asList("read", "write")))); } @Test public void test_is_auto_approve() { oauthSettings.setAutoApprove(true); OauthClientDetails detail = new OauthClientDetails(oauthSettings); Set<String> autoApproveScopes = detail.getAutoApproveScopes(); assertEquals(1, autoApproveScopes.size()); assertEquals(AUTO_APPROVE_SCOPE, autoApproveScopes.iterator().next()); } @Test public void test_is_resource_server() { oauthSettings.setResourceServer(true); OauthClientDetails detail = new OauthClientDetails(oauthSettings); Collection<GrantedAuthority> authorities = detail.getAuthorities(); assertEquals(1, authorities.size()); assertEquals(ROLE_TOKEN_CHECKER, authorities.iterator().next().getAuthority()); assertTrue(detail.getAuthorizedGrantTypes().equals(new HashSet<>(Collections.singleton("resource_server")))); } }
package br.com.leandromoreira.jdcpu16br; import static br.com.leandromoreira.jdcpu16br.CPU.*; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.Before; import org.junit.Test; public class TestCPU { private final CPU cpu = new CPU(); private final Memory memory = cpu.memory(); @Before public void setup() { cpu.reset(); } @Test public void it_returns_stack_and_increment_itself() { cpu.setStackPointer(0x0002); assertThat(cpu.popStackPointer(), is(0x0002)); assertThat(cpu.getStackPointer(), is(0x0003)); } @Test public void it_returns_drecremented_stack_pointer() { cpu.setStackPointer(0x0002); assertThat(cpu.pushStackPointer(), is(0x0001)); } @Test public void it_performs_add_a_to_b() { cpu.setRegister(A, 0x5); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_0010); cpu.step(); assertThat(cpu.register(A), is(0x5 + 0x5)); } @Test public void when_there_is_no_oveflow_at_add() { cpu.setRegister(A, 0x5); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_0010); cpu.step(); assertThat(cpu.getOverflow(), is(0x0000)); } @Test public void when_there_is_an_oveflow_at_add() { cpu.setRegister(A, 0xFFFF); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_0010); cpu.step(); assertThat(cpu.getOverflow(), is(0x0001)); } @Test public void it_performs_sub_a_to_b() { cpu.setRegister(A, 0x10); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_0011); cpu.step(); assertThat(cpu.register(A), is(0x10 - 0x5)); } @Test public void when_there_is_no_underflow_at_sub() { cpu.setRegister(A, 0x5); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_0011); cpu.step(); assertThat(cpu.getOverflow(), is(0x0000)); } @Test public void when_there_is_an_underflow_at_sub() { cpu.setRegister(A, 0x5); cpu.setRegister(B, 0x6); memory.writeAt(0x0000, 0b000001_000000_0011); cpu.step(); assertThat(cpu.getOverflow(), is(0xFFFF)); } @Test public void it_performs_mul_a_to_b() { cpu.setRegister(A, 0x10); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_0100); cpu.step(); assertThat(cpu.register(A), is(0x10 * 0x5)); } @Test public void mul_sets_overflow() { cpu.setRegister(A, 0x5); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_0100); cpu.step(); assertThat(cpu.getOverflow(), is(((0x5 * 0x5) >> 16) & 0xFFFF)); } @Test public void it_performs_div_a_to_b() { cpu.setRegister(A, 0x10); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_0101); cpu.step(); assertThat(cpu.register(A), is(0x10 / 0x5)); assertThat(cpu.getOverflow(), is(((cpu.register(A) << 16) / cpu.register(B)) & 0xFFFF)); } @Test public void when_b_is_zero_there_is_no_division() { cpu.setRegister(A, 0x10); cpu.setRegister(B, 0x0); memory.writeAt(0x0000, 0b000001_000000_0101); cpu.step(); assertThat(cpu.register(A), is(0x0)); assertThat(cpu.getOverflow(), is(0x0)); } @Test public void it_performs_mod_a_to_b() { cpu.setRegister(A, 0x10); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_0110); cpu.step(); assertThat(cpu.register(A), is(0x10 % 0x5)); } @Test public void when_b_is_zero_there_is_no_mod() { cpu.setRegister(A, 0x10); cpu.setRegister(B, 0x0); memory.writeAt(0x0000, 0b000001_000000_0110); cpu.step(); assertThat(cpu.register(A), is(0x0)); } @Test public void it_performs_shl_a_to_b() { cpu.setRegister(A, 0x10); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_0111); cpu.step(); assertThat(cpu.register(A), is(0x10 << 0x5)); assertThat(cpu.getOverflow(), is(((0x10 << 0x5) >> 16) & 0xFFFF)); } @Test public void it_performs_shr_a_to_b() { cpu.setRegister(A, 0x10); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_1000); cpu.step(); assertThat(cpu.register(A), is(0x10 >> 0x5)); assertThat(cpu.getOverflow(), is(((0x10 << 16) >> 0x5) & 0xFFFF)); } @Test public void it_performs_and_a_to_b() { cpu.setRegister(A, 0x10); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_1001); cpu.step(); assertThat(cpu.register(A), is(0x10 & 0x5)); } @Test public void it_performs_bor_a_to_b() { cpu.setRegister(A, 0x10); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_1010); cpu.step(); assertThat(cpu.register(A), is(0x10 | 0x5)); } @Test public void it_performs_xor_a_to_b() { cpu.setRegister(A, 0x10); cpu.setRegister(B, 0x5); memory.writeAt(0x0000, 0b000001_000000_1011); cpu.step(); assertThat(cpu.register(A), is(0x10 ^ 0x5)); } @Test public void it_performs_next_instruction_when_a_equals_to_b() { cpu.setRegister(A, 0x5); cpu.setRegister(B, 0x5); cpu.setRegister(C, 0x3); memory.writeAt(0x0000, 0b000001_000000_1100); memory.writeAt(0x0001, 0b000010_000000_0001); cpu.step(); cpu.step(); assertThat(cpu.register(A), is(0x3)); } @Test public void it_doesnt_performs_next_instruction_when_a_is_different_from_b() { cpu.setRegister(A, 0x1); cpu.setRegister(B, 0x5); cpu.setRegister(C, 0x3); memory.writeAt(0x0000, 0b000001_000000_1100); memory.writeAt(0x0001, 0b000010_000000_0010); memory.writeAt(0x0002, 0b000001_000000_0010); cpu.step(); cpu.step(); assertThat(cpu.register(A), is(0x5 + 0x1)); } @Test public void it_does_perform_next_instruction_when_a_equals_to_b() { cpu.setRegister(A, 0x1); cpu.setRegister(B, 0x5); cpu.setRegister(C, 0x3); memory.writeAt(0x0000, 0b000001_000000_1101); memory.writeAt(0x0001, 0b000010_000000_0010); memory.writeAt(0x0002, 0b000001_000000_0010); cpu.step(); cpu.step(); assertThat(cpu.register(A), is(0x3 + 0x1)); } @Test public void it_does_perform_next_instruction_when_a_is_greater_than_b() { cpu.setRegister(A, 0x6); cpu.setRegister(B, 0x5); cpu.setRegister(C, 0x3); memory.writeAt(0x0000, 0b000001_000000_1110); memory.writeAt(0x0001, 0b000010_000000_0010); memory.writeAt(0x0002, 0b000001_000000_0010); cpu.step(); cpu.step(); assertThat(cpu.register(A), is(0x3 + 0x6)); } @Test public void it_does_perform_next_instruction_when_a_and_b_different_from_zero() { cpu.setRegister(A, 0x6); cpu.setRegister(B, 0x5); cpu.setRegister(C, 0x3); memory.writeAt(0x0000, 0b000001_000000_1111); memory.writeAt(0x0001, 0b000010_000000_0010); memory.writeAt(0x0002, 0b000001_000000_0010); cpu.step(); cpu.step(); assertThat(cpu.register(A), is(0x3 + 0x6)); } @Test public void it_does_perform_syscall_jsr() { cpu.setRegister(A, 0x6); memory.writeAt(0x0000, 0b000000_000001_0000); cpu.step(); assertThat(cpu.getProgramCounter(), is(cpu.register(A))); } @Test public void it_runs_properly_instructions_with_different_sizes() { int address = 0x0000; memory.writeAt(address++, 0x7C01); memory.writeAt(address++, 0x0030); memory.writeAt(address++, 0x7DE1); memory.writeAt(address++, 0x1000); memory.writeAt(address++, 0x0020); cpu.step(); cpu.step(); assertThat(memory.readFrom(0x1000), is(0x20)); } @Test public void it_runs_properly_basic_stuff() { int address = 0x0000; memory.writeAt(address++, 0x7C01); memory.writeAt(address++, 0x0030); memory.writeAt(address++, 0x7DE1); memory.writeAt(address++, 0x1000); memory.writeAt(address++, 0x0020); memory.writeAt(address++, 0x7803); memory.writeAt(address++, 0x1000); memory.writeAt(address++, 0xC00D); memory.writeAt(address++, 0x7DC1); memory.writeAt(address++, 0x001A); memory.writeAt(address++, 0xA861); for (int steps = 0; steps < 5; steps++) { cpu.step(); } assertThat(cpu.register(A), is(0x10)); assertThat(cpu.register(I), is(10)); assertThat(memory.readFrom(0x1000), is(0x20)); } @Test public void it_runs_loopy_code() { int address = 0x0000; memory.writeAt(address++, 0x7C01); memory.writeAt(address++, 0x0030); memory.writeAt(address++, 0x7DE1); memory.writeAt(address++, 0x1000); memory.writeAt(address++, 0x0020); memory.writeAt(address++, 0x7803); memory.writeAt(address++, 0x1000); memory.writeAt(address++, 0xC00D); memory.writeAt(address++, 0x7DC1); memory.writeAt(address++, 0x001A); memory.writeAt(address++, 0xA861); memory.writeAt(address++, 0x7C01); memory.writeAt(address++, 0x2000); memory.writeAt(address++, 0x2161); memory.writeAt(address++, 0x2000); memory.writeAt(address++, 0x8463); memory.writeAt(address++, 0x806D); memory.writeAt(address++, 0x7DC1); memory.writeAt(address++, 0x000D); memory.writeAt(address++, 0x9031); memory.writeAt(address++, 0x7C10); memory.writeAt(address++, 0x0018); memory.writeAt(address++, 0x7DC1); memory.writeAt(address++, 0x001A); memory.writeAt(address++, 0x9037); memory.writeAt(address++, 0x61C1); memory.writeAt(address++, 0x7DC1); memory.writeAt(address++, 0x001A); for (int steps = 0; steps < 55; steps++) { cpu.step(); } assertThat(cpu.register(X), is(0x40)); } }
package com.google.javascript.clutz; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.*; import com.google.javascript.clutz.Options; import org.junit.Test; import org.kohsuke.args4j.CmdLineException; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class OptionsTest { @Test public void testFullUsage() throws Exception { Options opts = new Options(new String[] { "foo.js", "--externs", "extern1.js", "extern2.js", "-o", "output.d.ts" }); assertThat(opts.arguments).containsExactly("foo.js"); assertThat(opts.externs).containsExactly("extern1.js", "extern2.js").inOrder(); assertThat(opts.output).isEqualTo("output.d.ts"); } @Test public void testFilterSourcesDepgraphs() throws Exception { Options opts = new Options(new String[] { "javascript/closure/other_file_not_in_depgraph.js", "javascript/closure/string/string.js", "blaze-out/blah/my/blaze-out-file.js", "--externs", "extern1.js", "extern2.js", "--depgraphs", DepgraphTest.DEPGRAPH_PATH.toFile().toString(), "--depgraphs_filter_sources", "-o", "output.d.ts" }); // Outputs are filtered by what appears in the depgraph. assertThat(opts.arguments).containsExactly("javascript/closure/string/string.js", "blaze-out/blah/my/blaze-out-file.js").inOrder(); assertThat(opts.externs) .containsExactly("extern1.js", "extern2.js", "javascript/common/dom.js") .inOrder(); assertThat(opts.output).isEqualTo("output.d.ts"); } @Test public void testClosureEntryPoint() throws Exception { Options opts = new Options(new String[] { "foo.js", "--closure_entry_points", "ns.entryPoint1", "ns.entryPoint2", "--externs", "extern1.js", "extern2.js", "-o", "output.d.ts" }); assertThat(opts.arguments).containsExactly("foo.js"); assertThat(opts.entryPoints).containsExactly("ns.entryPoint1", "ns.entryPoint2"); assertThat(opts.externs).containsExactly("extern1.js", "extern2.js").inOrder(); assertThat(opts.output).isEqualTo("output.d.ts"); } @Test public void testHandleEmptyCommandLine() throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setErr(new PrintStream(out)); try { new Options(new String[0]); fail("Should throw"); } catch (CmdLineException expected) { assertThat(expected.getMessage()).isEqualTo("No files or externs were given"); } } @Test public void testShouldSupportExternsOnly() throws Exception { Options opts = new Options(new String[] { "--externs", "extern1.js"}); assertThat(opts.externs).containsExactly("extern1.js"); } }
package mil.nga.geopackage.io; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import mil.nga.geopackage.BoundingBox; import mil.nga.geopackage.GeoPackage; import mil.nga.geopackage.GeoPackageException; import mil.nga.geopackage.GeoPackageManager; import mil.nga.geopackage.contents.ContentsDataType; import mil.nga.geopackage.db.CoreSQLUtils; import mil.nga.geopackage.db.SQLUtils; import mil.nga.geopackage.db.master.SQLiteMaster; import mil.nga.geopackage.db.master.SQLiteMasterColumn; import mil.nga.geopackage.db.master.SQLiteMasterQuery; import mil.nga.geopackage.db.master.SQLiteMasterType; import mil.nga.geopackage.db.table.TableColumn; import mil.nga.geopackage.db.table.TableInfo; import mil.nga.geopackage.extension.coverage.CoverageData; import mil.nga.geopackage.extension.rtree.RTreeIndexExtension; import mil.nga.geopackage.features.columns.GeometryColumns; import mil.nga.geopackage.features.user.FeatureDao; import mil.nga.geopackage.features.user.FeatureRow; import mil.nga.geopackage.geom.GeoPackageGeometryData; import mil.nga.geopackage.srs.SpatialReferenceSystem; import mil.nga.geopackage.validate.GeoPackageValidate; import mil.nga.sf.Geometry; import mil.nga.sf.GeometryEnvelope; import mil.nga.sf.proj.Projection; import mil.nga.sf.proj.ProjectionConstants; import mil.nga.sf.proj.ProjectionFactory; import mil.nga.sf.proj.ProjectionTransform; import mil.nga.sf.util.GeometryEnvelopeBuilder; /** * Executes SQL on a SQLite database * * To run from command line, build with the standalone profile: * * mvn clean install -Pstandalone * * java -jar name.jar +usage_arguments * * java -classpath name.jar mil.nga.geopackage.io.SQLExec +usage_arguments * * @author osbornb * @since 3.3.0 */ public class SQLExec { /** * Argument prefix */ public static final String ARGUMENT_PREFIX = "-"; /** * Max Rows argument */ public static final String ARGUMENT_MAX_ROWS = "m"; /** * Default max rows */ public static final int DEFAULT_MAX_ROWS = 100; /** * Max column width argument */ public static final String ARGUMENT_MAX_COLUMN_WIDTH = "w"; /** * Default max column width */ public static final Integer DEFAULT_MAX_COLUMN_WIDTH = 120; /** * Max lines per row argument */ public static final String ARGUMENT_MAX_LINES_PER_ROW = "l"; /** * Default max lines per row */ public static final Integer DEFAULT_MAX_LINES_PER_ROW = null; /** * History pattern */ public static final Pattern HISTORY_PATTERN = Pattern.compile("^!-?\\d+$"); /** * Command prompt */ public static final String COMMAND_PROMPT = "sql> "; /** * Help command */ public static final String COMMAND_HELP = "help"; /** * Tables command */ public static final String COMMAND_TABLES = "tables"; /** * Indexes command */ public static final String COMMAND_INDEXES = "indexes"; /** * Views command */ public static final String COMMAND_VIEWS = "views"; /** * Triggers command */ public static final String COMMAND_TRIGGERS = "triggers"; /** * Command with all rows */ public static final int COMMAND_ALL_ROWS = 2147483646; /** * History command */ public static final String COMMAND_HISTORY = "history"; /** * Previous command */ public static final String COMMAND_PREVIOUS = "!!"; /** * Write blobs command */ public static final String COMMAND_WRITE_BLOBS = "blobs"; /** * Max rows command */ public static final String COMMAND_MAX_ROWS = "rows"; /** * Max column width command */ public static final String COMMAND_MAX_COLUMN_WIDTH = "width"; /** * Max lines per row command */ public static final String COMMAND_MAX_LINES_PER_ROW = "lines"; /** * Table Info command */ public static final String COMMAND_TABLE_INFO = "info"; /** * VACUUM command */ public static final String COMMAND_VACUUM = "vacuum"; /** * Foreign Keys command */ public static final String COMMAND_FOREIGN_KEYS = "fk"; /** * SQLite Master command */ public static final String COMMAND_FOREIGN_KEY_CHECK = "fkc"; /** * SQLite Master command */ public static final String COMMAND_INTEGRITY_CHECK = "integrity"; /** * Quick Check command */ public static final String COMMAND_QUICK_CHECK = "quick"; /** * SQLite Master command */ public static final String COMMAND_SQLITE_MASTER = "sqlite_master"; /** * GeoPackage contents command */ public static final String COMMAND_CONTENTS = "contents"; /** * GeoPackage Info command */ public static final String COMMAND_GEOPACKAGE_INFO = "ginfo"; /** * GeoPackage extensions command */ public static final String COMMAND_EXTENSIONS = "extensions"; /** * GeoPackage geometry command */ public static final String COMMAND_GEOMETRY = "geometry"; /** * Blob display value */ public static final String BLOB_DISPLAY_VALUE = "BLOB"; /** * Default write directory for blobs */ public static final String BLOBS_WRITE_DEFAULT_DIRECTORY = "blobs"; /** * Blobs extension argument */ public static final String BLOBS_ARGUMENT_EXTENSION = "e"; /** * Blobs directory argument */ public static final String BLOBS_ARGUMENT_DIRECTORY = "d"; /** * Blobs pattern argument */ public static final String BLOBS_ARGUMENT_PATTERN = "p"; /** * Blobs column start regex */ public static final String BLOBS_COLUMN_START_REGEX = "\\("; /** * Blobs column end regex */ public static final String BLOBS_COLUMN_END_REGEX = "\\)"; /** * GeoPackage contents bounds command */ public static final String COMMAND_CONTENTS_BOUNDS = "cbounds"; /** * GeoPackage bounds command */ public static final String COMMAND_BOUNDS = "bounds"; /** * GeoPackage table bounds command */ public static final String COMMAND_TABLE_BOUNDS = "tbounds"; /** * Bounds projection argument */ public static final String ARGUMENT_PROJECTION = "p"; /** * Bounds manual argument */ public static final String BOUNDS_ARGUMENT_MANUAL = "m"; /** * Blobs column pattern */ public static final Pattern BLOBS_COLUMN_PATTERN = Pattern .compile(BLOBS_COLUMN_START_REGEX + "([^" + BLOBS_COLUMN_END_REGEX + "]+)" + BLOBS_COLUMN_END_REGEX); /** * Blobs column pattern group */ public static final int BLOBS_COLUMN_PATTERN_GROUP = 1; /** * Bounds query type */ private static enum BoundsType { CONTENTS, ALL, TABLE; } /** * Main method to execute SQL in a SQLite database * * @param args * arguments * @throws Exception * upon failure */ public static void main(String[] args) throws Exception { boolean valid = true; boolean requiredArguments = false; File sqliteFile = null; Integer maxRows = DEFAULT_MAX_ROWS; Integer maxColumnWidth = DEFAULT_MAX_COLUMN_WIDTH; Integer maxLinesPerRow = DEFAULT_MAX_LINES_PER_ROW; StringBuilder sql = null; for (int i = 0; valid && i < args.length; i++) { String arg = args[i]; // Handle optional arguments if (arg.startsWith(ARGUMENT_PREFIX)) { String argument = arg.substring(ARGUMENT_PREFIX.length()); switch (argument) { case ARGUMENT_MAX_ROWS: if (i + 1 < args.length) { String maxRowsString = args[++i]; try { maxRows = Integer.valueOf(maxRowsString); } catch (NumberFormatException e) { valid = false; System.out.println("Error: Max Rows argument '" + arg + "' must be followed by a valid number. Invalid: " + maxRowsString); } maxRows = Math.max(0, maxRows); } else { valid = false; System.out.println("Error: Max Rows argument '" + arg + "' must be followed by a valid number"); } break; case ARGUMENT_MAX_COLUMN_WIDTH: if (i + 1 < args.length) { String maxColumnWidthString = args[++i]; try { maxColumnWidth = Integer .valueOf(maxColumnWidthString); } catch (NumberFormatException e) { valid = false; System.out.println( "Error: Max Column Width argument '" + arg + "' must be followed by a valid number. Invalid: " + maxColumnWidthString); } maxColumnWidth = Math.max(0, maxColumnWidth); } else { valid = false; System.out.println("Error: Max Column Width argument '" + arg + "' must be followed by a valid number"); } break; case ARGUMENT_MAX_LINES_PER_ROW: if (i + 1 < args.length) { String maxLinesPerRowString = args[++i]; try { maxLinesPerRow = Integer .valueOf(maxLinesPerRowString); } catch (NumberFormatException e) { valid = false; System.out.println( "Error: Max Lines Per Row argument '" + arg + "' must be followed by a valid number. Invalid: " + maxLinesPerRowString); } maxLinesPerRow = Math.max(0, maxLinesPerRow); } else { valid = false; System.out.println("Error: Max Lines Per Row argument '" + arg + "' must be followed by a valid number"); } break; default: valid = false; System.out.println("Error: Unsupported arg: '" + arg + "'"); } } else { // Set required arguments in order if (sqliteFile == null) { sqliteFile = new File(arg); requiredArguments = true; } else if (sql == null) { sql = new StringBuilder(arg); } else { sql.append(" ").append(arg); } } } if (!valid || !requiredArguments) { printUsage(); } else { // Create the file if it does not exist if (!GeoPackageManager.exists(sqliteFile)) { sqliteFile = GeoPackageManager.create(sqliteFile, false); } GeoPackage database = GeoPackageManager.open(sqliteFile, false); try { printInfo(database, maxRows, maxColumnWidth, maxLinesPerRow); if (sql != null) { try { SQLExecResult result = executeSQL(database, sql.toString(), maxRows); setPrintOptions(result, maxColumnWidth, maxLinesPerRow); result.printResults(); } catch (Exception e) { System.out.println(e); } } else { commandPrompt(database, maxRows, maxColumnWidth, maxLinesPerRow); } } finally { database.close(); } } } /** * Command prompt accepting SQL statements * * @param database * open database * @param maxRows * max rows * @param maxColumnWidth * max column width * @param maxLinesPerRow * max lines per row */ private static void commandPrompt(GeoPackage database, Integer maxRows, Integer maxColumnWidth, Integer maxLinesPerRow) { printHelp(database); List<String> history = new ArrayList<>(); Scanner scanner = new Scanner(System.in); try { StringBuilder sqlBuilder = new StringBuilder(); resetCommandPrompt(sqlBuilder); while (scanner.hasNextLine()) { try { String sqlLine = scanner.nextLine().trim(); int semicolon = sqlLine.indexOf(";"); boolean executeSql = semicolon >= 0; if (executeSql) { sqlLine = sqlLine.substring(0, semicolon + 1); } boolean singleLine = sqlBuilder.length() == 0; if (!sqlLine.isEmpty()) { if (!singleLine) { sqlBuilder.append(" "); } sqlBuilder.append(sqlLine); } if (singleLine) { if (executeSql) { sqlLine = sqlLine.substring(0, sqlLine.length() - 1) .trim(); } boolean command = true; String sqlLineLower = sqlLine.toLowerCase(); if (sqlLine.isEmpty()) { break; } else if (sqlLine.equalsIgnoreCase(COMMAND_HELP)) { printHelp(database); resetCommandPrompt(sqlBuilder); } else if (sqlLineLower.startsWith(COMMAND_TABLES)) { String name = sqlLine .substring(COMMAND_TABLES.length(), sqlLine.length()) .trim(); String sql = buildSqlMasterQuery(false, SQLiteMasterType.TABLE, name); executeSQL(database, sqlBuilder, sql, COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history); } else if (sqlLineLower.startsWith(COMMAND_INDEXES)) { String name = sqlLine .substring(COMMAND_INDEXES.length(), sqlLine.length()) .trim(); String sql = buildSqlMasterQuery(true, SQLiteMasterType.INDEX, name); executeSQL(database, sqlBuilder, sql, COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history); } else if (sqlLineLower.startsWith(COMMAND_VIEWS)) { String name = sqlLine .substring(COMMAND_VIEWS.length(), sqlLine.length()) .trim(); String sql = buildSqlMasterQuery(false, SQLiteMasterType.VIEW, name); executeSQL(database, sqlBuilder, sql, COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history); } else if (sqlLineLower.startsWith(COMMAND_TRIGGERS)) { String name = sqlLine .substring(COMMAND_TRIGGERS.length(), sqlLine.length()) .trim(); String sql = buildSqlMasterQuery(true, SQLiteMasterType.TRIGGER, name); executeSQL(database, sqlBuilder, sql, COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history); } else if (sqlLine.equalsIgnoreCase(COMMAND_HISTORY)) { for (int i = 0; i < history.size(); i++) { System.out.println( " " + String.format("%4d", i + 1) + " " + history.get(i)); } resetCommandPrompt(sqlBuilder); } else if (sqlLine.equalsIgnoreCase(COMMAND_PREVIOUS)) { executeSQL(database, sqlBuilder, history.size(), maxRows, maxColumnWidth, maxLinesPerRow, history); } else if (sqlLineLower .startsWith(COMMAND_WRITE_BLOBS)) { writeBlobs(database, sqlBuilder, maxRows, history, sqlLine.substring( COMMAND_WRITE_BLOBS.length())); } else if (HISTORY_PATTERN.matcher(sqlLine).matches()) { int historyNumber = Integer.parseInt( sqlLine.substring(1, sqlLine.length())); executeSQL(database, sqlBuilder, historyNumber, maxRows, maxColumnWidth, maxLinesPerRow, history); } else if (sqlLineLower.startsWith(COMMAND_MAX_ROWS)) { String maxRowsString = sqlLine .substring(COMMAND_MAX_ROWS.length(), sqlLine.length()) .trim(); if (!maxRowsString.isEmpty()) { maxRows = Integer.parseInt(maxRowsString); maxRows = Math.max(0, maxRows); } System.out.println( "Max Rows: " + printableValue(maxRows)); resetCommandPrompt(sqlBuilder); } else if (sqlLineLower .startsWith(COMMAND_MAX_COLUMN_WIDTH)) { String maxColumnWidthString = sqlLine.substring( COMMAND_MAX_COLUMN_WIDTH.length(), sqlLine.length()).trim(); if (!maxColumnWidthString.isEmpty()) { maxColumnWidth = Integer .parseInt(maxColumnWidthString); maxColumnWidth = Math.max(0, maxColumnWidth); } System.out.println("Max Column Width: " + printableValue(maxColumnWidth)); resetCommandPrompt(sqlBuilder); } else if (sqlLineLower .startsWith(COMMAND_MAX_LINES_PER_ROW)) { String maxLinesPerRowString = sqlLine.substring( COMMAND_MAX_LINES_PER_ROW.length(), sqlLine.length()).trim(); if (!maxLinesPerRowString.isEmpty()) { maxLinesPerRow = Integer .parseInt(maxLinesPerRowString); maxLinesPerRow = Math.max(0, maxLinesPerRow); } System.out.println("Max Lines Per Row: " + printableValue(maxLinesPerRow)); resetCommandPrompt(sqlBuilder); } else if (sqlLineLower .startsWith(COMMAND_TABLE_INFO)) { String tableName = sqlLine .substring(COMMAND_TABLE_INFO.length(), sqlLine.length()) .trim(); if (!tableName.isEmpty()) { executeSQL(database, sqlBuilder, "PRAGMA table_info(\"" + tableName + "\");", COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history); } else { printInfo(database, maxRows, maxColumnWidth, maxLinesPerRow); resetCommandPrompt(sqlBuilder); } } else if (sqlLine .equalsIgnoreCase(COMMAND_SQLITE_MASTER) || SQLiteMaster.count(database.getDatabase(), new SQLiteMasterType[] { SQLiteMasterType.TABLE, SQLiteMasterType.VIEW }, SQLiteMasterQuery.create( SQLiteMasterColumn.NAME, sqlLine)) > 0) { executeSQL(database, sqlBuilder, "SELECT * FROM \"" + sqlLine + "\";", maxRows, maxColumnWidth, maxLinesPerRow, history); } else if (sqlLineLower.startsWith(COMMAND_VACUUM)) { executeShortcutSQL(database, sqlBuilder, sqlLine, maxRows, maxColumnWidth, maxLinesPerRow, history, COMMAND_VACUUM, "VACUUM"); } else if (sqlLineLower .startsWith(COMMAND_FOREIGN_KEY_CHECK)) { executeShortcutSQL(database, sqlBuilder, sqlLine, maxRows, maxColumnWidth, maxLinesPerRow, history, COMMAND_FOREIGN_KEY_CHECK, "PRAGMA foreign_key_check"); } else if (sqlLineLower .startsWith(COMMAND_FOREIGN_KEYS)) { executeShortcutSQL(database, sqlBuilder, sqlLine, maxRows, maxColumnWidth, maxLinesPerRow, history, COMMAND_FOREIGN_KEYS, "PRAGMA foreign_keys"); } else if (sqlLineLower .startsWith(COMMAND_INTEGRITY_CHECK)) { executeShortcutSQL(database, sqlBuilder, sqlLine, maxRows, maxColumnWidth, maxLinesPerRow, history, COMMAND_INTEGRITY_CHECK, "PRAGMA integrity_check"); } else if (sqlLineLower .startsWith(COMMAND_QUICK_CHECK)) { executeShortcutSQL(database, sqlBuilder, sqlLine, maxRows, maxColumnWidth, maxLinesPerRow, history, COMMAND_QUICK_CHECK, "PRAGMA quick_check"); } else if (isGeoPackage(database)) { if (sqlLineLower.startsWith(COMMAND_CONTENTS)) { String tableName = sqlLine .substring(COMMAND_CONTENTS.length(), sqlLine.length()) .trim(); StringBuilder sql = new StringBuilder( "SELECT table_name, data_type FROM gpkg_contents"); if (!tableName.isEmpty()) { sql.append(" WHERE table_name LIKE "); sql.append( CoreSQLUtils.quoteWrap(tableName)); } sql.append(" ORDER BY table_name;"); executeSQL(database, sqlBuilder, sql.toString(), COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history); } else if (sqlLineLower .startsWith(COMMAND_GEOPACKAGE_INFO)) { String tableName = sqlLine.substring( COMMAND_GEOPACKAGE_INFO.length(), sqlLine.length()).trim(); if (!tableName.isEmpty()) { executeSQL(database, sqlBuilder, "SELECT * FROM gpkg_contents WHERE LOWER(table_name) = '" + tableName.toLowerCase() + "';", COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history, false); String tableType = database .getTableType(tableName); if (tableType != null) { switch (tableType) { case CoverageData.GRIDDED_COVERAGE: executeSQL(database, sqlBuilder, "SELECT * FROM gpkg_2d_gridded_coverage_ancillary WHERE tile_matrix_set_name = '" + tableName + "';", COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history, false); executeSQL(database, sqlBuilder, "SELECT * FROM gpkg_2d_gridded_tile_ancillary WHERE tpudt_name = '" + tableName + "';", COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history, false); break; } } ContentsDataType dataType = database .getTableDataType(tableName); if (dataType != null) { switch (dataType) { case ATTRIBUTES: break; case FEATURES: executeSQL(database, sqlBuilder, "SELECT * FROM gpkg_geometry_columns WHERE table_name = '" + tableName + "';", COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history, false); break; case TILES: executeSQL(database, sqlBuilder, "SELECT * FROM gpkg_tile_matrix_set WHERE table_name = '" + tableName + "';", COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history, false); executeSQL(database, sqlBuilder, "SELECT * FROM gpkg_tile_matrix WHERE table_name = '" + tableName + "';", COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history, false); break; } } executeSQL(database, sqlBuilder, "PRAGMA table_info(\"" + tableName + "\");", COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history, false); } resetCommandPrompt(sqlBuilder); } else if (sqlLineLower .startsWith(COMMAND_CONTENTS_BOUNDS) || sqlLineLower.startsWith(COMMAND_BOUNDS) || sqlLineLower .startsWith(COMMAND_TABLE_BOUNDS)) { BoundsType type = null; int commandLength; if (sqlLineLower .startsWith(COMMAND_CONTENTS_BOUNDS)) { type = BoundsType.CONTENTS; commandLength = COMMAND_CONTENTS_BOUNDS .length(); } else if (sqlLineLower .startsWith(COMMAND_TABLE_BOUNDS)) { type = BoundsType.TABLE; commandLength = COMMAND_TABLE_BOUNDS .length(); } else { type = BoundsType.ALL; commandLength = COMMAND_BOUNDS.length(); } bounds(database, sqlBuilder, type, sqlLine.substring(commandLength)); } else if (sqlLineLower .startsWith(COMMAND_EXTENSIONS)) { String tableName = sqlLine .substring(COMMAND_EXTENSIONS.length(), sqlLine.length()) .trim(); StringBuilder sql = new StringBuilder( "SELECT table_name, column_name, extension_name, definition FROM gpkg_extensions"); if (!tableName.isEmpty()) { sql.append( " WHERE LOWER(table_name) LIKE "); sql.append(CoreSQLUtils.quoteWrap( tableName.toLowerCase())); } sql.append(";"); executeSQL(database, sqlBuilder, sql.toString(), COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history); } else if (sqlLineLower .startsWith(COMMAND_GEOMETRY)) { geometries(database, sqlBuilder, maxRows, history, sqlLine.substring( COMMAND_GEOMETRY.length(), sqlLine.length())); } else { String[] parts = sqlLine.split("\\s+"); String dataType = parts[0]; if (ContentsDataType.fromName( dataType.toLowerCase()) != null || !database .getTables( dataType.toLowerCase()) .isEmpty() || !database.getTables(dataType) .isEmpty()) { StringBuilder sql = new StringBuilder( "SELECT table_name FROM gpkg_contents WHERE LOWER(data_type) = '"); sql.append(dataType.toLowerCase()); sql.append("'"); if (parts.length > 0) { String tableName = sqlLine .substring(dataType.length(), sqlLine.length()) .trim(); if (!tableName.isEmpty()) { sql.append(" AND table_name LIKE "); sql.append(CoreSQLUtils .quoteWrap(tableName)); } } sql.append(" ORDER BY table_name;"); executeSQL(database, sqlBuilder, sql.toString(), COMMAND_ALL_ROWS, maxColumnWidth, maxLinesPerRow, history); } else { command = false; } } } else { command = false; } if (command) { executeSql = false; } } if (executeSql) { executeSQL(database, sqlBuilder, sqlBuilder.toString(), maxRows, maxColumnWidth, maxLinesPerRow, history); } } catch (Exception e) { System.out.println(e); resetCommandPrompt(sqlBuilder); } } } finally { scanner.close(); } } /** * Build a SQLite Master table query * * @param tableName * true to include table name * @param type * SQLite Master type * @param name * name LIKE value * @return SQL */ private static String buildSqlMasterQuery(boolean tableName, SQLiteMasterType type, String name) { StringBuilder sql = new StringBuilder("SELECT "); sql.append(SQLiteMasterColumn.NAME.name().toLowerCase()); if (tableName) { sql.append(", "); sql.append(SQLiteMasterColumn.TBL_NAME.name().toLowerCase()); } sql.append(" FROM "); sql.append(SQLiteMaster.TABLE_NAME); sql.append(" WHERE "); sql.append(SQLiteMasterColumn.TYPE.name().toLowerCase()); sql.append(" = '"); sql.append(type.name().toLowerCase()); sql.append("' AND "); sql.append(SQLiteMasterColumn.NAME.name().toLowerCase()); sql.append(" NOT LIKE 'sqlite_%'"); if (name != null) { name = name.trim(); if (!name.isEmpty()) { sql.append(" AND "); sql.append(SQLiteMasterColumn.NAME.name().toLowerCase()); sql.append(" LIKE "); sql.append(CoreSQLUtils.quoteWrap(name)); } } sql.append(" ORDER BY "); sql.append(SQLiteMasterColumn.NAME.name().toLowerCase()); sql.append(";"); return sql.toString(); } /** * Print header information * * @param database * database * @param maxRows * max rows * @param maxColumnWidth * max column width * @param maxLinesPerRow * max lines per row */ private static void printInfo(GeoPackage database, Integer maxRows, Integer maxColumnWidth, Integer maxLinesPerRow) { boolean isGeoPackage = isGeoPackage(database); System.out.println(); if (isGeoPackage) { System.out.print("GeoPackage"); } else { System.out.print("Database"); } System.out.println(": " + database.getName()); System.out.println("Path: " + database.getPath()); System.out.println("Size: " + database.readableSize() + " (" + database.size() + " bytes)"); Integer applicationId = database.getApplicationIdInteger(); if (applicationId != null) { System.out.println("Application ID: " + applicationId + ", " + database.getApplicationIdHex() + ", " + database.getApplicationId()); } Integer userVersion = database.getUserVersion(); if (userVersion != null) { System.out.println("User Version: " + userVersion); } System.out.println("Max Rows: " + printableValue(maxRows)); System.out .println("Max Column Width: " + printableValue(maxColumnWidth)); System.out.println( "Max Lines Per Row: " + printableValue(maxLinesPerRow)); } /** * Print the command prompt help * * @param database * database */ private static void printHelp(GeoPackage database) { boolean isGeoPackage = isGeoPackage(database); System.out.println(); System.out.println("- Supports most SQLite statements including:"); System.out.println( "\tSELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, PRAGMA, VACUUM, etc"); System.out.println("- Terminate SQL statements with a ;"); System.out.println("- Exit with a single empty line"); System.out.println(); System.out.println("Commands:"); System.out.println(); System.out.println("\t" + COMMAND_TABLE_INFO + " - " + (isGeoPackage ? "GeoPackage" : "Database") + " information"); System.out.println("\t" + COMMAND_HELP + " - print this help information"); System.out.println("\t" + COMMAND_TABLES + " [name] - list database tables (all or LIKE table name)"); System.out.println("\t" + COMMAND_INDEXES + " [name] - list database indexes (all or LIKE index name)"); System.out.println("\t" + COMMAND_VIEWS + " [name] - list database views (all or LIKE view name)"); System.out.println("\t" + COMMAND_TRIGGERS + " [name] - list database triggers (all or LIKE trigger name)"); System.out.println("\t" + COMMAND_MAX_ROWS + " [n] - display or set the max rows per query"); System.out.println("\t" + COMMAND_MAX_COLUMN_WIDTH + " [n] - display or set the max width (in characters) per column"); System.out.println("\t" + COMMAND_MAX_LINES_PER_ROW + " [n] - display or set the max lines per row"); System.out.println("\t" + COMMAND_HISTORY + " - list successfully executed sql commands"); System.out.println("\t" + COMMAND_PREVIOUS + " - re-execute the previous successful sql command"); System.out.println( "\t!n - re-execute a sql statement by history id n"); System.out.println( "\t!-n - re-execute a sql statement n commands back in history"); System.out.println("\t" + COMMAND_WRITE_BLOBS + " [" + ARGUMENT_PREFIX + BLOBS_ARGUMENT_EXTENSION + " file_extension] [" + ARGUMENT_PREFIX + BLOBS_ARGUMENT_DIRECTORY + " directory] [" + ARGUMENT_PREFIX + BLOBS_ARGUMENT_PATTERN + " pattern]"); System.out.println( "\t - write blobs from the previous successful sql command to the file system"); System.out.println( "\t ([directory]|blobs)/table_name/column_name/(pk_values|result_index|[pattern])[.file_extension]"); System.out.println( "\t file_extension - file extension added to each saved blob file"); System.out.println( "\t directory - base directory to save table_name/column_name/blobs (default is ./" + BLOBS_WRITE_DEFAULT_DIRECTORY + ")"); System.out.println( "\t pattern - file directory and/or name pattern consisting of column names in parentheses"); System.out.println( "\t (column_name)-(column_name2)"); System.out.println( "\t (column_name)/(column_name2)"); System.out.println("\t" + COMMAND_TABLE_INFO + " <name> - PRAGMA table_info(<name>);"); System.out.println("\t" + COMMAND_SQLITE_MASTER + " - SELECT * FROM " + COMMAND_SQLITE_MASTER + ";"); System.out.println("\t<name> - SELECT * FROM <name>;"); System.out.println("\t" + COMMAND_VACUUM + " - VACUUM [INTO 'filename'];"); System.out.println("\t" + COMMAND_FOREIGN_KEYS + " - PRAGMA foreign_keys [= boolean];"); System.out.println("\t" + COMMAND_FOREIGN_KEY_CHECK + " - PRAGMA foreign_key_check[(<table-name>)];"); System.out.println("\t" + COMMAND_INTEGRITY_CHECK + " - PRAGMA integrity_check[(N)];"); System.out.println("\t" + COMMAND_QUICK_CHECK + " - PRAGMA quick_check[(N)];"); if (isGeoPackage) { System.out.println("\t" + COMMAND_CONTENTS + " [name] - List GeoPackage contents (all or LIKE table name)"); System.out.println("\t" + ContentsDataType.ATTRIBUTES.getName() + " [name] - List GeoPackage attributes tables (all or LIKE table name)"); System.out.println("\t" + ContentsDataType.FEATURES.getName() + " [name] - List GeoPackage feature tables (all or LIKE table name)"); System.out.println("\t" + ContentsDataType.TILES.getName() + " [name] - List GeoPackage tile tables (all or LIKE table name)"); System.out.println("\t" + COMMAND_GEOPACKAGE_INFO + " <name> - Query GeoPackage metadata for the table name"); System.out.println( "\t" + COMMAND_CONTENTS_BOUNDS + " [" + ARGUMENT_PREFIX + ARGUMENT_PROJECTION + " projection] [name]"); System.out.println( "\t - Determine the bounds (using only the contents) of the entire GeoPackage or single table name"); System.out.println( "\t projection - desired projection as 'authority:code' or 'epsg_code'"); System.out.println("\t" + COMMAND_BOUNDS + " [" + ARGUMENT_PREFIX + ARGUMENT_PROJECTION + " projection] [" + ARGUMENT_PREFIX + BOUNDS_ARGUMENT_MANUAL + "] [name]"); System.out.println( "\t - Determine the bounds of the entire GeoPackage or single table name"); System.out.println( "\t projection - desired projection as 'authority:code' or 'epsg_code'"); System.out.println("\t " + BOUNDS_ARGUMENT_MANUAL + " - manually query unindexed tables"); System.out.println("\t" + COMMAND_TABLE_BOUNDS + " [" + ARGUMENT_PREFIX + ARGUMENT_PROJECTION + " projection] [" + ARGUMENT_PREFIX + BOUNDS_ARGUMENT_MANUAL + "] [name]"); System.out.println( "\t - Determine the bounds (using only table metadata) of the entire GeoPackage or single table name"); System.out.println( "\t projection - desired projection as 'authority:code' or 'epsg_code'"); System.out.println("\t " + BOUNDS_ARGUMENT_MANUAL + " - manually query unindexed tables"); System.out.println("\t" + COMMAND_EXTENSIONS + " [name] - List GeoPackage extensions (all or LIKE table name)"); System.out.println( "\t" + COMMAND_GEOMETRY + " <name> [-p projection] [ids]"); System.out.println( "\t - Display feature table geometries as Well-Known Text"); System.out.println( "\t projection - desired display projection as 'authority:code' or 'epsg_code'"); System.out.println( "\t ids - single or comma delimited feature table row ids"); System.out.println("\t" + COMMAND_GEOMETRY + " <name> [-p projection] <id> <wkt>"); System.out.println( "\t - Update or insert a feature table geometry with Well-Known Text"); System.out.println( "\t projection - Well-Known Text projection as 'authority:code' or 'epsg_code'"); System.out.println( "\t id - single feature table row id to update or -1 to insert a new row"); System.out.println( "\t wkt - Well-Known Text"); } System.out.println(); System.out.println("Special Supported Cases:"); System.out.println(); System.out.println("\tDrop Column - Not natively supported in SQLite"); System.out.println( "\t * ALTER TABLE table_name DROP column_name"); System.out.println( "\t * ALTER TABLE table_name DROP COLUMN column_name"); System.out.println("\tCopy Table - Not a traditional SQL statment"); System.out.println( "\t * ALTER TABLE table_name COPY TO new_table_name"); if (isGeoPackage) { System.out.println( "\tRename Table - User tables are updated throughout the GeoPackage"); System.out.println( "\t * ALTER TABLE table_name RENAME TO new_table_name"); System.out.println( "\tDrop Table - User tables are dropped throughout the GeoPackage"); System.out.println("\t * DROP TABLE table_name"); } } /** * Execute the SQL * * @param database * database * @param sqlBuilder * SQL builder * @param historyNumber * history number * @param maxRows * max rows * @param maxColumnWidth * max column width * @param maxLinesPerRow * max lines per row * @param history * history * @throws SQLException * upon error */ private static void executeSQL(GeoPackage database, StringBuilder sqlBuilder, int historyNumber, Integer maxRows, Integer maxColumnWidth, Integer maxLinesPerRow, List<String> history) throws SQLException { int number = historyNumber; if (number < 0) { number += history.size(); } else { number } if (number >= 0 && number < history.size()) { String sql = history.get(number); System.out.println(sql); executeSQL(database, sqlBuilder, sql, maxRows, maxColumnWidth, maxLinesPerRow, history); } else { System.out.println("No History at " + historyNumber); resetCommandPrompt(sqlBuilder); } } /** * Execute the SQL * * @param database * database * @param sqlBuilder * SQL builder * @param sql * SQL statement * @param maxRows * max rows * @param maxColumnWidth * max column width * @param maxLinesPerRow * max lines per row * @param history * history * @throws SQLException * upon error */ private static void executeSQL(GeoPackage database, StringBuilder sqlBuilder, String sql, Integer maxRows, Integer maxColumnWidth, Integer maxLinesPerRow, List<String> history) throws SQLException { executeSQL(database, sqlBuilder, sql, maxRows, maxColumnWidth, maxLinesPerRow, history, true); } /** * Execute the SQL * * @param database * database * @param sqlBuilder * SQL builder * @param sql * SQL statement * @param maxRows * max rows * @param maxColumnWidth * max column width * @param maxLinesPerRow * max lines per row * @param history * history * @param resetCommandPrompt * reset command prompt * @throws SQLException * upon error */ private static void executeSQL(GeoPackage database, StringBuilder sqlBuilder, String sql, Integer maxRows, Integer maxColumnWidth, Integer maxLinesPerRow, List<String> history, boolean resetCommandPrompt) throws SQLException { executeSQL(database, sqlBuilder, sql, maxRows, maxColumnWidth, maxLinesPerRow, history, resetCommandPrompt, true); } /** * Execute the SQL * * @param database * database * @param sqlBuilder * SQL builder * @param sql * SQL statement * @param maxRows * max rows * @param maxColumnWidth * max column width * @param maxLinesPerRow * max lines per row * @param history * history * @param resetCommandPrompt * reset command prompt * @param printSides * true to print table sides * @throws SQLException * upon error */ private static void executeSQL(GeoPackage database, StringBuilder sqlBuilder, String sql, Integer maxRows, Integer maxColumnWidth, Integer maxLinesPerRow, List<String> history, boolean resetCommandPrompt, boolean printSides) throws SQLException { executeSQL(database, sqlBuilder, sql, null, maxRows, maxColumnWidth, maxLinesPerRow, history, resetCommandPrompt, printSides); } /** * Execute the SQL * * @param database * database * @param sqlBuilder * SQL builder * @param sql * SQL statement * @param projection * desired projection * @param maxRows * max rows * @param maxColumnWidth * max column width * @param maxLinesPerRow * max lines per row * @param history * history * @param resetCommandPrompt * reset command prompt * @param printSides * true to print table sides * @throws SQLException * upon error */ private static void executeSQL(GeoPackage database, StringBuilder sqlBuilder, String sql, Projection projection, Integer maxRows, Integer maxColumnWidth, Integer maxLinesPerRow, List<String> history, boolean resetCommandPrompt, boolean printSides) throws SQLException { SQLExecResult result = executeSQL(database, sql, projection, maxRows); setPrintOptions(result, maxColumnWidth, maxLinesPerRow); result.setPrintSides(printSides); result.printResults(); history.add(sql); if (resetCommandPrompt) { resetCommandPrompt(sqlBuilder); } } /** * Set print formatting options * * @param result * result * @param maxColumnWidth * max column width * @param maxLinesPerRow * max lines per row */ private static void setPrintOptions(SQLExecResult result, Integer maxColumnWidth, Integer maxLinesPerRow) { // If no max column width, use the default if (maxColumnWidth == null) { maxColumnWidth = DEFAULT_MAX_COLUMN_WIDTH; } // If no max lines per row, use the default if (maxLinesPerRow == null) { maxLinesPerRow = DEFAULT_MAX_LINES_PER_ROW; } result.setMaxColumnWidth(maxColumnWidth); result.setMaxLinesPerRow(maxLinesPerRow); } /** * Execute the SQL on the database * * @param database * database * @param sqlBuilder * SQL builder * @param sql * SQL statement * @param maxRows * max rows * @param maxColumnWidth * max column width * @param maxLinesPerRow * max lines per row * @param history * history * @param shortcut * shortcut command * @param replacement * shortcut replacement command * @throws SQLException * upon SQL error */ private static void executeShortcutSQL(GeoPackage database, StringBuilder sqlBuilder, String sql, Integer maxRows, Integer maxColumnWidth, Integer maxLinesPerRow, List<String> history, String shortcut, String replacement) throws SQLException { String replacedSql = replacement + sql.substring(shortcut.length()); executeSQL(database, sqlBuilder, replacedSql, maxRows, maxColumnWidth, maxLinesPerRow, history); } /** * Reset the command prompt * * @param sqlBuilder * sql builder */ private static void resetCommandPrompt(StringBuilder sqlBuilder) { sqlBuilder.setLength(0); System.out.println(); System.out.print(COMMAND_PROMPT); } /** * Execute the SQL on the database * * @param databaseFile * database file * @param sql * SQL statement * @return results * @throws SQLException * upon SQL error */ public static SQLExecResult executeSQL(File databaseFile, String sql) throws SQLException { return executeSQL(databaseFile, sql, null); } /** * Execute the SQL on the database * * @param databaseFile * database file * @param sql * SQL statement * @param maxRows * max rows * @return results * @throws SQLException * upon SQL error */ public static SQLExecResult executeSQL(File databaseFile, String sql, Integer maxRows) throws SQLException { SQLExecResult result = null; GeoPackage database = GeoPackageManager.open(databaseFile); try { result = executeSQL(database, sql, maxRows); } finally { database.close(); } return result; } /** * Execute the SQL on the database * * @param database * open database * @param sql * SQL statement * @return results * @throws SQLException * upon SQL error */ public static SQLExecResult executeSQL(GeoPackage database, String sql) throws SQLException { return executeSQL(database, sql, null); } /** * Execute the SQL on the GeoPackage database * * @param database * open database * @param sql * SQL statement * @param maxRows * max rows * @return results * @throws SQLException * upon SQL error */ public static SQLExecResult executeSQL(GeoPackage database, String sql, Integer maxRows) throws SQLException { return executeSQL(database, sql, null, maxRows); } /** * Execute the SQL on the GeoPackage database * * @param database * open database * @param sql * SQL statement * @param projection * desired projection * @param maxRows * max rows * @return results * @throws SQLException * upon SQL error */ public static SQLExecResult executeSQL(GeoPackage database, String sql, Projection projection, Integer maxRows) throws SQLException { sql = sql.trim(); RTreeIndexExtension rtree = new RTreeIndexExtension(database); if (rtree.has()) { rtree.createAllFunctions(); } SQLExecResult result = SQLExecAlterTable.alterTable(database, sql); if (result == null) { result = executeQuery(database, sql, projection, maxRows); } return result; } /** * Execute the query against the database * * @param database * open database * @param sql * SQL statement * @param projection * desired projection * @param maxRows * max rows * @return results * @throws SQLException * upon SQL error */ private static SQLExecResult executeQuery(GeoPackage database, String sql, Projection projection, Integer maxRows) throws SQLException { SQLExecResult result = new SQLExecResult(); if (!sql.equals(";")) { PreparedStatement statement = null; try { statement = database.getConnection().getConnection() .prepareStatement(sql); if (maxRows != null) { statement.setMaxRows(maxRows); result.setMaxRows(maxRows); } boolean hasResultSet = statement.execute(); if (hasResultSet) { ResultSet resultSet = statement.getResultSet(); ResultSetMetaData metadata = resultSet.getMetaData(); int numColumns = metadata.getColumnCount(); int[] columnWidths = new int[numColumns]; int[] columnTypes = new int[numColumns]; boolean isGeoPackage = isGeoPackage(database); Map<String, GeometryColumns> tableGeometryColumns = new HashMap<>(); Map<Integer, ProjectionTransform> geometryColumns = new HashMap<>(); for (int col = 1; col <= numColumns; col++) { String tableName = metadata.getTableName(col); result.addTable(tableName); String columnName = metadata.getColumnName(col); result.addColumn(columnName); columnTypes[col - 1] = metadata.getColumnType(col); columnWidths[col - 1] = columnName.length(); // Determine if the column is a GeoPackage geometry if (isGeoPackage) { GeometryColumns geometryColumn = null; if (tableGeometryColumns.containsKey(tableName)) { geometryColumn = tableGeometryColumns .get(tableName); } else { if (database.isFeatureTable(tableName)) { geometryColumn = database .getGeometryColumnsDao() .queryForTableName(tableName); } tableGeometryColumns.put(tableName, geometryColumn); } if (geometryColumn != null && geometryColumn.getColumnName() .equalsIgnoreCase(columnName)) { ProjectionTransform transform = null; if (projection != null) { transform = geometryColumn.getProjection() .getTransformation(projection); } geometryColumns.put(col, transform); } } } while (resultSet.next()) { List<String> row = new ArrayList<>(); result.addRow(row); for (int col = 1; col <= numColumns; col++) { String stringValue = null; Object value = resultSet.getObject(col); if (value != null) { switch (columnTypes[col - 1]) { case Types.BLOB: stringValue = BLOB_DISPLAY_VALUE; if (geometryColumns.containsKey(col)) { ProjectionTransform transform = geometryColumns .get(col); byte[] bytes = (byte[]) value; try { if (transform == null) { stringValue = GeoPackageGeometryData .wkt(bytes); } else { GeoPackageGeometryData geometryData = GeoPackageGeometryData .create(bytes); stringValue = geometryData .transform(transform) .getWkt(); } } catch (IOException e) { } } break; default: stringValue = value.toString().replaceAll( "\\s*[\\r\\n]+\\s*", " "); } int valueLength = stringValue.length(); if (valueLength > columnWidths[col - 1]) { columnWidths[col - 1] = valueLength; } } row.add(stringValue); } } result.addColumnWidths(columnWidths); } else { int updateCount = statement.getUpdateCount(); if (updateCount >= 0) { result.setUpdateCount(updateCount); } } } finally { SQLUtils.closeStatement(statement, sql); } } return result; } /** * Write blobs from the query * * @param database * database * @param sqlBuilder * SQL builder * @param maxRows * max rows * @param history * history * @param args * write blob arguments * @throws SQLException * upon error * @throws IOException * upon error */ private static void writeBlobs(GeoPackage database, StringBuilder sqlBuilder, Integer maxRows, List<String> history, String args) throws SQLException, IOException { if (history.isEmpty()) { System.out.println("No previous query with blobs"); } else { boolean valid = true; String extension = null; String directory = null; String pattern = null; List<String> patternColumns = new ArrayList<>(); if (args != null && !args.isEmpty()) { String[] argParts = args.trim().split("\\s+"); for (int i = 0; valid && i < argParts.length; i++) { String arg = argParts[i]; if (arg.startsWith(ARGUMENT_PREFIX)) { String argument = arg .substring(ARGUMENT_PREFIX.length()); switch (argument) { case BLOBS_ARGUMENT_EXTENSION: if (i + 1 < argParts.length) { extension = argParts[++i]; } else { valid = false; System.out.println( "Error: Blobs extension argument '" + arg + "' must be followed by a file extension"); } break; case BLOBS_ARGUMENT_DIRECTORY: if (i + 1 < argParts.length) { directory = argParts[++i]; } else { valid = false; System.out.println( "Error: Blobs directory argument '" + arg + "' must be followed by a directory location"); } break; case BLOBS_ARGUMENT_PATTERN: if (i + 1 < argParts.length) { pattern = argParts[++i]; Matcher matcher = BLOBS_COLUMN_PATTERN .matcher(pattern); while (matcher.find()) { String columnName = matcher .group(BLOBS_COLUMN_PATTERN_GROUP); patternColumns.add(columnName); } if (patternColumns.isEmpty()) { valid = false; System.out.println( "Error: Blobs pattern argument '" + arg + "' must be followed by a save pattern with at least one column surrounded by parentheses"); } } else { valid = false; System.out.println( "Error: Blobs pattern argument '" + arg + "' must be followed by a save pattern"); } break; default: valid = false; System.out.println( "Error: Unsupported arg: '" + arg + "'"); } } else { valid = false; System.out.println( "Error: Unsupported arg: '" + arg + "'"); } } } if (valid) { String sql = history.get(history.size() - 1); Set<String> blobsWritten = new LinkedHashSet<>(); int blobsWrittenCount = 0; PreparedStatement statement = null; try { statement = database.getConnection().getConnection() .prepareStatement(sql); if (maxRows != null) { statement.setMaxRows(maxRows); } boolean hasResultSet = statement.execute(); if (hasResultSet) { ResultSet resultSet = statement.getResultSet(); ResultSetMetaData metadata = resultSet.getMetaData(); int numColumns = metadata.getColumnCount(); List<Integer> blobColumns = new ArrayList<>(); List<String> tables = new ArrayList<>(); List<String> columnNames = new ArrayList<>(); Map<String, List<Integer>> tableNameColumns = new HashMap<>(); Map<String, Integer> columnNameIndexes = new HashMap<>(); for (int col = 1; col <= numColumns; col++) { columnNameIndexes.put(metadata.getColumnName(col), col); } for (int col = 1; col <= numColumns; col++) { if (metadata.getColumnType(col) == Types.BLOB) { blobColumns.add(col); String tableName = metadata.getTableName(col); List<Integer> nameColumns = tableNameColumns .get(tableName); if (nameColumns == null) { nameColumns = new ArrayList<>(); TableInfo tableInfo = TableInfo.info( database.getConnection(), tableName); List<String> nameColumnNames = null; if (pattern != null) { nameColumnNames = patternColumns; } else if (tableInfo.hasPrimaryKey()) { nameColumnNames = new ArrayList<>(); for (TableColumn tableColumn : tableInfo .getPrimaryKeys()) { nameColumnNames .add(tableColumn.getName()); } } if (nameColumnNames != null) { for (String columnName : nameColumnNames) { Integer columnIndex = columnNameIndexes .get(columnName); if (columnIndex == null && pattern != null) { throw new IllegalArgumentException( "Pattern column not found in query: " + columnName); } nameColumns.add(columnIndex); } } tableNameColumns.put(tableName, nameColumns); } tables.add(tableName); columnNames.add(metadata.getColumnName(col)); } } if (!blobColumns.isEmpty()) { if (extension != null && !extension.startsWith(".")) { extension = "." + extension; } if (directory == null) { directory = BLOBS_WRITE_DEFAULT_DIRECTORY; } File blobsDirectory = new File(directory); int resultCount = 0; while (resultSet.next()) { resultCount++; for (int i = 0; i < blobColumns.size(); i++) { int col = blobColumns.get(i); byte[] blobBytes = resultSet.getBytes(col); if (blobBytes != null) { String tableName = tables.get(i); File tableDirectory = new File( blobsDirectory, tableName); File columnDirectory = new File( tableDirectory, columnNames.get(i)); String name = null; if (pattern != null) { name = pattern; } List<Integer> nameColumns = tableNameColumns .get(tableName); if (!nameColumns.isEmpty()) { for (int j = 0; j < nameColumns .size(); j++) { Integer nameColumn = nameColumns .get(j); if (nameColumn != null) { String columnValue = resultSet .getString( nameColumn); if (columnValue != null) { if (pattern != null) { String columnName = patternColumns .get(j); name = name .replaceAll( BLOBS_COLUMN_START_REGEX + columnName + BLOBS_COLUMN_END_REGEX, columnValue); } else if (name == null) { name = columnValue; } else { name += "-" + columnValue; } } } } } if (name == null) { name = String.valueOf(resultCount); } if (extension != null) { name += extension; } File blobFile = new File( columnDirectory, name); blobFile.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream( blobFile); fos.write(blobBytes); fos.close(); blobsWrittenCount++; blobsWritten.add(columnDirectory .getAbsolutePath()); } } } } } } finally { SQLUtils.closeStatement(statement, sql); } if (blobsWrittenCount <= 0) { System.out.println("No Blobs in previous query: " + sql); } else { System.out .println(blobsWrittenCount + " Blobs written to:"); for (String location : blobsWritten) { System.out.println(location); } } } } resetCommandPrompt(sqlBuilder); } /** * Print or update geometries * * @param database * database * @param sqlBuilder * SQL builder * @param maxRows * max rows * @param history * history * @param args * write blob arguments * @throws SQLException * upon error * @throws IOException * upon error */ private static void geometries(GeoPackage database, StringBuilder sqlBuilder, Integer maxRows, List<String> history, String args) throws SQLException, IOException { String[] parts = args.trim().split("\\s+"); boolean valid = true; String tableName = null; String ids = null; Long singleId = null; Projection projection = null; StringBuilder wktBuilder = null; for (int i = 0; valid && i < parts.length; i++) { String arg = parts[i]; if (arg.startsWith(ARGUMENT_PREFIX)) { if (wktBuilder != null) { valid = false; System.out.println("Error: Unexpected argument '" + arg + "' after expected Well-Known Text: " + wktBuilder.toString()); } else { String argument = arg.substring(ARGUMENT_PREFIX.length()); switch (argument) { case ARGUMENT_PROJECTION: if (i + 1 < parts.length) { String projectionArugment = parts[++i]; projection = getProjection(projectionArugment); if (projection == null) { valid = false; } } else { valid = false; System.out.println("Error: Projection argument '" + arg + "' must be followed by 'authority:code' or 'epsg_code'"); } break; default: valid = false; System.out.println( "Error: Unsupported arg: '" + arg + "'"); } } } else { if (tableName == null) { tableName = arg; if (!database.isFeatureTable(tableName)) { valid = false; if (tableName.isEmpty()) { System.out.println("Error: Feature table required"); } else { System.out.println("Error: '" + tableName + "' is not a feature table"); } } } else if (ids == null) { ids = arg; if (ids.indexOf(",") == -1) { try { singleId = Long.parseLong(ids); } catch (NumberFormatException e) { valid = false; System.out.println("Error: Invalid single row id '" + ids + "'"); } } } else if (singleId == null) { valid = false; System.out.println("Error: Unexpected additional argument '" + arg + "' for multiple id query"); } else { if (wktBuilder == null) { wktBuilder = new StringBuilder(); } else { wktBuilder.append(" "); } wktBuilder.append(arg); } } } if (tableName == null) { valid = false; System.out.println("Error: Feature table required"); } if (valid) { FeatureDao featureDao = database.getFeatureDao(tableName); if (wktBuilder != null) { String wkt = wktBuilder.toString().trim(); if (wkt.startsWith("'") || wkt.startsWith("\"")) { wkt = wkt.substring(1); } if (wkt.endsWith("'") || wkt.endsWith("\"")) { wkt = wkt.substring(0, wkt.length() - 1); } GeoPackageGeometryData geometryData = GeoPackageGeometryData .createFromWktAndBuildEnvelope(featureDao.getSrsId(), wkt); if (projection != null) { ProjectionTransform transform = projection .getTransformation(featureDao.getProjection()); if (!transform.isSameProjection()) { geometryData = geometryData.transform(transform); } } FeatureRow featureRow = null; if (singleId == -1) { featureRow = featureDao.newRow(); featureRow.setGeometry(geometryData); singleId = featureDao.insert(featureRow); System.out.println(); System.out.println("Inserted Row Id: " + singleId); } else { featureRow = featureDao.queryForIdRow(singleId); if (featureRow != null) { featureRow.setGeometry(geometryData); featureDao.update(featureRow); System.out.println(); System.out.println("Updated Row Id: " + singleId); } else { System.out.println( "Error: No row found for feature table '" + tableName + "' with id '" + singleId + "'"); } } if (featureRow != null) { featureRow = featureDao.queryForIdRow(singleId); if (featureRow != null) { printGeometryData(database, featureDao, featureRow.getGeometry()); } } } else { StringBuilder sql = new StringBuilder("SELECT " + CoreSQLUtils .quoteWrap(featureDao.getGeometryColumnName()) + " FROM " + CoreSQLUtils.quoteWrap(tableName)); if (ids != null) { sql.append(" WHERE " + CoreSQLUtils .quoteWrap(featureDao.getIdColumnName()) + " IN (" + ids + ")"); } if (singleId != null) { FeatureRow featureRow = featureDao.queryForIdRow(singleId); if (featureRow != null) { GeoPackageGeometryData geometryData = featureRow .getGeometry(); if (projection != null) { ProjectionTransform transform = featureDao .getProjection() .getTransformation(projection); if (!transform.isSameProjection()) { geometryData = geometryData .transform(transform); } } printGeometryDataHeader(database, featureDao, geometryData, projection); } } executeSQL(database, sqlBuilder, sql.toString(), projection, COMMAND_ALL_ROWS, 0, 0, history, false, false); } } resetCommandPrompt(sqlBuilder); } /** * Print the geometry data * * @param geometryData * geometry data * @throws SQLException * upon error */ private static void printGeometryData(GeoPackage database, FeatureDao featureDao, GeoPackageGeometryData geometryData) throws SQLException { printGeometryDataHeader(database, featureDao, geometryData, null); System.out.println(); System.out.println(geometryData.getWkt()); } /** * Print the geometry data header * * @param database * database * @param featureDao * feature dao * @param geometryData * geometry data * @param projection * transformed projection * @throws SQLException * upon error */ private static void printGeometryDataHeader(GeoPackage database, FeatureDao featureDao, GeoPackageGeometryData geometryData, Projection projection) throws SQLException { System.out.println(); if (projection == null) { int srsId = geometryData.getSrsId(); SpatialReferenceSystem geometrySrs = database .getSpatialReferenceSystemDao().queryForId((long) srsId); if (geometrySrs != null) { projection = geometrySrs.getProjection(); } } if (projection != null) { System.out.println("Projection: " + projection); } Projection featureProjection = featureDao.getProjection(); if (projection == null || !projection.equals(featureProjection)) { System.out.println("Table Projection: " + featureProjection); } GeometryEnvelope envelope = geometryData.getEnvelope(); if (envelope != null) { System.out.print("Geometry "); printGeometryEnvelope(envelope); } Geometry geometry = geometryData.getGeometry(); GeometryEnvelope builtEnvelope = GeometryEnvelopeBuilder .buildEnvelope(geometry); if (builtEnvelope != null && (envelope == null || !envelope.equals(builtEnvelope))) { System.out.print("Calculated "); printGeometryEnvelope(builtEnvelope); } } /** * Print the geometry envelope * * @param envelope * geometry envelope */ private static void printGeometryEnvelope(GeometryEnvelope envelope) { System.out.println("Envelope"); System.out.println(" min x: " + envelope.getMinX()); System.out.println(" min y: " + envelope.getMinY()); System.out.println(" max x: " + envelope.getMaxX()); System.out.println(" max y: " + envelope.getMaxY()); if (envelope.hasZ()) { System.out.println(" min z: " + envelope.getMinZ()); System.out.println(" max z: " + envelope.getMaxZ()); } if (envelope.hasM()) { System.out.println(" min m: " + envelope.getMinM()); System.out.println(" max m: " + envelope.getMaxM()); } } /** * Get the projection from the projection authority:code or epsg_code * argument * * @param argument * projection argument * @return projection or null */ private static Projection getProjection(String argument) { Projection projection = null; String authority = null; String code = null; String[] projectionParts = argument.split(":"); switch (projectionParts.length) { case 1: authority = ProjectionConstants.AUTHORITY_EPSG; code = projectionParts[0]; break; case 2: authority = projectionParts[0]; code = projectionParts[1]; break; default: System.out.println("Error: Invalid projection argument '" + argument + "', expected 'authority:code' or 'epsg_code'"); } if (authority != null) { projection = ProjectionFactory.getProjection(authority, code); } return projection; } /** * Determine the bounds * * @param database * database * @param sqlBuilder * SQL builder * @param type * bounds type * @param args * bounds arguments */ private static void bounds(GeoPackage database, StringBuilder sqlBuilder, BoundsType type, String args) { boolean valid = true; String table = null; Projection projection = null; boolean manual = false; if (args != null && !args.isEmpty()) { String[] argParts = args.trim().split("\\s+"); for (int i = 0; valid && i < argParts.length; i++) { String arg = argParts[i]; if (arg.startsWith(ARGUMENT_PREFIX)) { String argument = arg.substring(ARGUMENT_PREFIX.length()); switch (argument) { case ARGUMENT_PROJECTION: if (i + 1 < argParts.length) { String projectionArugment = argParts[++i]; projection = getProjection(projectionArugment); if (projection == null) { valid = false; } } else { valid = false; System.out.println("Error: Projection argument '" + arg + "' must be followed by 'authority:code' or 'epsg_code'"); } break; case BOUNDS_ARGUMENT_MANUAL: if (type == BoundsType.CONTENTS) { valid = false; System.out.println( "Error: Unsupported arg: '" + arg + "'"); } else { manual = true; } break; default: valid = false; System.out.println( "Error: Unsupported arg: '" + arg + "'"); } } else { if (table == null) { table = arg; if (!database.isContentsTable(table)) { valid = false; System.out.println("Error: Not a contents table: '" + table + "'"); } } else { valid = false; System.out.println( "Error: Unsupported arg: '" + arg + "'"); } } } } if (valid) { BoundingBox bounds = null; if (table != null) { switch (type) { case CONTENTS: if (projection != null) { bounds = database.getContentsBoundingBox(projection, table); } else { bounds = database.getContentsBoundingBox(table); projection = database.getContentsProjection(table); } break; case ALL: if (projection != null) { bounds = database.getBoundingBox(projection, table, manual); } else { bounds = database.getBoundingBox(table, manual); projection = database.getProjection(table); } break; case TABLE: if (projection != null) { bounds = database.getTableBoundingBox(projection, table, manual); } else { bounds = database.getTableBoundingBox(table, manual); projection = database.getProjection(table); } break; default: throw new GeoPackageException("Unsupported type: " + type); } } else { if (projection == null) { projection = ProjectionFactory.getProjection( ProjectionConstants.EPSG_WORLD_GEODETIC_SYSTEM); } switch (type) { case CONTENTS: bounds = database.getContentsBoundingBox(projection); break; case ALL: bounds = database.getBoundingBox(projection, manual); break; case TABLE: bounds = database.getTableBoundingBox(projection, manual); break; default: throw new GeoPackageException("Unsupported type: " + type); } } printBounds(table, projection, bounds); } resetCommandPrompt(sqlBuilder); } /** * Print table bounds * * @param table * table name * @param projection * bounds projection * @param bounds * bounding box bounds */ private static void printBounds(String table, Projection projection, BoundingBox bounds) { SQLExecResult result = new SQLExecResult(); result.addTable(table); List<String> columns = new ArrayList<>(); columns.add("Projection"); columns.add("Min Longitude"); columns.add("Min Latitude"); columns.add("Max Longitude"); columns.add("Max Latitude"); result.addColumns(columns); int[] columnWidths = new int[columns.size()]; for (int i = 0; i < columnWidths.length; i++) { columnWidths[i] = columns.get(i).length(); } String proj = null; if (projection != null) { proj = projection.getAuthority() + ":" + projection.getCode(); } String minLon = null; String minLat = null; String maxLon = null; String maxLat = null; if (bounds != null) { DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); df.setMaximumFractionDigits(340); minLon = df.format(bounds.getMinLongitude()); minLat = df.format(bounds.getMinLatitude()); maxLon = df.format(bounds.getMaxLongitude()); maxLat = df.format(bounds.getMaxLatitude()); } List<String> row = new ArrayList<>(); row.add(proj); row.add(minLon); row.add(minLat); row.add(maxLon); row.add(maxLat); result.addRow(row); for (int i = 0; i < columnWidths.length; i++) { String value = row.get(i); if (value != null) { columnWidths[i] = Math.max(columnWidths[i], value.length()); } } result.addColumnWidths(columnWidths); result.printResults(); } /** * Print usage for the main method */ private static void printUsage() { System.out.println(); System.out.println("USAGE"); System.out.println(); System.out.println("\t[" + ARGUMENT_PREFIX + ARGUMENT_MAX_ROWS + " max_rows] [" + ARGUMENT_PREFIX + ARGUMENT_MAX_COLUMN_WIDTH + " max_column_width] [" + ARGUMENT_PREFIX + ARGUMENT_MAX_LINES_PER_ROW + " max_lines_per_row] sqlite_file [sql]"); System.out.println(); System.out.println("DESCRIPTION"); System.out.println(); System.out.println("\tExecutes SQL on a SQLite database"); System.out.println(); System.out.println( "\tProvide the SQL to execute a single statement. Omit to start an interactive session."); System.out.println(); System.out.println("ARGUMENTS"); System.out.println(); System.out.println( "\t" + ARGUMENT_PREFIX + ARGUMENT_MAX_ROWS + " max_rows"); System.out.println("\t\tMax rows per query" + " (Default is " + printableValue(DEFAULT_MAX_ROWS) + ")"); System.out.println(); System.out.println("\t" + ARGUMENT_PREFIX + ARGUMENT_MAX_COLUMN_WIDTH + " max_column_width"); System.out.println( "\t\tMax width (in characters) per column" + " (Default is " + printableValue(DEFAULT_MAX_COLUMN_WIDTH) + ")"); System.out.println(); System.out.println("\t" + ARGUMENT_PREFIX + ARGUMENT_MAX_LINES_PER_ROW + " max_lines_per_row"); System.out.println("\t\tMax lines per row" + " (Default is " + printableValue(DEFAULT_MAX_LINES_PER_ROW) + ")"); System.out.println(); System.out.println("\tsqlite_file"); System.out.println("\t\tpath to the SQLite database file"); System.out.println(); System.out.println("\tsql"); System.out.println("\t\tSQL statement to execute"); System.out.println(); } /** * Get a printable string for the integer value * * @param value * value * @return string */ private static String printableValue(Integer value) { return (value != null && value > 0) ? value.toString() : "0 = none"; } /** * Check if the SQLite database is a GeoPackage * * @param database * SQLite database * @return true if a GeoPackage */ public static boolean isGeoPackage(GeoPackage database) { return GeoPackageValidate.hasMinimumTables(database); } }
package com.idugalic; import static org.hamcrest.CoreMatchers.endsWith; import static org.junit.Assert.assertThat; import static org.springframework.http.MediaType.TEXT_EVENT_STREAM; import java.util.List; import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.FluxExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; import com.idugalic.domain.blog.BlogPost; import com.idugalic.domain.blog.BlogPostRepository; import com.idugalic.domain.project.Project; import com.idugalic.domain.project.ProjectRepository; import com.idugalic.web.blog.BlogPostController; import com.idugalic.web.project.ProjectController; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class ApplicationIntegrationTest { WebTestClient webTestClient; List<BlogPost> expectedBlogPosts; List<Project> expectedProjects; @Autowired BlogPostRepository blogPostRepository; @Autowired ProjectRepository projectRepository; @Before public void setup() { webTestClient = WebTestClient.bindToController(new BlogPostController(blogPostRepository), new ProjectController(projectRepository)).build(); expectedBlogPosts = blogPostRepository.findAll().collectList().block(); expectedProjects = projectRepository.findAll().collectList().block(); } @Test public void listAllBlogPostsIntegrationTest() { this.webTestClient.get().uri("/blogposts") .exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) .expectBodyList(BlogPost.class).isEqualTo(expectedBlogPosts); } @Test public void listAllProjectsIntegrationTest() { this.webTestClient.get().uri("/projects") .exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) .expectBodyList(Project.class).isEqualTo(expectedProjects); } @Test public void streamAllBlogPostsIntegrationTest() throws Exception { FluxExchangeResult<BlogPost> result = this.webTestClient.get() .uri("/blogposts") .accept(TEXT_EVENT_STREAM) .exchange() .expectStatus().isOk() .expectHeader().contentType(TEXT_EVENT_STREAM) .returnResult(BlogPost.class); StepVerifier.create(result.getResponseBody()) .expectNext(expectedBlogPosts.get(0), expectedBlogPosts.get(1)) .expectNextCount(1) .consumeNextWith(blogPost -> assertThat(blogPost.getAuthorId(), endsWith("4"))) .thenCancel() .verify(); } @Test public void streamAllProjectsIntegrationTest() throws Exception { FluxExchangeResult<Project> result = this.webTestClient.get() .uri("/projects") .accept(TEXT_EVENT_STREAM) .exchange() .expectStatus().isOk() .expectHeader().contentType(TEXT_EVENT_STREAM) .returnResult(Project.class); StepVerifier.create(result.getResponseBody()) .expectNext(expectedProjects.get(0), expectedProjects.get(1)) .expectNextCount(1) .consumeNextWith(project -> assertThat(project.getName(), endsWith("4"))) .thenCancel() .verify(); } @Test public void listBlogPostsByTitleIntegrationTest() { this.webTestClient.get().uri("/blogposts/search/bytitle?title=title1") .exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) .expectBodyList(BlogPost.class).isEqualTo(expectedBlogPosts.stream().filter(bp->bp.getTitle().equals("title1")).collect(Collectors.toList())); } @Test public void listProjectsByNameIntegrationTest() { this.webTestClient.get().uri("/projects/search/byname?name=name1") .exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) .expectBodyList(Project.class).isEqualTo(expectedProjects.stream().filter(bp->bp.getName().equals("name1")).collect(Collectors.toList())); } @Test public void getBlogPostIntegrationTest() throws Exception { this.webTestClient.get().uri("/blogposts/"+expectedBlogPosts.get(0).getId()) .exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) .expectBody(BlogPost.class).isEqualTo(expectedBlogPosts.get(0)); } @Test public void getProjectIntegrationTest() throws Exception { this.webTestClient.get().uri("/projects/"+expectedProjects.get(0).getId()) .exchange() .expectStatus().isOk() .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8) .expectBody(Project.class).isEqualTo(expectedProjects.get(0)); } @Test public void postBlogPostIntegrationTest() throws Exception { this.webTestClient.post().uri("/blogposts") .body(Mono.just(new BlogPost("authorId5", "title5", "content5", "tagString5")), BlogPost.class) .exchange() .expectStatus().isOk() .expectBody().isEmpty(); } @Test public void postProjectIntegrationTest() throws Exception { this.webTestClient.post().uri("/projects") .body(Mono.just(new Project("name5", "repoUrl5", "siteUrl5", "category5", "description5")), Project.class) .exchange() .expectStatus().isOk().expectBody().isEmpty(); } }
package net.barik; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.poi.hssf.usermodel.HSSFChart; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.poifs.eventfilesystem.POIFSReader; import org.apache.poi.poifs.eventfilesystem.POIFSReaderEvent; import org.apache.poi.poifs.eventfilesystem.POIFSReaderListener; import org.apache.poi.poifs.filesystem.POIFSDocumentPath; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class SpreadsheetAnalyzer { private Workbook workbook; private Map<SheetLocation, InputCellReferencePackage> inputCellByReferenceMap = new HashMap<>(); private Map<String, Set<InputCellReferencePackage>> inputCellMap = new HashMap<>(); //maps sheet name to inputCellPackage private Map<SheetLocation, CellReferencePackage> formulaCellByReferenceMap = new HashMap<>(); private Map<String, Set<CellReferencePackage>> formulaCellMap = new HashMap<>(); //maps sheet name to formulaCellPackage private Map<InputCellType, Integer> inputCellCounts = new EnumMap<>(InputCellType.class); private Map<String, Integer> functionCounts = new HashMap<>(); private Map<FunctionEvalType, Integer> evalTypeCounts = new EnumMap<>(FunctionEvalType.class); private boolean containsMacros = false; private final Pattern findFunctions = Pattern.compile("\\p{Upper}+\\(");
package io.georocket.commands; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.delete; import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import org.junit.Test; import org.junit.runner.RunWith; import com.github.tomakehurst.wiremock.client.VerificationException; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; /** * Test for {@link DeleteCommand} * @author Michel Kraemer */ @RunWith(VertxUnitRunner.class) public class DeleteCommandTest extends CommandTestBase<DeleteCommand> { @Override protected DeleteCommand createCommand() { return new DeleteCommand(); } /** * Test no layer * @param context the test context * @throws Exception if something goes wrong */ @Test public void noLayer(TestContext context) throws Exception { context.assertEquals(1, cmd.run(new String[] { }, in, out)); } /** * Test empty layer * @param context the test context * @throws Exception if something goes wrong */ @Test public void emptyLayer(TestContext context) throws Exception { context.assertEquals(1, cmd.run(new String[] { "" }, in, out)); } /** * Verify that a certain DELETE request has been made * @param url the request URL * @param context the current test context */ protected void verifyDeleted(String url, TestContext context) { try { verify(deleteRequestedFor(urlEqualTo(url))); } catch (VerificationException e) { context.fail(e); } } /** * Test a delete with a simple query * @param context the test context * @throws Exception if something goes wrong */ @Test public void simpleQueryDelete(TestContext context) throws Exception { String url = "/store/?search=test"; stubFor(delete(urlEqualTo(url)) .willReturn(aResponse() .withStatus(204))); Async async = context.async(); cmd.setEndHandler(exitCode -> { context.assertEquals(0, exitCode); verifyDeleted(url, context); async.complete(); }); cmd.run(new String[] { "test" }, in, out); } /** * Test a delete with query that consists of two terms * @param context the test context * @throws Exception if something goes wrong */ @Test public void twoTermsQueryDelete(TestContext context) throws Exception { String url = "/store/?search=test1+test2"; stubFor(delete(urlEqualTo(url)) .willReturn(aResponse() .withStatus(204))); Async async = context.async(); cmd.setEndHandler(exitCode -> { context.assertEquals(0, exitCode); verifyDeleted(url, context); async.complete(); }); cmd.run(new String[] { "test1", "test2" }, in, out); } /** * Test to delete the root layer * @param context the test context * @throws Exception if something goes wrong */ @Test public void rootLayer(TestContext context) throws Exception { String url = "/store/"; stubFor(delete(urlEqualTo(url)) .willReturn(aResponse() .withStatus(204))); Async async = context.async(); cmd.setEndHandler(exitCode -> { context.assertEquals(0, exitCode); verifyDeleted(url, context); async.complete(); }); cmd.run(new String[] { "-l", "/" }, in, out); } /** * Test a delete with a layer but no query * @param context the test context * @throws Exception if something goes wrong */ @Test public void layerNoQuery(TestContext context) throws Exception { String url = "/store/hello/world/"; stubFor(delete(urlEqualTo(url)) .willReturn(aResponse() .withStatus(204))); Async async = context.async(); cmd.setEndHandler(exitCode -> { context.assertEquals(0, exitCode); verifyDeleted(url, context); async.complete(); }); cmd.run(new String[] { "-l", "hello/world" }, in, out); } /** * Test a delete with a layer and a query * @param context the test context * @throws Exception if something goes wrong */ @Test public void layerQuery(TestContext context) throws Exception { String url = "/store/hello/world/?search=test"; stubFor(delete(urlEqualTo(url)) .willReturn(aResponse() .withStatus(204))); Async async = context.async(); cmd.setEndHandler(exitCode -> { context.assertEquals(0, exitCode); verifyDeleted(url, context); async.complete(); }); cmd.run(new String[] { "-l", "hello/world", "test" }, in, out); } }
package org.amc.game.chess; import org.amc.util.DefaultSubject; /** * Represents a Chess Board * Responsibility is to know the position of all the pieces * * @author Adrian Mclaughlin * */ public class ChessBoard extends DefaultSubject { public enum Coordinate implements Comparable<Coordinate>{ A(0), B(1), C(2), D(3), E(4), F(5), G(6), H(7); private int name; private Coordinate(int name){ this.name=name; } public int getName(){ return this.name; } } private final ChessPiece[][] board; public ChessBoard(){ board=new ChessPiece[8][8]; } /** * Sets up the board in it's initial state */ public void initialise(){ putPieceOnBoardAt(new BishopPiece(Colour.WHITE), new Location(Coordinate.C,1)); putPieceOnBoardAt(new BishopPiece(Colour.WHITE), new Location(Coordinate.F,1)); putPieceOnBoardAt(new KingPiece(Colour.WHITE), new Location(Coordinate.E, 1)); putPieceOnBoardAt(new BishopPiece(Colour.BLACK), new Location(Coordinate.C,8)); putPieceOnBoardAt(new BishopPiece(Colour.BLACK), new Location(Coordinate.F,8)); putPieceOnBoardAt(new KingPiece(Colour.BLACK), new Location(Coordinate.E, 8)); } public void move(Player player,Move move)throws InvalidMoveException{ ChessPiece piece=getPieceFromBoardAt(move.getStart()); if(piece==null){ throw new InvalidMoveException("No piece at "+move.getStart()); }else if (player.getColour()!=piece.getColour()){ throw new InvalidMoveException("Player can only move their own pieces"); }else{ if(piece.isValidMove(this, move)){ removePieceOnBoardAt(piece, move.getStart()); putPieceOnBoardAt(piece, move.getEnd()); this.notifyObservers(null); } else { throw new InvalidMoveException("Not a valid move"); } } } void removePieceOnBoardAt(ChessPiece piece,Location location){ this.board[location.getLetter().getName()][location.getNumber()-1]=null; } void putPieceOnBoardAt(ChessPiece piece,Location location){ this.board[location.getLetter().getName()][location.getNumber()-1]=piece; } ChessPiece getPieceFromBoardAt(int letterCoordinate,int numberCoordinate){ return board[letterCoordinate][numberCoordinate-1]; } ChessPiece getPieceFromBoardAt(Location location){ return getPieceFromBoardAt(location.getLetter().getName(), location.getNumber()); } }
package net.sf.jabref.bibtex; import net.sf.jabref.Globals; import net.sf.jabref.JabRefPreferences; import net.sf.jabref.exporter.LatexFieldFormatter; import net.sf.jabref.importer.ParserResult; import net.sf.jabref.importer.fileformat.BibtexParser; import net.sf.jabref.model.entry.BibEntry; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.Collection; import java.util.Set; import static org.junit.Assert.assertEquals; public class BibEntryWriterTest { private BibtexEntryWriter writer; private static JabRefPreferences backup; @BeforeClass public static void setUp() { Globals.prefs = JabRefPreferences.getInstance(); backup = Globals.prefs; // make sure that we use the "new style" serialization Globals.prefs.putInt(JabRefPreferences.WRITEFIELD_SORTSTYLE, 0); // make sure that we use camel casing Globals.prefs.putBoolean(JabRefPreferences.WRITEFIELD_CAMELCASENAME, true); } @AfterClass public static void tearDown() { Globals.prefs.overwritePreferences(backup); } @Before public void setUpWriter() { writer = new BibtexEntryWriter(new LatexFieldFormatter(), true); } @Test public void testSerialization() throws IOException { StringWriter stringWriter = new StringWriter(); BibEntry entry = new BibEntry("1234", EntryTypes.getType("Article")); //set a required field entry.setField("author", "Foo Bar"); entry.setField("journal", "International Journal of Something"); //set an optional field entry.setField("number", "1"); entry.setField("note", "some note"); writer.write(entry, stringWriter); String actual = stringWriter.toString(); String expected = Globals.NEWLINE + Globals.NEWLINE + "@Article{," + Globals.NEWLINE + " Author = {Foo Bar}," + Globals.NEWLINE + " Journal = {International Journal of Something}," + Globals.NEWLINE + " Note = {some note}," + Globals.NEWLINE + " Number = {1}" + Globals.NEWLINE + "}"; assertEquals(expected, actual); } @Test public void roundTripTest() throws IOException { String bibtexEntry = "@Article{test," + Globals.NEWLINE + " Author = {Foo Bar}," + Globals.NEWLINE + " Journal = {International Journal of Something}," + Globals.NEWLINE + " Note = {some note}," + Globals.NEWLINE + " Number = {1}" + Globals.NEWLINE + "}"; // read in bibtex string ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); Assert.assertEquals(1, entries.size()); BibEntry entry = entries.iterator().next(); Assert.assertEquals("test", entry.getCiteKey()); Assert.assertEquals(5, entry.getFieldNames().size()); Set<String> fields = entry.getFieldNames(); Assert.assertTrue(fields.contains("author")); Assert.assertEquals("Foo Bar", entry.getField("author")); //write out bibtex string StringWriter stringWriter = new StringWriter(); writer.write(entry, stringWriter); String actual = stringWriter.toString(); assertEquals(bibtexEntry, actual); } @Test public void roundTripWithPrependingNewlines() throws IOException { String bibtexEntry = "\r\n@Article{test," + Globals.NEWLINE + " Author = {Foo Bar}," + Globals.NEWLINE + " Journal = {International Journal of Something}," + Globals.NEWLINE + " Note = {some note}," + Globals.NEWLINE + " Number = {1}" + Globals.NEWLINE + "}"; // read in bibtex string ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); Assert.assertEquals(1, entries.size()); BibEntry entry = entries.iterator().next(); Assert.assertEquals("test", entry.getCiteKey()); Assert.assertEquals(5, entry.getFieldNames().size()); Set<String> fields = entry.getFieldNames(); Assert.assertTrue(fields.contains("author")); Assert.assertEquals("Foo Bar", entry.getField("author")); //write out bibtex string StringWriter stringWriter = new StringWriter(); writer.write(entry, stringWriter); String actual = stringWriter.toString(); assertEquals(bibtexEntry, actual); } @Test public void roundTripWithModification() throws IOException { String bibtexEntry = Globals.NEWLINE + "@Article{test," + Globals.NEWLINE + " Author = {Foo Bar}," + Globals.NEWLINE + " Journal = {International Journal of Something}," + Globals.NEWLINE + " Note = {some note}," + Globals.NEWLINE + " Number = {1}" + Globals.NEWLINE + "}"; // read in bibtex string ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); Assert.assertEquals(1, entries.size()); BibEntry entry = entries.iterator().next(); Assert.assertEquals("test", entry.getCiteKey()); Assert.assertEquals(5, entry.getFieldNames().size()); entry.setField("author", "BlaBla"); Set<String> fields = entry.getFieldNames(); Assert.assertTrue(fields.contains("author")); Assert.assertEquals("BlaBla", entry.getField("author")); //write out bibtex string StringWriter stringWriter = new StringWriter(); writer.write(entry, stringWriter); String actual = stringWriter.toString(); String expected = Globals.NEWLINE + Globals.NEWLINE + "@Article{test," + Globals.NEWLINE + " Author = {BlaBla}," + Globals.NEWLINE + " Journal = {International Journal of Something}," + Globals.NEWLINE + " Note = {some note}," + Globals.NEWLINE + " Number = {1}" + Globals.NEWLINE + "}"; assertEquals(expected, actual); } @Test public void roundTripWithCamelCasing() throws IOException { String bibtexEntry = Globals.NEWLINE + "@Article{test," + Globals.NEWLINE + " author = {Foo Bar}," + Globals.NEWLINE + " journal = {International Journal of Something}," + Globals.NEWLINE + " note = {some note}," + Globals.NEWLINE + " Number = {1}," + Globals.NEWLINE + " howpublished = {asdf}" + Globals.NEWLINE + "}"; // read in bibtex string ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); Assert.assertEquals(1, entries.size()); BibEntry entry = entries.iterator().next(); Assert.assertEquals("test", entry.getCiteKey()); Assert.assertEquals(6, entry.getFieldNames().size()); entry.setField("author", "BlaBla"); Set<String> fields = entry.getFieldNames(); Assert.assertTrue(fields.contains("author")); Assert.assertEquals("BlaBla", entry.getField("author")); //write out bibtex string StringWriter stringWriter = new StringWriter(); writer.write(entry, stringWriter); String actual = stringWriter.toString(); String expected = Globals.NEWLINE + Globals.NEWLINE + "@Article{test," + Globals.NEWLINE + " Author = {BlaBla}," + Globals.NEWLINE + " Journal = {International Journal of Something}," + Globals.NEWLINE + " Note = {some note}," + Globals.NEWLINE + " Number = {1}," + Globals.NEWLINE + " HowPublished = {asdf}" + Globals.NEWLINE + "}"; assertEquals(expected, actual); } @Test public void roundTripWithAppendedNewlines() throws IOException { String bibtexEntry = "@Article{test," + Globals.NEWLINE + " Author = {Foo Bar}," + Globals.NEWLINE + " Journal = {International Journal of Something}," + Globals.NEWLINE + " Note = {some note}," + Globals.NEWLINE + " Number = {1}" + Globals.NEWLINE + "}\n\n"; // read in bibtex string ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); Assert.assertEquals(1, entries.size()); BibEntry entry = entries.iterator().next(); Assert.assertEquals("test", entry.getCiteKey()); Assert.assertEquals(5, entry.getFieldNames().size()); Set<String> fields = entry.getFieldNames(); Assert.assertTrue(fields.contains("author")); Assert.assertEquals("Foo Bar", entry.getField("author")); //write out bibtex string StringWriter stringWriter = new StringWriter(); writer.write(entry, stringWriter); String actual = stringWriter.toString(); //appending newlines are not written by the writer, but by FileActions. So, these should be removed here. assertEquals(bibtexEntry.substring(0, bibtexEntry.length() - 2), actual); } @Test public void multipleWritesWithoutModification() throws IOException { String bibtexEntry = "@Article{test," + Globals.NEWLINE + " Author = {Foo Bar}," + Globals.NEWLINE + " Journal = {International Journal of Something}," + Globals.NEWLINE + " Note = {some note}," + Globals.NEWLINE + " Number = {1}" + Globals.NEWLINE + "}"; String result = testSingleWrite(bibtexEntry); result = testSingleWrite(result); result = testSingleWrite(result); assertEquals(bibtexEntry, result); } private String testSingleWrite(String bibtexEntry) throws IOException { // read in bibtex string ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); Assert.assertEquals(1, entries.size()); BibEntry entry = entries.iterator().next(); Assert.assertEquals("test", entry.getCiteKey()); Assert.assertEquals(5, entry.getFieldNames().size()); Set<String> fields = entry.getFieldNames(); Assert.assertTrue(fields.contains("author")); Assert.assertEquals("Foo Bar", entry.getField("author")); //write out bibtex string StringWriter stringWriter = new StringWriter(); writer.write(entry, stringWriter); String actual = stringWriter.toString(); assertEquals(bibtexEntry, actual); return actual; } @Test public void monthFieldSpecialSyntax() throws IOException { String bibtexEntry = "@Article{test," + Globals.NEWLINE + " Author = {Foo Bar}," + Globals.NEWLINE + " Month = mar," + Globals.NEWLINE + " Number = {1}" + Globals.NEWLINE + "}"; // read in bibtex string ParserResult result = BibtexParser.parse(new StringReader(bibtexEntry)); Collection<BibEntry> entries = result.getDatabase().getEntries(); Assert.assertEquals(1, entries.size()); BibEntry entry = entries.iterator().next(); Assert.assertEquals("test", entry.getCiteKey()); Assert.assertEquals(4, entry.getFieldNames().size()); Set<String> fields = entry.getFieldNames(); Assert.assertTrue(fields.contains("month")); Assert.assertEquals("#mar#", entry.getField("month")); //write out bibtex string StringWriter stringWriter = new StringWriter(); writer.write(entry, stringWriter); String actual = stringWriter.toString(); assertEquals(bibtexEntry, actual); } }
package org.arkanos.aos.api.data; import java.io.IOException; import java.io.Reader; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DecimalFormat; import java.util.Vector; import org.arkanos.aos.api.controllers.Database; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** * Goal data access and operation. * * @version 1.0 * @author Matheus Borges Teixeira */ public class Goal { /** SQL table name **/ static public final String TABLE_NAME = "goal"; /** SQL/JSON field for the goal ID **/ static public final String FIELD_ID = "id"; /** SQL/JSON field for the goal title **/ static public final String FIELD_TITLE = "title"; /** SQL/JSON field for the time planned **/ static public final String FIELD_TIME_PLANNED = "time_planned"; /** SQL/JSON field for the description **/ static public final String FIELD_DESCRIPTION = "description"; /** SQL/JSON field for the username **/ static public final String FIELD_USER_NAME = "user_name"; /** SQL/JSON field for the calculated completion **/ static public final String EXTRA_COMPLETION = "completion"; /** SQL/JSON field for the calculated dedication **/ static public final String EXTRA_DEDICATION = "dedication"; /** SQL/JSON field for the calculated time spent **/ static public final String EXTRA_TOTAL_TIME_SPENT = "total_time_spent"; /** * Creates a new Goal in the database. * * @param title * @param time_planned * @param description * @param user_name * @return id of the created goal or -1 if creation failed. */ static public int createGoal(String title, int time_planned, String description, String user_name) { boolean insertion = Database.execute("INSERT INTO " + Goal.TABLE_NAME + " (" + Goal.FIELD_TITLE + "," + Goal.FIELD_TIME_PLANNED + "," + Goal.FIELD_DESCRIPTION + "," + Goal.FIELD_USER_NAME + ") " + "VALUES (\"" + title + "\"," + time_planned + ",\"" + description + "\",\"" + user_name + "\");"); if (insertion == true) { try { ResultSet rs = Database.query("SELECT MAX(" + Goal.FIELD_ID + ") AS created_id" + " FROM " + Goal.TABLE_NAME + " WHERE " + Goal.FIELD_TITLE + " = \"" + title + "\" AND " + Goal.FIELD_TIME_PLANNED + " = " + time_planned + " AND " + Goal.FIELD_DESCRIPTION + " = \"" + description + "\" AND " + Goal.FIELD_USER_NAME + " = \"" + user_name + "\";"); if ((rs != null) && rs.next()) return rs.getInt("created_id"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return -1; } /** * Fetches a given goal from the database and calculates extra information. * * @param user_name * defines the owner of the goal. * @param id * specifies the goal to be fetched. * @return the goal instance or null if none was found. */ public static Goal getGoal(String user_name, int id) { try { ResultSet rs = Database.query("SELECT * FROM " + Goal.TABLE_NAME + " WHERE " + Goal.FIELD_USER_NAME + " = \"" + user_name + "\"" + " AND " + Goal.FIELD_ID + " = " + id + ";"); if ((rs != null) && rs.next()) { Goal newone = new Goal(rs.getInt(Goal.FIELD_ID), rs.getString(Goal.FIELD_TITLE), rs.getInt(Goal.FIELD_TIME_PLANNED), rs.getString(Goal.FIELD_DESCRIPTION), user_name); return newone; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * Fetches all goals from a user. * * @param user_name * defines the user. * @return all goals or null, in case there are connection problems. */ static public Vector<Goal> getUserGoals(String user_name) { try { ResultSet rs = Database.query("SELECT * FROM " + Goal.TABLE_NAME + " WHERE " + Goal.FIELD_USER_NAME + " = \"" + user_name + "\";"); Vector<Goal> results = new Vector<Goal>(); while ((rs != null) && rs.next()) { Goal newone = new Goal(rs.getInt(Goal.FIELD_ID), rs.getString(Goal.FIELD_TITLE), rs.getInt(Goal.FIELD_TIME_PLANNED), rs.getString(Goal.FIELD_DESCRIPTION), user_name); //TODO optimize? ResultSet newrs = Database.query("SELECT AVG(help.progress) AS completion, SUM(help.spent) AS total_time_spent FROM (" + "SELECT IF(SUM((w." + Work.FIELD_RESULT + ")/(t." + Task.FIELD_TARGET + "-t." + Task.FIELD_INITIAL + ")) IS NULL, 0, SUM((w." + Work.FIELD_RESULT + ")/(t." + Task.FIELD_TARGET + "-t." + Task.FIELD_INITIAL + "))) AS progress, " + "SUM(" + Work.FIELD_TIME_SPENT + ") AS spent FROM goal g " + "LEFT JOIN " + Task.TABLE_NAME + " t on t." + Task.FIELD_GOAL_ID + " = g." + Goal.FIELD_ID + " " + "LEFT JOIN " + Work.TABLE_NAME + " w ON t." + Task.FIELD_ID + " = w." + Work.FIELD_TASK_ID + " " + "WHERE g." + Goal.FIELD_ID + " = " + newone.getID() + " " + "AND g." + Goal.FIELD_USER_NAME + " = \"" + user_name + "\"" + "GROUP BY t." + Task.FIELD_ID + ",g." + Goal.FIELD_ID + ") help;"); if ((newrs != null) && newrs.next()) { newone.setCompletion(newrs.getFloat("completion")); newone.setTotalTimeSpent(newrs.getInt("total_time_spent")); } results.add(newone); } return results; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * Fetches all goals but calculates extra data based on a time range. * Both dates provided should be in format YYYY-MM-DD HH:mm:ss.0 * * @param user_name * defines the user. * @param from * specifies the starting of the period. * @param to * specifies the end of the period. * @return */ static public Vector<Goal> getUserGoalsSnapshot(String user_name, String from, String to) { try { ResultSet rs = Database.query("SELECT * FROM " + Goal.TABLE_NAME + " WHERE " + Goal.FIELD_USER_NAME + " = \"" + user_name + "\";"); Vector<Goal> results = new Vector<Goal>(); while ((rs != null) && rs.next()) { Goal newone = new Goal(rs.getInt(Goal.FIELD_ID), rs.getString(Goal.FIELD_TITLE), rs.getInt(Goal.FIELD_TIME_PLANNED), rs.getString(Goal.FIELD_DESCRIPTION), user_name); //TODO might be possible to optimize. ResultSet newrs = Database.query("SELECT AVG(help.progress) AS completion, SUM(help.spent) AS total_time_spent FROM (" + "SELECT IF(SUM((w." + Work.FIELD_RESULT + ")/(t." + Task.FIELD_TARGET + "-t." + Task.FIELD_INITIAL + ")) IS NULL, 0, SUM((w." + Work.FIELD_RESULT + ")/(t." + Task.FIELD_TARGET + "-t." + Task.FIELD_INITIAL + "))) AS progress, " + "SUM(" + Work.FIELD_TIME_SPENT + ") AS spent FROM goal g " + "LEFT JOIN " + Task.TABLE_NAME + " t on t." + Task.FIELD_GOAL_ID + " = g." + Goal.FIELD_ID + " " + "LEFT JOIN (SELECT * FROM " + Work.TABLE_NAME + " WHERE " + Work.FIELD_START + " >= \"" + from + "\" " + "AND " + Work.FIELD_START + " <= \"" + to + "\") " + " w ON t." + Task.FIELD_ID + " = w." + Work.FIELD_TASK_ID + " " + "WHERE g." + Goal.FIELD_ID + " = " + newone.getID() + " " + "AND g." + Goal.FIELD_USER_NAME + " = \"" + user_name + "\" " + "GROUP BY t." + Task.FIELD_ID + ",g." + Goal.FIELD_ID + ") help;"); if ((newrs != null) && newrs.next()) { newone.setCompletion(newrs.getFloat("completion")); newone.setTotalTimeSpent(newrs.getInt("total_time_spent")); } results.add(newone); } return results; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * Checks if a goal belongs to a user. * * @param user_name * defines the user. * @param goal_id * specifies the goal to be checked. * @return whether the goal belongs to the user. */ static public boolean isUserGoal(String user_name, int goal_id) { try { ResultSet rs = Database.query("SELECT COUNT(*) AS goal_count FROM " + Goal.TABLE_NAME + " WHERE " + Goal.FIELD_ID + " = " + goal_id + " AND " + Goal.FIELD_USER_NAME + " = \"" + user_name + "\";"); if ((rs != null) && rs.next()) return (rs.getInt("goal_count") > 0); else return false; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } /** * Creates a goal object based on a JSON file. * * @param from * defines the source of the JSON. * @param user_name * defines the user to own the goal. * @return the created goal instance. */ static public Goal parseGoal(Reader from, String user_name) { JSONParser jp = new JSONParser(); try { //TODO rewrite to a better JSON library. JSONObject jo = (JSONObject) jp.parse(from); String id = "" + jo.get(Goal.FIELD_ID); String title = "" + jo.get(Goal.FIELD_TITLE); String time_planned = "" + jo.get(Goal.FIELD_TIME_PLANNED); String description = "" + jo.get(Goal.FIELD_DESCRIPTION); Goal newone = new Goal(Integer.parseInt(id), title, (int) (Float.parseFloat(time_planned) * 60), description, user_name); newone.setCompletion(Float.parseFloat("" + jo.get(Task.EXTRA_COMPLETION))); newone.setTotalTimeSpent((int) (Float.parseFloat("" + jo.get(Goal.EXTRA_TOTAL_TIME_SPENT)) * 60)); return newone; } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** ID of the Goal instance **/ private final int id; /** Planned time of the Goal instance **/ private int time_planned; /** Title of the Goal instance **/ private String title; /** Description of the Goal instance **/ private String description; /** Owner of the Goal instance **/ private final String user_name; /* Volatile data */ /** Calculated completion of the Goal instance **/ private float completion = 0; /** Calculated total time spent of the Goal instance **/ private int total_time_spent = 0; /** * Constructor of the Goal instance. * * @param id * @param title * @param time_planned * @param description * @param user_name */ public Goal(int id, String title, int time_planned, String description, String user_name) { this.id = id; this.user_name = user_name; this.time_planned = time_planned; if (title != null) { this.title = title; } else { this.title = ""; } if (description != null) { this.description = description; } else { this.description = ""; } } /** * Removes the instance from the database. * * @return whether the instance could be removed. */ public boolean delete() { return Database.execute("DELETE FROM " + Goal.TABLE_NAME + " WHERE " + Goal.FIELD_ID + " = " + this.id + " AND " + Goal.FIELD_USER_NAME + " = \"" + this.user_name + "\";"); } public float getCompletion() { return this.completion; } public float getDedication() { if (this.time_planned > 0) return this.total_time_spent / (float) this.time_planned; else return 1; } public int getID() { return this.id; } public float getProductivity() { if (this.getDedication() > 0) return this.getCompletion() / this.getDedication(); else return 0; } public int getTimePlanned() { return this.time_planned; } public String getTitle() { return this.title; } public int getTotalTimeSpent() { return this.total_time_spent; } /** * Replaces content of the instance. * * @param to * defines the original instance. */ public void replaceContent(Goal to) { /* NEVER * this.id = to.id; * this.user_name = to.user_name; */ this.title = Database.sanitizeString(to.title); this.description = Database.sanitizeString(to.description); this.time_planned = to.time_planned; this.completion = to.completion; this.total_time_spent = to.total_time_spent; } private void setCompletion(float c) { this.completion = c; } private void setTotalTimeSpent(int tts) { this.total_time_spent = tts; } @Override public String toString() { DecimalFormat df = new DecimalFormat(); df.setMaximumFractionDigits(1); df.setGroupingUsed(false); String result = "{\""; result += Goal.FIELD_ID + "\":" + this.id + ",\""; result += Goal.FIELD_TITLE + "\":\"" + this.title + "\",\""; result += Goal.FIELD_TIME_PLANNED + "\":" + df.format(this.time_planned / 60.0f) + ",\""; if (this.time_planned > 0) { float dedication = (this.total_time_spent * 100.0f) / this.time_planned; result += Goal.EXTRA_DEDICATION + "\":" + df.format(dedication) + ",\""; } result += Goal.EXTRA_TOTAL_TIME_SPENT + "\":" + df.format(this.total_time_spent / 60.0f) + ",\""; result += Goal.EXTRA_COMPLETION + "\":" + df.format(this.completion * 100.0f) + ",\""; result += Goal.FIELD_DESCRIPTION + "\":\"" + this.description + "\"}"; return result; } /** * Updates the instance in the database. * * @return whether the instance could be updated */ public boolean update() { return Database.execute("UPDATE " + Goal.TABLE_NAME + " SET " + Goal.FIELD_TITLE + " = \"" + this.title + "\"," + Goal.FIELD_TIME_PLANNED + " = " + this.time_planned + "," + Goal.FIELD_DESCRIPTION + " = \"" + this.description + "\"" + " WHERE " + Goal.FIELD_ID + " = " + this.id + " AND " + Goal.FIELD_USER_NAME + " = \"" + this.user_name + "\";"); } }
package org.cpic.haplotype; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import com.google.common.collect.ListMultimap; import org.cpic.TestUtil; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class DefinitionReaderTest { @Test public void testReader() throws Exception { System.out.println("DefinitionReaderTest"); DefinitionReader dr = new DefinitionReader(); //ClassLoader classLoader = getClass().getClassLoader(); File file = new File(DefinitionReader.class.getResource("SLCO1B1.tsv").getFile()); Path path = Paths.get(file.getAbsolutePath()); dr.read(path); ListMultimap<String, Variant> m_haplotypePositions=dr.getHaplotypePositions(); ListMultimap<String, Haplotype> m_haplotypes=dr.getHaplotypes(); System.out.println(m_haplotypes); System.out.println(m_haplotypePositions); List<Variant> v_list = m_haplotypePositions.get("SLCO1B1"); List<Haplotype> h_list = m_haplotypes.get("SLCO1B1"); System.out.println(v_list.size()); System.out.println(h_list.size()); assertEquals(29,v_list.size()); assertEquals(37,h_list.size()); } @Test public void testReadAllDefinitions() throws Exception { Path file = TestUtil.getFile("org/cpic/haplotype/CYP2C19.tsv"); DefinitionReader reader = new DefinitionReader(); reader.read(file.getParent()); for (String gene : reader.getHaplotypePositions().keySet()) { for (Variant variant : reader.getHaplotypePositions().get(gene)) { assertTrue(variant.getCHROM().startsWith("chr")); if (variant.getPOS()<1){ System.out.println(gene); } assertTrue(variant.getPOS() > 0); } } } @Test public void testReadCyp2c19() throws Exception { Path file = TestUtil.getFile("org/cpic/haplotype/CYP2C19.tsv"); DefinitionReader reader = new DefinitionReader(); reader.read(file); for (String gene : reader.getHaplotypePositions().keySet()) { for (Variant variant : reader.getHaplotypePositions().get(gene)) { assertTrue(variant.getCHROM().startsWith("chr")); assertTrue(variant.getPOS() > 0); } } } }
package org.b3log.symphony.util; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.symphony.model.Link; import org.json.JSONObject; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import javax.servlet.http.HttpServletResponse; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class Links { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(Links.class); public static List<JSONObject> getLinks(final String baseURL, final String html) { final Document doc = Jsoup.parse(html, baseURL); final Elements urlElements = doc.select("a"); final Set<String> urls = new HashSet<>(); final List<Spider> spiders = new ArrayList<>(); String url = null; for (final Element urlEle : urlElements) { try { url = urlEle.absUrl("href"); if (StringUtils.isBlank(url) || !StringUtils.contains(url, ": url = StringUtils.substringBeforeLast(baseURL, "/") + url; } final URL formedURL = new URL(url); final String protocol = formedURL.getProtocol(); final String host = formedURL.getHost(); final int port = formedURL.getPort(); final String path = formedURL.getPath(); url = protocol + "://" + host; if (-1 != port && 80 != port && 443 != port) { url += ":" + port; } url += path; if (StringUtils.endsWith(url, "/")) { url = StringUtils.substringBeforeLast(url, "/"); } urls.add(url); } catch (final Exception e) { LOGGER.warn("Can't parse [" + url + "]"); } } final List<JSONObject> ret = new ArrayList<>(); try { for (final String u : urls) { spiders.add(new Spider(u)); } final List<Future<JSONObject>> results = Symphonys.EXECUTOR_SERVICE.invokeAll(spiders); for (final Future<JSONObject> result : results) { final JSONObject link = result.get(); if (null == link) { continue; } ret.add(link); } } catch (final Exception e) { LOGGER.log(Level.ERROR, "Parses URLs failed", e); } Collections.sort(ret, Comparator.comparingInt(link -> link.optInt(Link.LINK_BAIDU_REF_CNT))); return ret; } private static boolean containsChinese(final String str) { if (StringUtils.isBlank(str)) { return false; } final Pattern p = Pattern.compile("[\u4e00-\u9fa5]"); final Matcher m = p.matcher(str); return m.find(); } static class Spider implements Callable<JSONObject> { private final String url; Spider(final String url) { this.url = url; } @Override public JSONObject call() throws Exception { final int TIMEOUT = 2000; try { final JSONObject ret = new JSONObject(); // Get meta info of the URL final Connection.Response res = Jsoup.connect(url).timeout(TIMEOUT).followRedirects(false).execute(); if (HttpServletResponse.SC_OK != res.statusCode()) { return null; } String charset = res.charset(); if (StringUtils.isBlank(charset)) { charset = "UTF-8"; } final String html = new String(res.bodyAsBytes(), charset); String title = StringUtils.substringBetween(html, "<title>", "</title>"); title = StringUtils.trim(title); if (!containsChinese(title)) { return null; } final String keywords = StringUtils.substringBetween(html, "eywords\" content=\"", "\""); ret.put(Link.LINK_ADDR, url); ret.put(Link.LINK_TITLE, title); ret.put(Link.LINK_T_KEYWORDS, keywords); ret.put(Link.LINK_T_HTML, html); final Document doc = Jsoup.parse(html); doc.select("pre").remove(); ret.put(Link.LINK_T_TEXT, doc.text()); // Evaluate the URL URL baiduURL = new URL("https: HttpURLConnection conn = (HttpURLConnection) baiduURL.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.addRequestProperty("User-Agent", Symphonys.USER_AGENT_BOT); InputStream inputStream = conn.getInputStream(); String baiduRes = IOUtils.toString(inputStream, "UTF-8"); IOUtils.closeQuietly(inputStream); conn.disconnect(); int baiduRefCnt = StringUtils.countMatches(baiduRes, "<em>" + url + "</em>"); if (1 > baiduRefCnt) { ret.put(Link.LINK_BAIDU_REF_CNT, baiduRefCnt); LOGGER.debug(ret.optString(Link.LINK_ADDR)); return ret; } else { baiduURL = new URL("https: conn = (HttpURLConnection) baiduURL.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.addRequestProperty("User-Agent", Symphonys.USER_AGENT_BOT); inputStream = conn.getInputStream(); baiduRes = IOUtils.toString(inputStream, "UTF-8"); IOUtils.closeQuietly(inputStream); conn.disconnect(); baiduRefCnt += StringUtils.countMatches(baiduRes, "<em>" + url + "</em>"); ret.put(Link.LINK_BAIDU_REF_CNT, baiduRefCnt); LOGGER.debug(ret.optString(Link.LINK_ADDR)); return ret; } } catch (final SocketTimeoutException e) { return null; } catch (final Exception e) { LOGGER.log(Level.WARN, "Parses URL [" + url + "] failed", e); return null; } } } }
package org.basex.query.func; import static javax.xml.datatype.DatatypeConstants.*; import static org.basex.query.QueryText.*; import static org.basex.query.util.Err.*; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Map; import javax.xml.datatype.Duration; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import org.basex.io.serial.Serializer; import org.basex.query.QueryContext; import org.basex.query.QueryException; import org.basex.query.expr.Arr; import org.basex.query.expr.Expr; import org.basex.query.item.AtomType; import org.basex.query.item.Bln; import org.basex.query.item.Dbl; import org.basex.query.item.Empty; import org.basex.query.item.Flt; import org.basex.query.item.FuncType; import org.basex.query.item.Int; import org.basex.query.item.Jav; import org.basex.query.item.NodeType; import org.basex.query.item.Type; import org.basex.query.item.Value; import org.basex.query.iter.ItemCache; import org.basex.util.InputInfo; import org.basex.util.Token; import org.w3c.dom.Attr; import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; public final class JavaFunc extends Arr { /** New keyword. */ private static final String NEW = "new"; /** Input Java types. */ private static final Class<?>[] JAVA = { String.class, boolean.class, Boolean.class, byte.class, Byte.class, short.class, Short.class, int.class, Integer.class, long.class, Long.class, float.class, Float.class, double.class, Double.class, BigDecimal.class, BigInteger.class, QName.class, CharSequence.class, byte[].class, Object[].class, Map.class }; /** Resulting XQuery types. */ private static final Type[] XQUERY = { AtomType.STR, AtomType.BLN, AtomType.BLN, AtomType.BYT, AtomType.BYT, AtomType.SHR, AtomType.SHR, AtomType.INT, AtomType.INT, AtomType.LNG, AtomType.LNG, AtomType.FLT, AtomType.FLT, AtomType.DBL, AtomType.DBL, AtomType.DEC, AtomType.ITR, AtomType.QNM, AtomType.STR, AtomType.HEX, AtomType.SEQ, FuncType.ANY_FUN }; /** Java class. */ private final Class<?> cls; /** Java method. */ private final String mth; /** * Constructor. * @param ii input info * @param c Java class * @param m Java method/field * @param a arguments */ public JavaFunc(final InputInfo ii, final Class<?> c, final String m, final Expr[] a) { super(ii, a); cls = c; mth = m; } @Override public Value value(final QueryContext ctx) throws QueryException { final Value[] arg = new Value[expr.length]; for(int a = 0; a < expr.length; ++a) { arg[a] = expr[a].value(ctx); if(arg[a].isEmpty()) XPEMPTY.thrw(input, description()); } Object res = null; try { res = mth.equals(NEW) ? constructor(arg) : method(arg); } catch(final InvocationTargetException ex) { JAVAERR.thrw(input, ex.getCause()); } catch(final Exception ex) { FUNJAVA.thrw(input, description(), arg); } if(res == null) return Empty.SEQ; if(res instanceof Value) return (Value) res; if(!res.getClass().isArray()) return new Jav(res); final ItemCache ic = new ItemCache(); if(res instanceof boolean[]) { for(final boolean o : (boolean[]) res) ic.add(Bln.get(o)); } else if(res instanceof char[]) { for(final char o : (char[]) res) ic.add(Int.get(o)); } else if(res instanceof byte[]) { for(final byte o : (byte[]) res) ic.add(Int.get(o)); } else if(res instanceof short[]) { for(final short o : (short[]) res) ic.add(Int.get(o)); } else if(res instanceof int[]) { for(final int o : (int[]) res) ic.add(Int.get(o)); } else if(res instanceof long[]) { for(final long o : (long[]) res) ic.add(Int.get(o)); } else if(res instanceof float[]) { for(final float o : (float[]) res) ic.add(Flt.get(o)); } else if(res instanceof double[]) { for(final double o : (double[]) res) ic.add(Dbl.get(o)); } else { for(final Object o : (Object[]) res) { ic.add(o instanceof Value ? (Value) o : new Jav(o)); } } return ic.value(); } /** * Calls a constructor. * @param ar arguments * @return resulting object * @throws Exception exception */ private Object constructor(final Value[] ar) throws Exception { for(final Constructor<?> con : cls.getConstructors()) { final Object[] arg = args(con.getParameterTypes(), ar, true); if(arg != null) return con.newInstance(arg); } throw new Exception(); } /** * Calls a constructor. * @param ar arguments * @return resulting object * @throws Exception exception */ private Object method(final Value[] ar) throws Exception { // check if a field with the specified name exists try { final Field f = cls.getField(mth); final boolean st = Modifier.isStatic(f.getModifiers()); if(ar.length == (st ? 0 : 1)) { return f.get(st ? null : instObj(ar[0])); } } catch(final NoSuchFieldException ex) { /* ignored */ } for(final Method meth : cls.getMethods()) { if(!meth.getName().equals(mth)) continue; final boolean st = Modifier.isStatic(meth.getModifiers()); final Object[] arg = args(meth.getParameterTypes(), ar, st); if(arg != null) return meth.invoke(st ? null : instObj(ar[0]), arg); } throw new Exception(); } /** * Creates the instance on which a non-static field getter or method is * invoked. * @param v XQuery value * @return Java object * @throws QueryException query exception */ private Object instObj(final Value v) throws QueryException { return cls.isInstance(v) ? v : v instanceof Jav ? ((Jav) v).val : v.toJava(); } /** * Checks if the arguments conform with the specified parameters. * @param params parameters * @param args arguments * @param stat static flag * @return argument array or {@code null} * @throws QueryException query exception */ private Object[] args(final Class<?>[] params, final Value[] args, final boolean stat) throws QueryException { final int s = stat ? 0 : 1; final int l = args.length - s; if(l != params.length) return null; /** Function arguments. */ final Object[] val = new Object[l]; int a = 0; for(final Class<?> par : params) { final Value arg = args[s + a]; final Object next; if(par.isInstance(arg)) { next = arg; } else { final Type jtype = type(par); if(jtype == null || !arg.type.instanceOf(jtype) && !jtype.instanceOf(arg.type)) return null; next = arg.toJava(); } val[a++] = next; } return val; } /** * Returns an appropriate XQuery data type for the specified Java class. * @param type Java type * @return xquery type */ private static Type type(final Class<?> type) { for(int j = 0; j < JAVA.length; ++j) { if(JAVA[j].isAssignableFrom(type)) return XQUERY[j]; } return AtomType.JAVA; } /** * Returns an appropriate XQuery data type for the specified Java object. * @param o object * @return xquery type */ public static Type type(final Object o) { final Type t = type(o.getClass()); if(t != AtomType.JAVA) return t; if(o instanceof Element) return NodeType.ELM; if(o instanceof Document) return NodeType.DOC; if(o instanceof DocumentFragment) return NodeType.DOC; if(o instanceof Attr) return NodeType.ATT; if(o instanceof Comment) return NodeType.COM; if(o instanceof ProcessingInstruction) return NodeType.PI; if(o instanceof Text) return NodeType.TXT; if(o instanceof Duration) { final Duration d = (Duration) o; return !d.isSet(YEARS) && !d.isSet(MONTHS) ? AtomType.DTD : !d.isSet(HOURS) && !d.isSet(MINUTES) && !d.isSet(SECONDS) ? AtomType.YMD : AtomType.DUR; } if(o instanceof XMLGregorianCalendar) { final QName type = ((XMLGregorianCalendar) o).getXMLSchemaType(); if(type == DATE) return AtomType.DAT; if(type == DATETIME) return AtomType.DTM; if(type == TIME) return AtomType.TIM; if(type == GYEARMONTH) return AtomType.YMO; if(type == GMONTHDAY) return AtomType.MDA; if(type == GYEAR) return AtomType.YEA; if(type == GMONTH) return AtomType.MON; if(type == GDAY) return AtomType.DAY; } return AtomType.JAVA; } @Override public void plan(final Serializer ser) throws IOException { ser.openElement(this, NAM, Token.token(cls + "." + mth)); for(final Expr arg : expr) arg.plan(ser); ser.closeElement(); } @Override public String description() { return cls.getName() + "." + mth + "(...)" + (mth.equals(NEW) ? " constructor" : " method"); } @Override public String toString() { return cls + "." + mth + PAR1 + toString(SEP) + PAR2; } }
package org.owasp.esapi.crypto; import static org.junit.Assert.*; import java.util.Random; import org.junit.Test; import javax.crypto.SecretKey; import junit.framework.JUnit4TestAdapter; import org.owasp.esapi.crypto.CryptoHelper; import org.owasp.esapi.errors.EncryptionException; public class CryptoHelperTest { @Test public final void testGenerateSecretKeySunnyDay() { try { SecretKey key = CryptoHelper.generateSecretKey("AES", 128); assertTrue(key.getAlgorithm().equals("AES")); assertTrue(128 / 8 == key.getEncoded().length); } catch (EncryptionException e) { // OK if not covered in code coverage -- not expected. fail("Caught unexpected EncryptionException; msg was " + e.getMessage()); } } @Test(expected = EncryptionException.class) public final void testGenerateSecretKeyEncryptionException() throws EncryptionException { SecretKey key = CryptoHelper.generateSecretKey("NoSuchAlg", 128); assertTrue(key == null); // Not reached! } @Test public final void testOverwriteByteArrayByte() { byte[] secret = "secret password".getBytes(); int len = secret.length; CryptoHelper.overwrite(secret, (byte) 'x'); assertTrue(secret.length == len); // Length unchanged assertTrue(checkByteArray(secret, (byte) 'x')); // Filled with 'x' } @Test public final void testCopyByteArraySunnyDay() { byte[] src = new byte[20]; fillByteArray(src, (byte) 'A'); byte[] dest = new byte[20]; fillByteArray(dest, (byte) 'B'); CryptoHelper.copyByteArray(src, dest); assertTrue(checkByteArray(src, (byte) 'A')); // Still filled with 'A' assertTrue(checkByteArray(dest, (byte) 'A')); // Now filled with 'B' } @Test(expected = NullPointerException.class) public final void testCopyByteArraySrcNullPointerException() { byte[] ba = new byte[16]; CryptoHelper.copyByteArray(null, ba, ba.length); } @Test(expected = NullPointerException.class) public final void testCopyByteArrayDestNullPointerException() { byte[] ba = new byte[16]; CryptoHelper.copyByteArray(ba, null, ba.length); } @Test(expected = IndexOutOfBoundsException.class) public final void testCopyByteArrayIndexOutOfBoundsException() { byte[] ba8 = new byte[8]; byte[] ba16 = new byte[16]; CryptoHelper.copyByteArray(ba8, ba16, ba16.length); } @Test public final void testArrayCompare() { byte[] ba1 = new byte[32]; byte[] ba2 = new byte[32]; byte[] ba3 = new byte[48]; // Note: Don't need cryptographically secure random numbers for this! Random prng = new Random(); prng.nextBytes(ba1); prng.nextBytes(ba2); prng.nextBytes(ba3); /* * Unfortunately, can't rely no the nanosecond timer because as the * Javadoc for System.nanoTime() states, " No guarantees are made * about how frequently values change", so this is not very reliable. * * However, on can uncomment the code and observe that elapsed times * are generally less than 10 millionth of a second. I suppose if we * declared a large enough epsilon, we could make it work, but it is * easier to convince yourself from the CryptoHelper.arrayCompare() code * itself that it always goes through all the bits of the byte array * if it compares any bits at all. */ // long start, stop, diff; // start = System.nanoTime(); assertTrue(CryptoHelper.arrayCompare(null, null)); // stop = System.nanoTime(); // diff = stop - start; // System.out.println("diff: " + diff + " nanosec"); // start = System.nanoTime(); assertTrue(CryptoHelper.arrayCompare(ba1, ba1)); // stop = System.nanoTime(); // diff = stop - start; // System.out.println("diff: " + diff + " nanosec"); // start = System.nanoTime(); assertFalse(CryptoHelper.arrayCompare(ba1, ba2)); // stop = System.nanoTime(); // diff = stop - start; // System.out.println("diff: " + diff + " nanosec"); // start = System.nanoTime(); assertFalse(CryptoHelper.arrayCompare(ba1, ba3)); // stop = System.nanoTime(); // diff = stop - start; // System.out.println("diff: " + diff + " nanosec"); // start = System.nanoTime(); assertFalse(CryptoHelper.arrayCompare(ba1, null)); // stop = System.nanoTime(); // diff = stop - start; // System.out.println("diff: " + diff + " nanosec"); ba2 = ba1; // start = System.nanoTime(); assertTrue(CryptoHelper.arrayCompare(ba1, ba2)); // stop = System.nanoTime(); // diff = stop - start; // System.out.println("diff: " + diff + " nanosec"); } private void fillByteArray(byte[] ba, byte b) { for (int i = 0; i < ba.length; i++) { ba[i] = b; } } private boolean checkByteArray(byte[] ba, byte b) { for (int i = 0; i < ba.length; i++) { if (ba[i] != b) { return false; } } return true; } /** * Run all the test cases in this suite. This is to allow running from * {@code org.owasp.esapi.AllTests} which uses a JUnit 3 test runner. */ public static junit.framework.Test suite() { return new JUnit4TestAdapter(CryptoHelperTest.class); } }
package ru.parsentev.task_005; import org.junit.Test; import ru.parsentev.task_002.Point; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * TODO: comment * * @author parsentev * @since 28.07.2016 */ public class RightTriangleTest { @Test public void checkExists() { Point first = new Point(0, 0); Point second = new Point(0, 2); Point third = new Point(2, 0); boolean result = new RightTriangle(first, second, third).exists(); assertThat(result, is(false)); } @Test public void inLine() { Point first = new Point(0, 0); Point second = new Point(0, 2); Point third = new Point(0, 4); boolean result = new RightTriangle(first, second, third).exists(); assertThat(result, is(false)); } @Test public void notRight() { Point first = new Point(0, 0); Point second = new Point(2, 2); Point third = new Point(0, 5); boolean result = new RightTriangle(first, second, third).exists(); assertThat(result, is(false)); } }
package org.dynmap.spout; import java.io.File; import java.net.InetSocketAddress; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import org.dynmap.DynmapCommonAPI; import org.dynmap.DynmapCore; import org.dynmap.DynmapLocation; import org.dynmap.DynmapWorld; import org.dynmap.Log; import org.dynmap.common.BiomeMap; import org.dynmap.common.DynmapCommandSender; import org.dynmap.common.DynmapPlayer; import org.dynmap.common.DynmapServerInterface; import org.dynmap.common.DynmapListenerManager.EventType; import org.dynmap.markers.MarkerAPI; import org.dynmap.spout.permissions.PermissionProvider; import org.spout.api.command.Command; import org.spout.api.command.CommandSource; import org.spout.api.command.RawCommandExecutor; import org.spout.api.entity.Entity; import org.spout.api.event.Event; import org.spout.api.event.EventExecutor; import org.spout.api.event.EventHandler; import org.spout.api.event.Listener; import org.spout.api.event.block.BlockChangeEvent; import org.spout.api.event.player.PlayerChatEvent; import org.spout.api.event.player.PlayerJoinEvent; import org.spout.api.event.player.PlayerLeaveEvent; import org.spout.api.exception.CommandException; import org.spout.api.geo.World; import org.spout.api.geo.cuboid.Block; import org.spout.api.geo.discrete.Point; import org.spout.api.geo.discrete.atomic.AtomicPoint; import org.spout.api.geo.discrete.atomic.Transform; import org.spout.api.player.Player; import org.spout.api.plugin.CommonPlugin; import org.spout.api.plugin.PluginDescriptionFile; import org.spout.api.plugin.PluginManager; import org.spout.api.util.Named; import org.spout.api.Game; import org.spout.api.ChatColor; public class DynmapPlugin extends CommonPlugin implements DynmapCommonAPI { private final String prefix = "[Dynmap] "; private DynmapCore core; private PermissionProvider permissions; private String version; private Game game; public SpoutEventProcessor sep; //TODO public SnapshotCache sscache; public static DynmapPlugin plugin; public DynmapPlugin() { plugin = this; } /** * Server access abstraction class */ public class SpoutServer implements DynmapServerInterface { public void scheduleServerTask(Runnable run, long delay) { game.getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, run, delay); } public DynmapPlayer[] getOnlinePlayers() { Player[] players = game.getOnlinePlayers(); DynmapPlayer[] dplay = new DynmapPlayer[players.length]; for(int i = 0; i < players.length; i++) { dplay[i] = new SpoutPlayer(players[i]); } return dplay; } public void reload() { PluginManager pluginManager = game.getPluginManager(); pluginManager.disablePlugin(DynmapPlugin.this); pluginManager.enablePlugin(DynmapPlugin.this); } public DynmapPlayer getPlayer(String name) { Player p = game.getPlayer(name, true); if(p != null) { return new SpoutPlayer(p); } return null; } public Set<String> getIPBans() { //TODO return getServer().getIPBans(); return Collections.emptySet(); } public <T> Future<T> callSyncMethod(final Callable<T> task) { final FutureTask<T> ft = new FutureTask<T>(task); final Object o = new Object(); synchronized(o) { game.getScheduler().scheduleSyncDelayedTask(DynmapPlugin.this, new Runnable() { public void run() { try { ft.run(); } finally { synchronized(o) { o.notify(); } } } }); try { o.wait(); } catch (InterruptedException ix) {} } return ft; } public String getServerName() { return game.getName(); } public boolean isPlayerBanned(String pid) { //TODO OfflinePlayer p = getServer().getOfflinePlayer(pid); //TODO if((p != null) && p.isBanned()) //TODO return true; return false; } public String stripChatColor(String s) { return ChatColor.strip(s); } private Set<EventType> registered = new HashSet<EventType>(); public boolean requestEventNotification(EventType type) { if(registered.contains(type)) return true; switch(type) { case WORLD_LOAD: case WORLD_UNLOAD: /* Already called for normal world activation/deactivation */ break; case WORLD_SPAWN_CHANGE: //TODO sep.registerEvent(Type.SPAWN_CHANGE, new WorldListener() { //TODO @Override //TODO public void onSpawnChange(SpawnChangeEvent evt) { //TODO DynmapWorld w = new SpoutWorld(evt.getWorld()); //TODO core.listenerManager.processWorldEvent(EventType.WORLD_SPAWN_CHANGE, w); //TODO } //TODO }); break; case PLAYER_JOIN: case PLAYER_QUIT: /* Already handled */ break; case PLAYER_BED_LEAVE: //TODO sep.registerEvent(Type.PLAYER_BED_LEAVE, new PlayerListener() { //TODO @Override //TODO public void onPlayerBedLeave(PlayerBedLeaveEvent evt) { //TODO DynmapPlayer p = new BukkitPlayer(evt.getPlayer()); //TODO core.listenerManager.processPlayerEvent(EventType.PLAYER_BED_LEAVE, p); //TODO } //TODO }); break; case PLAYER_CHAT: sep.registerEvent(PlayerChatEvent.class, new EventExecutor() { public void execute(Event evt) { PlayerChatEvent chatevt = (PlayerChatEvent)evt; DynmapPlayer p = null; if(chatevt.getPlayer() != null) p = new SpoutPlayer(chatevt.getPlayer()); core.listenerManager.processChatEvent(EventType.PLAYER_CHAT, p, chatevt.getMessage()); } }); break; case BLOCK_BREAK: //TODO - doing this for all block changes, not just breaks sep.registerEvent(BlockChangeEvent.class, new EventExecutor() { public void execute(Event evt) { BlockChangeEvent bce = (BlockChangeEvent)evt; Block b = bce.getBlock(); core.listenerManager.processBlockEvent(EventType.BLOCK_BREAK, b.getBlockId(), b.getWorld().getName(), b.getX(), b.getY(), b.getZ()); } }); break; case SIGN_CHANGE: //TODO - no event yet //bep.registerEvent(Type.SIGN_CHANGE, new BlockListener() { // @Override // public void onSignChange(SignChangeEvent evt) { // Block b = evt.getBlock(); // Location l = b.getLocation(); // String[] lines = evt.getLines(); /* Note: changes to this change event - intentional */ // DynmapPlayer dp = null; // Player p = evt.getPlayer(); // if(p != null) dp = new BukkitPlayer(p); // core.listenerManager.processSignChangeEvent(EventType.SIGN_CHANGE, b.getType().getId(), // l.getWorld().getName(), l.getBlockX(), l.getBlockY(), l.getBlockZ(), lines, dp); break; default: Log.severe("Unhandled event type: " + type); return false; } return true; } public boolean sendWebChatEvent(String source, String name, String msg) { DynmapWebChatEvent evt = new DynmapWebChatEvent(source, name, msg); game.getEventManager().callEvent(evt); return (evt.isCancelled() == false); } public void broadcastMessage(String msg) { game.broadcastMessage(msg); } public String[] getBiomeIDs() { BiomeMap[] b = BiomeMap.values(); String[] bname = new String[b.length]; for(int i = 0; i < bname.length; i++) bname[i] = b[i].toString(); return bname; } public double getCacheHitRate() { //TODO return sscache.getHitRate(); return 0.0; } public void resetCacheStats() { //TODO sscache.resetStats(); } public DynmapWorld getWorldByName(String wname) { World w = game.getWorld(wname); if(w != null) { return new SpoutWorld(w); } return null; } public DynmapPlayer getOfflinePlayer(String name) { //TODO return null; } } /** * Player access abstraction class */ public class SpoutPlayer extends SpoutCommandSender implements DynmapPlayer { private Player player; public SpoutPlayer(Player p) { super(p); player = p; } public boolean isConnected() { return player.isOnline(); } public String getName() { return player.getName(); } public String getDisplayName() { return player.getDisplayName(); } public boolean isOnline() { return player.isOnline(); } public DynmapLocation getLocation() { Point p = player.getEntity().getTransform().getPosition(); return toLoc(p); } public String getWorld() { Entity e = player.getEntity(); if(e != null) { World w = e.getWorld(); if(w != null) { return w.getName(); } } return null; } public InetSocketAddress getAddress() { return new InetSocketAddress(player.getAddress(), 0); } public boolean isSneaking() { //TODO return false; } public int getHealth() { //TODO return 0; } public int getArmorPoints() { //TODO return 0; } public DynmapLocation getBedSpawnLocation() { //TODO return null; } public long getLastLoginTime() { // TODO return 0; } public long getFirstLoginTime() { // TODO return 0; } } /* Handler for generic console command sender */ public class SpoutCommandSender implements DynmapCommandSender { private CommandSource sender; public SpoutCommandSender(CommandSource send) { sender = send; } public boolean hasPrivilege(String privid) { return permissions.has(sender, privid); } public void sendMessage(String msg) { sender.sendMessage(msg); } public boolean isConnected() { return true; } public boolean isOp() { //TODO return sender.isInGroup(group) return false; } } @Override public void onEnable() { game = getGame(); PluginDescriptionFile pdfFile = this.getDescription(); version = pdfFile.getVersion(); /* Initialize event processor */ if(sep == null) sep = new SpoutEventProcessor(this); /* Set up player login/quit event handler */ registerPlayerLoginListener(); permissions = new PermissionProvider(); /* Use spout default */ /* Get and initialize data folder */ File dataDirectory = this.getDataFolder(); if(dataDirectory.exists() == false) dataDirectory.mkdirs(); /* Get MC version */ String mcver = game.getVersion(); /* Instantiate core */ if(core == null) core = new DynmapCore(); /* Inject dependencies */ core.setPluginVersion(version); core.setMinecraftVersion(mcver); core.setDataFolder(dataDirectory); core.setServer(new SpoutServer()); /* Enable core */ if(!core.enableCore()) { this.setEnabled(false); return; } //TODO sscache = new SnapshotCache(core.getSnapShotCacheSize()); game.getScheduler().scheduleSyncDelayedTask(this, new Runnable() { public void run() { /* Initialized the currently loaded worlds */ for (World world : game.getWorlds()) { SpoutWorld w = new SpoutWorld(world); if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */ core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w); } } }, 100); /* Register our update trigger events */ registerEvents(); Command cmd = game.getRootCommand().addSubCommand(new Named() { public String getName() { return "dynmap"; } }, "dynmap"); cmd.setRawExecutor(new RawCommandExecutor() { public void execute(CommandSource sender, String[] args, int baseIndex, boolean fuzzyLookup) throws CommandException { DynmapCommandSender dsender; if(sender instanceof Player) { dsender = new SpoutPlayer((Player)sender); } else { dsender = new SpoutCommandSender(sender); } String[] cmdargs = new String[args.length-1]; System.arraycopy(args, 1, cmdargs, 0, cmdargs.length); if(!core.processCommand(dsender, args[0], "dynmap", cmdargs)) throw new CommandException("Bad Command"); } }); } @Override public void onDisable() { /* Reset registered listeners */ sep.cleanup(); /* Disable core */ core.disableCore(); //TODO if(sscache != null) { //TODO sscache.cleanup(); //TODO sscache = null; //TODO } } public String getPrefix() { return prefix; } public final MarkerAPI getMarkerAPI() { return core.getMarkerAPI(); } public final boolean markerAPIInitialized() { return core.markerAPIInitialized(); } public final boolean sendBroadcastToWeb(String sender, String msg) { return core.sendBroadcastToWeb(sender, msg); } public final int triggerRenderOfVolume(String wid, int minx, int miny, int minz, int maxx, int maxy, int maxz) { return core.triggerRenderOfVolume(wid, minx, miny, minz, maxx, maxy, maxz); } public final int triggerRenderOfBlock(String wid, int x, int y, int z) { return core.triggerRenderOfBlock(wid, x, y, z); } public final void setPauseFullRadiusRenders(boolean dopause) { core.setPauseFullRadiusRenders(dopause); } public final boolean getPauseFullRadiusRenders() { return core.getPauseFullRadiusRenders(); } public final void setPauseUpdateRenders(boolean dopause) { core.setPauseUpdateRenders(dopause); } public final boolean getPauseUpdateRenders() { return core.getPauseUpdateRenders(); } public final void setPlayerVisiblity(String player, boolean is_visible) { core.setPlayerVisiblity(player, is_visible); } public final boolean getPlayerVisbility(String player) { return core.getPlayerVisbility(player); } public final void postPlayerMessageToWeb(String playerid, String playerdisplay, String message) { core.postPlayerMessageToWeb(playerid, playerdisplay, message); } public final void postPlayerJoinQuitToWeb(String playerid, String playerdisplay, boolean isjoin) { core.postPlayerJoinQuitToWeb(playerid, playerdisplay, isjoin); } public final String getDynmapCoreVersion() { return core.getDynmapCoreVersion(); } public final void setPlayerVisiblity(Player player, boolean is_visible) { core.setPlayerVisiblity(player.getName(), is_visible); } public final boolean getPlayerVisbility(Player player) { return core.getPlayerVisbility(player.getName()); } public final void postPlayerMessageToWeb(Player player, String message) { core.postPlayerMessageToWeb(player.getName(), player.getDisplayName(), message); } public void postPlayerJoinQuitToWeb(Player player, boolean isjoin) { core.postPlayerJoinQuitToWeb(player.getName(), player.getDisplayName(), isjoin); } public String getDynmapVersion() { return version; } private static DynmapLocation toLoc(Point p) { return new DynmapLocation(p.getWorld().getName(), p.getX(), p.getY(), p.getZ()); } private void registerPlayerLoginListener() { sep.registerEvent(PlayerJoinEvent.class, new EventExecutor() { public void execute(Event evt) { PlayerJoinEvent pje = (PlayerJoinEvent)evt; SpoutPlayer dp = new SpoutPlayer(pje.getPlayer()); core.listenerManager.processPlayerEvent(EventType.PLAYER_JOIN, dp); } }); sep.registerEvent(PlayerLeaveEvent.class, new EventExecutor() { public void execute(Event evt) { PlayerLeaveEvent pje = (PlayerLeaveEvent)evt; SpoutPlayer dp = new SpoutPlayer(pje.getPlayer()); core.listenerManager.processPlayerEvent(EventType.PLAYER_QUIT, dp); } }); } private boolean onplace; private boolean onbreak; private boolean onblockform; private boolean onblockfade; private boolean onblockspread; private boolean onblockfromto; private boolean onblockphysics; private boolean onleaves; private boolean onburn; private boolean onpiston; private boolean onplayerjoin; private boolean onplayermove; private boolean ongeneratechunk; private boolean onloadchunk; private boolean onexplosion; private void registerEvents() { // BlockListener blockTrigger = new BlockListener() { // @Override // public void onBlockPlace(BlockPlaceEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onplace) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockplace"); // @Override // public void onBlockBreak(BlockBreakEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onbreak) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockbreak"); // @Override // public void onLeavesDecay(LeavesDecayEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onleaves) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "leavesdecay"); // @Override // public void onBlockBurn(BlockBurnEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onburn) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockburn"); // @Override // public void onBlockForm(BlockFormEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onblockform) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockform"); // @Override // public void onBlockFade(BlockFadeEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onblockfade) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockfade"); // @Override // public void onBlockSpread(BlockSpreadEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onblockspread) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockspread"); // @Override // public void onBlockFromTo(BlockFromToEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getToBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onblockfromto) // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockfromto"); // loc = event.getBlock().getLocation(); // wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onblockfromto) // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockfromto"); // @Override // public void onBlockPhysics(BlockPhysicsEvent event) { // if(event.isCancelled()) // return; // Location loc = event.getBlock().getLocation(); // String wn = loc.getWorld().getName(); // sscache.invalidateSnapshot(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); // if(onblockphysics) { // mapManager.touch(wn, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ(), "blockphysics"); // @Override // public void onBlockPistonRetract(BlockPistonRetractEvent event) { // if(event.isCancelled()) // return; // Block b = event.getBlock(); // Location loc = b.getLocation(); // BlockFace dir; // try { // dir = event.getDirection(); // } catch (ClassCastException ccx) { // dir = BlockFace.NORTH; // String wn = loc.getWorld().getName(); // int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ(); // sscache.invalidateSnapshot(wn, x, y, z); // if(onpiston) // mapManager.touch(wn, x, y, z, "pistonretract"); // for(int i = 0; i < 2; i++) { // x += dir.getModX(); // y += dir.getModY(); // z += dir.getModZ(); // sscache.invalidateSnapshot(wn, x, y, z); // if(onpiston) // mapManager.touch(wn, x, y, z, "pistonretract"); // @Override // public void onBlockPistonExtend(BlockPistonExtendEvent event) { // if(event.isCancelled()) // return; // Block b = event.getBlock(); // Location loc = b.getLocation(); // BlockFace dir; // try { // dir = event.getDirection(); // } catch (ClassCastException ccx) { // dir = BlockFace.NORTH; // String wn = loc.getWorld().getName(); // int x = loc.getBlockX(), y = loc.getBlockY(), z = loc.getBlockZ(); // sscache.invalidateSnapshot(wn, x, y, z); // if(onpiston) // mapManager.touch(wn, x, y, z, "pistonretract"); // for(int i = 0; i < 1+event.getLength(); i++) { // x += dir.getModX(); // y += dir.getModY(); // z += dir.getModZ(); // sscache.invalidateSnapshot(wn, x, y, z); // if(onpiston) // mapManager.touch(wn, x, y, z, "pistonretract"); // // To trigger rendering. // onplace = core.isTrigger("blockplaced"); // bep.registerEvent(Event.Type.BLOCK_PLACE, blockTrigger); // onbreak = core.isTrigger("blockbreak"); // bep.registerEvent(Event.Type.BLOCK_BREAK, blockTrigger); // if(core.isTrigger("snowform")) Log.info("The 'snowform' trigger has been deprecated due to Bukkit changes - use 'blockformed'"); // onleaves = core.isTrigger("leavesdecay"); // bep.registerEvent(Event.Type.LEAVES_DECAY, blockTrigger); // onburn = core.isTrigger("blockburn"); // bep.registerEvent(Event.Type.BLOCK_BURN, blockTrigger); // onblockform = core.isTrigger("blockformed"); // bep.registerEvent(Event.Type.BLOCK_FORM, blockTrigger); // onblockfade = core.isTrigger("blockfaded"); // bep.registerEvent(Event.Type.BLOCK_FADE, blockTrigger); // onblockspread = core.isTrigger("blockspread"); // bep.registerEvent(Event.Type.BLOCK_SPREAD, blockTrigger); // onblockfromto = core.isTrigger("blockfromto"); // bep.registerEvent(Event.Type.BLOCK_FROMTO, blockTrigger); // onblockphysics = core.isTrigger("blockphysics"); // bep.registerEvent(Event.Type.BLOCK_PHYSICS, blockTrigger); // onpiston = core.isTrigger("pistonmoved"); // bep.registerEvent(Event.Type.BLOCK_PISTON_EXTEND, blockTrigger); // bep.registerEvent(Event.Type.BLOCK_PISTON_RETRACT, blockTrigger); // /* Register player event trigger handlers */ Listener playerTrigger = new Listener() { @EventHandler void handlePlayerJoin(PlayerJoinEvent event) { if(onplayerjoin) { AtomicPoint loc = event.getPlayer().getEntity().getTransform().getPosition(); core.mapManager.touch(loc.getWorld().getName(), (int)loc.getX(), (int)loc.getY(), (int)loc.getZ(), "playerjoin"); } core.listenerManager.processPlayerEvent(EventType.PLAYER_JOIN, new SpoutPlayer(event.getPlayer())); } @EventHandler void handlePlayerLeave(PlayerLeaveEvent event) { core.listenerManager.processPlayerEvent(EventType.PLAYER_QUIT, new SpoutPlayer(event.getPlayer())); } }; onplayerjoin = core.isTrigger("playerjoin"); onplayermove = core.isTrigger("playermove"); game.getEventManager().registerEvents(playerTrigger, plugin); // if(onplayermove) // bep.registerEvent(Event.Type.PLAYER_MOVE, playerTrigger); // /* Register entity event triggers */ // EntityListener entityTrigger = new EntityListener() { // @Override // public void onEntityExplode(EntityExplodeEvent event) { // Location loc = event.getLocation(); // String wname = loc.getWorld().getName(); // int minx, maxx, miny, maxy, minz, maxz; // minx = maxx = loc.getBlockX(); // miny = maxy = loc.getBlockY(); // minz = maxz = loc.getBlockZ(); // /* Calculate volume impacted by explosion */ // List<Block> blocks = event.blockList(); // for(Block b: blocks) { // Location l = b.getLocation(); // int x = l.getBlockX(); // if(x < minx) minx = x; // if(x > maxx) maxx = x; // int y = l.getBlockY(); // if(y < miny) miny = y; // if(y > maxy) maxy = y; // int z = l.getBlockZ(); // if(z < minz) minz = z; // if(z > maxz) maxz = z; // sscache.invalidateSnapshot(wname, minx, miny, minz, maxx, maxy, maxz); // if(onexplosion) { // mapManager.touchVolume(wname, minx, miny, minz, maxx, maxy, maxz, "entityexplode"); // onexplosion = core.isTrigger("explosion"); // bep.registerEvent(Event.Type.ENTITY_EXPLODE, entityTrigger); // /* Register world event triggers */ // WorldListener worldTrigger = new WorldListener() { // @Override // public void onChunkLoad(ChunkLoadEvent event) { // if(DynmapCore.ignore_chunk_loads) // return; // Chunk c = event.getChunk(); // /* Touch extreme corners */ // int x = c.getX() << 4; // int z = c.getZ() << 4; // mapManager.touchVolume(event.getWorld().getName(), x, 0, z, x+15, 128, z+16, "chunkload"); // @Override // public void onChunkPopulate(ChunkPopulateEvent event) { // Chunk c = event.getChunk(); // /* Touch extreme corners */ // int x = c.getX() << 4; // int z = c.getZ() << 4; // mapManager.touchVolume(event.getWorld().getName(), x, 0, z, x+15, 128, z+16, "chunkpopulate"); // @Override // public void onWorldLoad(WorldLoadEvent event) { // core.updateConfigHashcode(); // SpoutWorld w = new SpoutWorld(event.getWorld()); // if(core.processWorldLoad(w)) /* Have core process load first - fire event listeners if good load after */ // core.listenerManager.processWorldEvent(EventType.WORLD_LOAD, w); // @Override // public void onWorldUnload(WorldUnloadEvent event) { // core.updateConfigHashcode(); // DynmapWorld w = core.getWorld(event.getWorld().getName()); // if(w != null) // core.listenerManager.processWorldEvent(EventType.WORLD_UNLOAD, w); // ongeneratechunk = core.isTrigger("chunkgenerated"); // if(ongeneratechunk) { // bep.registerEvent(Event.Type.CHUNK_POPULATED, worldTrigger); // onloadchunk = core.isTrigger("chunkloaded"); // if(onloadchunk) { // bep.registerEvent(Event.Type.CHUNK_LOAD, worldTrigger); // // To link configuration to real loaded worlds. // bep.registerEvent(Event.Type.WORLD_LOAD, worldTrigger); // bep.registerEvent(Event.Type.WORLD_UNLOAD, worldTrigger); } public void assertPlayerInvisibility(String player, boolean is_invisible, String plugin_id) { core.assertPlayerInvisibility(player, is_invisible, plugin_id); } }
package seedu.address.commons.util; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.TextStyle; import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.Locale; import org.junit.Test; import seedu.todo.commons.util.DateUtil; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class DateUtilTest { @Test public void toDate_equalTimestamps() { long currTimeMs = java.lang.System.currentTimeMillis(); Date testDate = new Date(currTimeMs); LocalDateTime testDateTime = fromEpoch(currTimeMs); Date actualDate = DateUtil.toDate(testDateTime); assertEquals(testDate.getTime(), actualDate.getTime()); } @Test public void toDate_differentTimestamps() { long currTimeMs = java.lang.System.currentTimeMillis(); Date testDate = new Date(currTimeMs); LocalDateTime testDateTime = fromEpoch(currTimeMs + 1); Date actualDate = DateUtil.toDate(testDateTime); assertNotEquals(testDate.getTime(), actualDate.getTime()); } @Test public void floorDate_sameDate() { long testEpoch1 = 1476099300000l; // 10/10/2016 @ 11:35am (UTC) long testEpoch2 = 1476099360000l; // 10/10/2016 @ 11:36am (UTC) LocalDateTime testDateTime1 = fromEpoch(testEpoch1); LocalDateTime testDateTime2 = fromEpoch(testEpoch2); assertEquals(DateUtil.floorDate(testDateTime1), DateUtil.floorDate(testDateTime2)); } @Test public void floorDate_differentDate() { long testEpoch1 = 1476099300000l; // 10/10/2016 @ 11:35am (UTC) long testEpoch2 = 1476185700000l; // 11/10/2016 @ 11:35am (UTC) LocalDateTime testDateTime1 = fromEpoch(testEpoch1); LocalDateTime testDateTime2 = fromEpoch(testEpoch2); assertNotEquals(DateUtil.floorDate(testDateTime1), DateUtil.floorDate(testDateTime2)); } @Test public void formatDayTests() { LocalDateTime now = LocalDateTime.now(); assertEquals(DateUtil.formatDay(now), "Today " + now.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.US).substring(0, 3) + " " + now.getDayOfMonth() + " " + now.getMonth().getDisplayName(TextStyle.FULL, Locale.US).substring(0, 3)); assertEquals(DateUtil.formatDay(now.plus(1, ChronoUnit.DAYS)), "Tomorrow " + now.plus(1, ChronoUnit.DAYS).getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.US).substring(0, 3) + " " + now.plus(1, ChronoUnit.DAYS).getDayOfMonth() + " " + now.plus(1, ChronoUnit.DAYS).getMonth().getDisplayName(TextStyle.FULL, Locale.US).substring(0, 3)); assertEquals(DateUtil.formatDay(now.plus(2, ChronoUnit.DAYS)), now.plus(2, ChronoUnit.DAYS).getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.US) + " " + now.plus(2, ChronoUnit.DAYS).getDayOfMonth() + " " + now.plus(2, ChronoUnit.DAYS).getMonth().getDisplayName(TextStyle.FULL, Locale.US).substring(0, 3)); assertEquals(DateUtil.formatDay(now.plus(6, ChronoUnit.DAYS)), now.plus(6, ChronoUnit.DAYS).getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.US) + " " + now.plus(6, ChronoUnit.DAYS).getDayOfMonth() + " " + now.plus(6, ChronoUnit.DAYS).getMonth().getDisplayName(TextStyle.FULL, Locale.US).substring(0, 3)); assertEquals(DateUtil.formatDay(now.minus(1, ChronoUnit.DAYS)), "1 day ago"); assertEquals(DateUtil.formatDay(now.minus(6, ChronoUnit.DAYS)), "6 days ago"); assertEquals(DateUtil.formatDay(now.minus(14, ChronoUnit.DAYS)), "14 days ago"); } private static LocalDateTime fromEpoch(long epoch) { return LocalDateTime.ofInstant(Instant.ofEpochMilli(epoch), ZoneId.systemDefault()); } }
package org.javacs; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.sun.source.util.TreePath; import com.sun.source.util.Trees; import org.eclipse.lsp4j.*; import org.eclipse.lsp4j.jsonrpc.messages.Either; import org.eclipse.lsp4j.services.LanguageClient; import org.eclipse.lsp4j.services.LanguageServer; import org.eclipse.lsp4j.services.TextDocumentService; import org.eclipse.lsp4j.services.WorkspaceService; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.lang.model.element.Element; import javax.tools.JavaFileObject; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.*; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.javacs.Main.JSON; class JavaLanguageServer implements LanguageServer { private static final Logger LOG = Logger.getLogger("main"); int maxItems = 100; private Path workspaceRoot; private Map<URI, String> activeDocuments = new HashMap<>(); private LanguageClient client; JavaLanguageServer() { this.testJavac = Optional.empty(); } JavaLanguageServer(JavacHolder testJavac) { this.testJavac = Optional.of(testJavac); } @Override public CompletableFuture<InitializeResult> initialize(InitializeParams params) { workspaceRoot = Paths.get(params.getRootPath()).toAbsolutePath().normalize(); InitializeResult result = new InitializeResult(); ServerCapabilities c = new ServerCapabilities(); c.setTextDocumentSync(TextDocumentSyncKind.Incremental); c.setDefinitionProvider(true); c.setCompletionProvider(new CompletionOptions(false, ImmutableList.of("."))); c.setHoverProvider(true); c.setWorkspaceSymbolProvider(true); c.setReferencesProvider(true); c.setDocumentSymbolProvider(true); c.setCodeActionProvider(true); c.setExecuteCommandProvider(new ExecuteCommandOptions(ImmutableList.of("Java.importClass"))); result.setCapabilities(c); return CompletableFuture.completedFuture(result); } @Override public CompletableFuture<Object> shutdown() { return CompletableFuture.completedFuture(null); } @Override public void exit() { } @Override public TextDocumentService getTextDocumentService() { return new TextDocumentService() { @Override public CompletableFuture<Either<List<CompletionItem>, CompletionList>> completion(TextDocumentPositionParams position) { Instant started = Instant.now(); URI uri = URI.create(position.getTextDocument().getUri()); Optional<String> content = activeContent(uri); int line = position.getPosition().getLine() + 1; int character = position.getPosition().getCharacter() + 1; LOG.info(String.format("completion at %s %d:%d", uri, line, character)); List<CompletionItem> items = findCompiler(uri) .map(compiler -> compiler.compileFocused(uri, content, line, character, true)) .map(Completions::at) .orElseGet(Stream::empty) .limit(maxItems) .collect(Collectors.toList()); CompletionList result = new CompletionList(items.size() == maxItems, items); Duration elapsed = Duration.between(started, Instant.now()); if (result.isIncomplete()) LOG.info(String.format("Found %d items (incomplete) in %d ms", items.size(), elapsed.toMillis())); else LOG.info(String.format("Found %d items in %d ms", items.size(), elapsed.toMillis())); return CompletableFuture.completedFuture(Either.forRight(result)); } @Override public CompletableFuture<CompletionItem> resolveCompletionItem(CompletionItem unresolved) { return null; } @Override public CompletableFuture<Hover> hover(TextDocumentPositionParams position) { URI uri = URI.create(position.getTextDocument().getUri()); Optional<String> content = activeContent(uri); int line = position.getPosition().getLine() + 1; int character = position.getPosition().getCharacter() + 1; LOG.info(String.format("hover at %s %d:%d", uri, line, character)); Hover hover = findCompiler(uri) .map(compiler -> compiler.compileFocused(uri, content, line, character, false)) .flatMap(Hovers::hoverText) .orElseGet(Hover::new); return CompletableFuture.completedFuture(hover); } @Override public CompletableFuture<SignatureHelp> signatureHelp(TextDocumentPositionParams position) { return null; } @Override public CompletableFuture<List<? extends Location>> definition(TextDocumentPositionParams position) { URI uri = URI.create(position.getTextDocument().getUri()); Optional<String> content = activeContent(uri); int line = position.getPosition().getLine() + 1; int character = position.getPosition().getCharacter() + 1; LOG.info(String.format("definition at %s %d:%d", uri, line, character)); List<Location> locations = findCompiler(uri) .flatMap(compiler -> { FocusedResult result = compiler.compileFocused(uri, content, line, character, false); return References.gotoDefinition(result, compiler.index); }) .map(Collections::singletonList) .orElseGet(Collections::emptyList); return CompletableFuture.completedFuture(locations); } @Override public CompletableFuture<List<? extends Location>> references(ReferenceParams params) { URI uri = URI.create(params.getTextDocument().getUri()); Optional<String> content = activeContent(uri); int line = params.getPosition().getLine() + 1; int character = params.getPosition().getCharacter() + 1; LOG.info(String.format("references at %s %d:%d", uri, line, character)); List<Location> locations = findCompiler(uri) .map(compiler -> { FocusedResult result = compiler.compileFocused(uri, content, line, character, false); return References.findReferences(result, compiler.index); }) .orElseGet(Stream::empty) .collect(Collectors.toList()); return CompletableFuture.completedFuture(locations); } @Override public CompletableFuture<List<? extends DocumentHighlight>> documentHighlight(TextDocumentPositionParams position) { return null; } @Override public CompletableFuture<List<? extends SymbolInformation>> documentSymbol(DocumentSymbolParams params) { URI uri = URI.create(params.getTextDocument().getUri()); List<SymbolInformation> symbols = findCompiler(uri) .map(compiler -> compiler.searchFile(uri)) .orElse(Stream.empty()) .collect(Collectors.toList()); return CompletableFuture.completedFuture(symbols); } @Override public CompletableFuture<List<? extends Command>> codeAction(CodeActionParams params) { URI uri = URI.create(params.getTextDocument().getUri()); int line = params.getRange().getStart().getLine() + 1; int character = params.getRange().getStart().getCharacter() + 1; LOG.info(String.format("codeAction at %s %d:%d", uri, line, character)); List<? extends Command> commands = findCompiler(uri) .map(compiler -> new CodeActions(compiler, uri, activeContent(uri), line, character).find(params)) .orElse(Collections.emptyList()); return CompletableFuture.completedFuture(commands); } @Override public CompletableFuture<List<? extends CodeLens>> codeLens(CodeLensParams params) { return null; } @Override public CompletableFuture<CodeLens> resolveCodeLens(CodeLens unresolved) { return null; } @Override public CompletableFuture<List<? extends TextEdit>> formatting(DocumentFormattingParams params) { return null; } @Override public CompletableFuture<List<? extends TextEdit>> rangeFormatting(DocumentRangeFormattingParams params) { return null; } @Override public CompletableFuture<List<? extends TextEdit>> onTypeFormatting(DocumentOnTypeFormattingParams params) { return null; } @Override public CompletableFuture<WorkspaceEdit> rename(RenameParams params) { return null; } @Override public void didOpen(DidOpenTextDocumentParams params) { try { TextDocumentItem document = params.getTextDocument(); URI uri = URI.create(document.getUri()); String text = document.getText(); activeDocuments.put(uri, text); doLint(Collections.singleton(uri)); } catch (NoJavaConfigException e) { throw ShowMessageException.warning(e.getMessage(), e); } } @Override public void didChange(DidChangeTextDocumentParams params) { VersionedTextDocumentIdentifier document = params.getTextDocument(); URI uri = URI.create(document.getUri()); for (TextDocumentContentChangeEvent change : params.getContentChanges()) { if (change.getRange() == null) activeDocuments.put(uri, change.getText()); else { String existingText = activeDocuments.get(uri); String newText = patch(existingText, change); activeDocuments.put(uri, newText); } } } @Override public void didClose(DidCloseTextDocumentParams params) { TextDocumentIdentifier document = params.getTextDocument(); URI uri = URI.create(document.getUri()); // Remove from source cache activeDocuments.remove(uri); } @Override public void didSave(DidSaveTextDocumentParams params) { // Re-lint all active documents doLint(activeDocuments.keySet()); params.getText(); } }; } private String patch(String sourceText, TextDocumentContentChangeEvent change) { try { Range range = change.getRange(); BufferedReader reader = new BufferedReader(new StringReader(sourceText)); StringWriter writer = new StringWriter(); // Skip unchanged lines int line = 0; while (line < range.getStart().getLine()) { writer.write(reader.readLine() + '\n'); line++; } // Skip unchanged chars for (int character = 0; character < range.getStart().getCharacter(); character++) writer.write(reader.read()); // Write replacement text writer.write(change.getText()); // Skip replaced text reader.skip(change.getRangeLength()); // Write remaining text while (true) { int next = reader.read(); if (next == -1) return writer.toString(); else writer.write(next); } } catch (IOException e) { throw new RuntimeException(e); } } private void doLint(Collection<URI> paths) { LOG.info("Lint " + Joiner.on(", ").join(paths)); Map<JavacConfig, Map<URI, Optional<String>>> files = new HashMap<>(); for (URI each : paths) { file(each).flatMap(this::findConfig).ifPresent(config -> { files.computeIfAbsent(config, newConfig -> new HashMap<>()).put(each, Optional.empty()); }); } files.forEach((config, configFiles) -> { BatchResult compile = findCompilerForConfig(config).compileBatch(configFiles); publishDiagnostics(paths, compile); }); } /** * Text of file, if it is in the active set */ private Optional<String> activeContent(URI file) { return Optional.ofNullable(activeDocuments.get(file)); } @Override public WorkspaceService getWorkspaceService() { return new WorkspaceService() { @Override public CompletableFuture<Object> executeCommand(ExecuteCommandParams params) { LOG.info(params.toString()); switch (params.getCommand()) { case "Java.importClass": String fileString = (String) params.getArguments().get(0); URI fileUri = URI.create(fileString); String packageName = (String) params.getArguments().get(1); String className = (String) params.getArguments().get(2); findCompiler(fileUri).ifPresent(compiler -> { FocusedResult compiled = compiler.compileFocused(fileUri, activeContent(fileUri), 1, 1, false); if (compiled.compilationUnit.getSourceFile().toUri().equals(fileUri)) { List<TextEdit> edits = new RefactorFile(compiled.task, compiled.compilationUnit) .addImport(packageName, className); client.applyEdit(new ApplyWorkspaceEditParams(new WorkspaceEdit( Collections.singletonMap(fileString, edits), null ))); } }); break; default: LOG.warning("Don't know what to do with " + params.getCommand()); } return CompletableFuture.completedFuture("Done"); } @Override public CompletableFuture<List<? extends SymbolInformation>> symbol(WorkspaceSymbolParams params) { Collection<JavacHolder> compilers = testJavac .map(javac -> (Collection<JavacHolder>) Collections.singleton(javac)) .orElseGet(compilerCache::values); List<SymbolInformation> infos = compilers.stream() .flatMap(compiler -> compiler.searchWorkspace(params.getQuery())) .limit(maxItems) .collect(Collectors.toList()); return CompletableFuture.completedFuture(infos); } @Override public void didChangeConfiguration(DidChangeConfigurationParams didChangeConfigurationParams) { } @Override public void didChangeWatchedFiles(DidChangeWatchedFilesParams params) { for (FileEvent event : params.getChanges()) { if (event.getUri().endsWith(".java")) { if (event.getType() == FileChangeType.Deleted) { URI uri = URI.create(event.getUri()); activeDocuments.remove(uri); findCompiler(uri).ifPresent(compiler -> { BatchResult result = compiler.delete(uri); publishDiagnostics(Collections.singleton(uri), result); }); } } else if (event.getUri().endsWith("javaconfig.json")) { // TODO invalidate caches when javaconfig.json changes } } } }; } private void publishDiagnostics(Collection<URI> touched, BatchResult result) { Map<URI, PublishDiagnosticsParams> files = new HashMap<>(); touched.forEach(p -> files.put(p, newPublishDiagnostics(p))); result.errors.getDiagnostics().forEach(error -> { if (error.getStartPosition() != javax.tools.Diagnostic.NOPOS) { URI uri = error.getSource().toUri(); PublishDiagnosticsParams publish = files.computeIfAbsent(uri, this::newPublishDiagnostics); Range range = position(error); Diagnostic diagnostic = new Diagnostic(); DiagnosticSeverity severity = severity(error.getKind()); diagnostic.setSeverity(severity); diagnostic.setRange(range); diagnostic.setCode(error.getCode()); diagnostic.setMessage(error.getMessage(null)); publish.getDiagnostics().add(diagnostic); } }); files.values().forEach(d -> client.publishDiagnostics(d)); } private DiagnosticSeverity severity(javax.tools.Diagnostic.Kind kind) { switch (kind) { case ERROR: return DiagnosticSeverity.Error; case WARNING: case MANDATORY_WARNING: return DiagnosticSeverity.Warning; case NOTE: case OTHER: default: return DiagnosticSeverity.Information; } } private PublishDiagnosticsParams newPublishDiagnostics(URI newUri) { PublishDiagnosticsParams p = new PublishDiagnosticsParams(); p.setDiagnostics(new ArrayList<>()); p.setUri(newUri.toString()); return p; } private Map<JavacConfig, JavacHolder> compilerCache = new HashMap<>(); /** * Instead of looking for javaconfig.json and creating a JavacHolder, just use this. * For testing. */ private final Optional<JavacHolder> testJavac; /** * Look for a configuration in a parent directory of uri */ private Optional<JavacHolder> findCompiler(URI uri) { if (testJavac.isPresent()) return testJavac; else return dir(uri) .flatMap(this::findConfig) .map(this::findCompilerForConfig); } private static Optional<Path> dir(URI uri) { return file(uri).map(path -> path.getParent()); } private static Optional<Path> file(URI uri) { if (!uri.getScheme().equals("file")) return Optional.empty(); else return Optional.of(Paths.get(uri)); } private JavacHolder findCompilerForConfig(JavacConfig config) { if (testJavac.isPresent()) return testJavac.get(); else return compilerCache.computeIfAbsent(config, this::newJavac); } private JavacHolder newJavac(JavacConfig c) { return JavacHolder.create(c.classPath, c.sourcePath, c.outputDirectory); } // TODO invalidate cache when VSCode notifies us config file has changed private Map<Path, Optional<JavacConfig>> configCache = new HashMap<>(); private Optional<JavacConfig> findConfig(Path file) { if (!file.toFile().isDirectory()) file = file.getParent(); if (file == null) return Optional.empty(); return configCache.computeIfAbsent(file, this::doFindConfig); } private Optional<JavacConfig> doFindConfig(Path dir) { if (testJavac.isPresent()) return testJavac.map(j -> new JavacConfig(j.sourcePath, j.classPath, j.outputDirectory)); while (true) { Optional<JavacConfig> found = readIfConfig(dir); if (found.isPresent()) return found; else if (workspaceRoot.startsWith(dir)) return Optional.empty(); else dir = dir.getParent(); } } /** * If directory contains a config file, for example javaconfig.json or an eclipse project file, read it. */ private Optional<JavacConfig> readIfConfig(Path dir) { if (Files.exists(dir.resolve("javaconfig.json"))) { JavaConfigJson json = readJavaConfigJson(dir.resolve("javaconfig.json")); Set<Path> classPath = json.classPathFile.map(classPathFile -> { Path classPathFilePath = dir.resolve(classPathFile); return readClassPathFile(classPathFilePath); }).orElse(Collections.emptySet()); Set<Path> sourcePath = json.sourcePath.stream().map(dir::resolve).collect(Collectors.toSet()); Path outputDirectory = dir.resolve(json.outputDirectory); JavacConfig config = new JavacConfig(sourcePath, classPath, outputDirectory); return Optional.of(config); } else if (Files.exists(dir.resolve("pom.xml"))) { Path pomXml = dir.resolve("pom.xml"); // Invoke maven to get classpath Set<Path> classPath = buildClassPath(pomXml); // Get source directory from pom.xml Set<Path> sourcePath = sourceDirectories(pomXml); // Use target/javacs Path outputDirectory = Paths.get("target/classes").toAbsolutePath(); JavacConfig config = new JavacConfig(sourcePath, classPath, outputDirectory); return Optional.of(config); } // TODO add more file types else { return Optional.empty(); } } public static Set<Path> buildClassPath(Path pomXml) { try { Objects.requireNonNull(pomXml, "pom.xml path is null"); // Tell maven to output classpath to a temporary file // TODO if pom.xml already specifies outputFile, use that location Path classPathTxt = Files.createTempFile("classpath", ".txt"); LOG.info("Emit classpath to " + classPathTxt); String cmd = getMvnCommand() + " dependency:build-classpath -Dmdep.outputFile=" + classPathTxt; File workingDirectory = pomXml.toAbsolutePath().getParent().toFile(); int result = Runtime.getRuntime().exec(cmd, null, workingDirectory).waitFor(); if (result != 0) throw new RuntimeException("`" + cmd + "` returned " + result); return readClassPathFile(classPathTxt); } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } } private static String getMvnCommand() { String mvnCommand = "mvn"; if (File.separatorChar == '\\') { mvnCommand = findExecutableOnPath("mvn.cmd"); if (mvnCommand == null) { mvnCommand = findExecutableOnPath("mvn.bat"); } } return mvnCommand; } private static String findExecutableOnPath(String name) { for (String dirname : System.getenv("PATH").split(File.pathSeparator)) { File file = new File(dirname, name); if (file.isFile() && file.canExecute()) { return file.getAbsolutePath(); } } return null; } private static Set<Path> sourceDirectories(Path pomXml) { try { Set<Path> all = new HashSet<>(); // Parse pom.xml DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(pomXml.toFile()); // Find source directory String sourceDir = XPathFactory.newInstance().newXPath().compile("/project/build/sourceDirectory").evaluate(doc); if (sourceDir == null || sourceDir.isEmpty()) { LOG.info("Use default source directory src/main/java"); sourceDir = "src/main/java"; } else LOG.info("Use source directory from pom.xml " + sourceDir); all.add(pomXml.resolveSibling(sourceDir).toAbsolutePath()); // Find test directory String testDir = XPathFactory.newInstance().newXPath().compile("/project/build/testSourceDirectory").evaluate(doc); if (testDir == null || testDir.isEmpty()) { LOG.info("Use default test directory src/test/java"); testDir = "src/test/java"; } else LOG.info("Use test directory from pom.xml " + testDir); all.add(pomXml.resolveSibling(testDir).toAbsolutePath()); return all; } catch (IOException | ParserConfigurationException | SAXException | XPathExpressionException e) { throw new RuntimeException(e); } } private JavaConfigJson readJavaConfigJson(Path configFile) { try { return JSON.readValue(configFile.toFile(), JavaConfigJson.class); } catch (IOException e) { MessageParams message = new MessageParams(); message.setMessage("Error reading " + configFile); message.setType(MessageType.Error); throw new ShowMessageException(message, e); } } private static Set<Path> readClassPathFile(Path classPathFilePath) { try { InputStream in = Files.newInputStream(classPathFilePath); String text = new BufferedReader(new InputStreamReader(in)) .lines() .collect(Collectors.joining()); Path dir = classPathFilePath.getParent(); return Arrays.stream(text.split(File.pathSeparator)) .map(dir::resolve) .collect(Collectors.toSet()); } catch (IOException e) { MessageParams message = new MessageParams(); message.setMessage("Error reading " + classPathFilePath); message.setType(MessageType.Error); throw new ShowMessageException(message, e); } } private Range position(javax.tools.Diagnostic<? extends JavaFileObject> error) { // Compute start position Position start = new Position(); start.setLine((int) (error.getLineNumber() - 1)); start.setCharacter((int) (error.getColumnNumber() - 1)); // Compute end position Position end = endPosition(error); // Combine into Range Range range = new Range(); range.setStart(start); range.setEnd(end); return range; } private Position endPosition(javax.tools.Diagnostic<? extends JavaFileObject> error) { try (Reader reader = error.getSource().openReader(true)) { long startOffset = error.getStartPosition(); long endOffset = error.getEndPosition(); reader.skip(startOffset); int line = (int) error.getLineNumber() - 1; int column = (int) error.getColumnNumber() - 1; for (long i = startOffset; i < endOffset; i++) { int next = reader.read(); if (next == '\n') { line++; column = 0; } else column++; } Position end = new Position(); end.setLine(line); end.setCharacter(column); return end; } catch (IOException e) { throw new UncheckedIOException(e); } } public Optional<Element> findSymbol(URI file, int line, int character) { Optional<String> content = activeContent(file); return findCompiler(file) .flatMap(compiler -> { FocusedResult result = compiler.compileFocused(file, content, line, character, false); Trees trees = Trees.instance(result.task); Function<TreePath, Optional<Element>> findSymbol = cursor -> Optional.ofNullable(trees.getElement(cursor)); return result.cursor.flatMap(findSymbol); }); } public void installClient(LanguageClient client) { this.client = client; Logger.getLogger("").addHandler(new Handler() { @Override public void publish(LogRecord record) { String message = record.getMessage(); if (record.getThrown() != null) { StringWriter trace = new StringWriter(); record.getThrown().printStackTrace(new PrintWriter(trace)); message += "\n" + trace; } client.logMessage(new MessageParams( messageType(record.getLevel().intValue()), message )); } private MessageType messageType(int level) { if (level >= Level.SEVERE.intValue()) return MessageType.Error; else if (level >= Level.WARNING.intValue()) return MessageType.Warning; else if (level >= Level.INFO.intValue()) return MessageType.Info; else return MessageType.Log; } @Override public void flush() { } @Override public void close() throws SecurityException { } }); } }
package com.sometrik.framework; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import com.sometrik.framework.NativeCommand.Selector; import android.graphics.Bitmap; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; public class FWImageView extends ImageView implements NativeCommandHandler { FrameWork frame; ViewStyleManager normalStyle, activeStyle, currentStyle; Bitmap ownedBitmap = null; boolean imageRequestSent = false; String currentUrl = null; int currentWidth = 0, currentHeight = 0; public FWImageView(final FrameWork frame, int id, String imageUrl) { super(frame); this.frame = frame; this.setId(id); this.setScaleType(ScaleType.CENTER_CROP); // needed for parallax scrolling this.setClipToOutline(true); this.setAdjustViewBounds(true); this.setClickable(true); if (imageUrl != null) { String protocol = getProtocol(imageUrl); if (protocol.equals("http") || protocol.equals("https")) { currentUrl = imageUrl; } else { setImageFromAssets(imageUrl); } } final float scale = getContext().getResources().getDisplayMetrics().density; this.normalStyle = currentStyle = new ViewStyleManager(frame.bitmapCache, scale, true); this.activeStyle = new ViewStyleManager(frame.bitmapCache, scale, false); final FWImageView image = this; setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (!FrameWork.transitionAnimation) { frame.intChangedEvent(getElementId(), 0, 0); } } }); setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { image.currentStyle = image.activeStyle; image.currentStyle.apply(image); } else if (event.getAction() == MotionEvent.ACTION_UP) { image.currentStyle = image.normalStyle; image.currentStyle.apply(image); } return false; } }); } private String getProtocol(String filename) { try { URI uri = new URI(filename); String scheme = uri.getScheme(); return scheme != null ? scheme : "asset"; } catch (URISyntaxException e) { return "asset"; } } private void setImageFromAssets(String filename) { deinitialize(); Bitmap bitmap = frame.bitmapCache.loadBitmap(filename); setImageBitmap(bitmap); invalidate(); } @Override public void onScreenOrientationChange(boolean isLandscape) { } @Override public void addChild(View view) { } @Override public void addOption(int optionId, String text) { } @Override public void addColumn(String text, int columnType) { } @Override public void addData(String text, int row, int column, int sheet) { } @Override public void setValue(String v) { deinitialize(); String protocol = getProtocol(v); if (protocol.equals("http") || protocol.equals("https")) { currentUrl = v; if (currentWidth != 0 && currentHeight != 0) requestImage(); } else { currentUrl = null; setImageFromAssets(v); } } @Override public void setValue(int v) { } @Override public void reshape(int value, int size) { } @Override public void setViewVisibility(boolean visible) { } @Override public void setStyle(Selector selector, String key, String value) { if (selector == Selector.NORMAL) { normalStyle.setStyle(key, value); if (normalStyle == currentStyle) normalStyle.apply(this); } else if (selector == Selector.ACTIVE) { activeStyle.setStyle(key, value); if (activeStyle == currentStyle) activeStyle.apply(this); } if (key.equals("scale")) { if (value.equals("fit-start")) { setScaleType(ScaleType.FIT_START); } else if (value.equals("fit-end")) { setScaleType(ScaleType.FIT_END); } else if (value.equals("fit-center")) { setScaleType(ScaleType.FIT_CENTER); } else if (value.equals("center")) { setScaleType(ScaleType.CENTER); } } } @Override public void setError(boolean hasError, String errorText) { } @Override public void clear() { } @Override public void flush() { } @Override public int getElementId() { return getId(); } private Bitmap createBitmap(int width, int height, int internalFormat) { switch (internalFormat) { case 3: return Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); case 4: return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444); case 5: case 6: return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); } System.out.println("ERROR: unable to display format " + internalFormat); return null; } @Override public void setImage(byte[] bytes, int width, int height, int internalFormat) { deinitialize(); ownedBitmap = createBitmap(width, height, internalFormat); if (ownedBitmap != null) { ByteBuffer buffer = ByteBuffer.wrap(bytes); ownedBitmap.copyPixelsFromBuffer(buffer); } this.setImageBitmap(ownedBitmap); invalidate(); activeStyle.apply(this); } @Override public void reshape(int size) { } @Override public void deinitialize() { if (ownedBitmap != null) { ownedBitmap.recycle(); ownedBitmap = null; } else if (imageRequestSent) { frame.cancelImageRequest(getElementId()); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { currentWidth = w; currentHeight = h; if (currentUrl != null) requestImage(); } protected void requestImage() { if (currentWidth > 0) { System.out.println("Sending image request for " + currentUrl); imageRequestSent = true; final float scale = getContext().getResources().getDisplayMetrics().density; frame.sendImageRequest(getElementId(), currentUrl, (int)(currentWidth / scale), 0); } else { System.out.println("Unable to sent image request for " + currentUrl); } } }
package org.kumoricon.model.user; import jdk.nashorn.internal.runtime.regexp.joni.exception.ValueException; import org.kumoricon.model.role.Role; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.math.BigInteger; @Entity @Table(name = "users") public class User implements Serializable { public static final String DEFAULT_PASSWORD = "password"; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @NotNull @Column(unique=true) private String username; @NotNull private String password; private String firstName; private String lastName; private String phone; @NotNull private Boolean enabled; @ManyToOne(cascade=CascadeType.MERGE) private Role role; private String salt; @NotNull private Integer lastBadgeNumberCreated; @NotNull private Integer sessionNumber; // Used for printing report when cashing out public User() { this.id = null; this.salt = "TempSalt"; // Todo: randomly generate salt this.enabled = true; this.lastBadgeNumberCreated = 1213; // Start at an arbitrary number instead of 0 this.sessionNumber = 1; } public User(String firstName, String lastName) { this(); setFirstName(firstName); setLastName(lastName); setPassword(DEFAULT_PASSWORD); setUsername(generateUserName(firstName, lastName)); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { if (username != null) { this.username = username.toLowerCase(); } } public String getPassword() { return password; } public void setPassword(String newPassword) { if (newPassword == null || newPassword.trim().equals("")) { throw new ValueException("Password cannot be blank"); } this.password = hashPassword(newPassword, salt); } public Boolean checkPassword(String password) { return (hashPassword(password, salt).equals(this.password)); } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Integer getLastBadgeNumberCreated() { return lastBadgeNumberCreated; } public void setLastBadgeNumberCreated(Integer lastBadgeNumberCreated) { this.lastBadgeNumberCreated = lastBadgeNumberCreated; } public Integer getNextBadgeNumber() { if (lastBadgeNumberCreated == null) { lastBadgeNumberCreated = 0; } return ++lastBadgeNumberCreated; } private static String hashPassword(String password, String salt){ char[] passwordChars = password.toCharArray(); byte[] saltBytes = salt.getBytes(); PBEKeySpec spec = new PBEKeySpec( passwordChars, saltBytes, 1000, 256); byte[] hashedPassword; try { SecretKeyFactory key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); hashedPassword = key.generateSecret(spec).getEncoded(); return String.format("%x", new BigInteger(hashedPassword)); } catch (Exception e) { System.out.println(e.getMessage()); } return null; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getSessionNumber() { return sessionNumber; } public void setSessionNumber(Integer sessionNumber) { this.sessionNumber = sessionNumber; } public static String generateUserName(String firstName, String lastName) { // Remove anything that isn't a letter and combine to first initial + last name // Doesn't do uniqueness checking String username; firstName = firstName.replaceAll("[^\\p{L}]", ""); if (firstName.length() > 0) { firstName = firstName.substring(0, 1); } lastName = lastName.replaceAll("[^\\p{L}]", ""); username = firstName + lastName; return username.toLowerCase(); } public String toString() { if (firstName != null && lastName != null) { return String.format("%s (%s %s)", username, firstName, lastName); } else { return username; } } @Override public boolean equals(Object other) { if (!(other instanceof User)) return false; if (this.getId() == null) { return this == other; } else { User o = (User) other; return this.getId().equals(o.getId()); } } @Override public int hashCode() { return getUsername().hashCode(); } public boolean hasRight(String right) { if (role == null) { return false; } else { return role.hasRight(right); } } }
package org.apache.commons.fileupload; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit tests {@link org.apache.commons.fileupload.FileUpload}. * * @author <a href="mailto:jmcnally@apache.org">John McNally</a> */ public class FileUploadTest extends TestCase { public FileUploadTest(String name) { super(name); } public void testParseRequest() { // todo - implement } }
package org.lantern; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Enumeration; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.lantern.event.Events; import org.lantern.event.PeerCertEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Charsets; import com.google.inject.Inject; import com.google.inject.Singleton; /** * This class manages the local trust store of external entities we trust * for creating SSL connections. This includes both hard coded certificates * for a small number of services we use as well as dynamically added * certificates for peers. Peer certificates must be discovered and added * through a trusted channel such as one of the hard coded trusted authorities * (aka Google Talk with its equifax certificate as of this writing). */ @Singleton public class LanternTrustStore { private final static Logger log = LoggerFactory.getLogger(LanternTrustStore.class); private final AtomicReference<SSLContext> sslContextRef = new AtomicReference<SSLContext>(); private final LanternKeyStoreManager ksm; private final KeyStore trustStore; private TrustManagerFactory tmf; @Inject public LanternTrustStore(final LanternKeyStoreManager ksm) { this.ksm = ksm; this.trustStore = blankTrustStore(); this.tmf = initTrustManagerFactory(); } /** * Every time the trust store changes, we need to recreate particularly * our SSL context because we now trust different servers. We reload only * on trust store changes as an optimization to avoid loading the whole * SSL context from scratch for each new outgoing socket. */ private void onTrustStoreChanged() { this.tmf = initTrustManagerFactory(); this.sslContextRef.set(provideSslContext()); } private TrustManagerFactory initTrustManagerFactory() { try { final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); // We create the trust manager factory with the latest trust store. trustManagerFactory.init(this.trustStore); return trustManagerFactory; } catch (final NoSuchAlgorithmException e) { log.error("Could not load algorithm?", e); throw new Error("Could not load algorithm", e); } catch (final KeyStoreException e) { log.error("Could not load keystore?", e); throw new Error("Could not load keystore for tmf", e); } } private KeyStore blankTrustStore() { try { final KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); final CertificateFactory cf = CertificateFactory.getInstance("X.509"); addCert(ks, cf, "littleproxy", LITTLEPROXY); addCert(ks, cf, "digicerthighassurancerootca", DIGICERT); addCert(ks, cf, "equifaxsecureca", EQUIFAX); return ks; } catch (final KeyStoreException e) { log.error("Could not load keystore?", e); throw new Error("Could not load blank trust store", e); } catch (final NoSuchAlgorithmException e) { log.error("No such algo?", e); throw new Error("Could not load blank trust store", e); } catch (final CertificateException e) { log.error("Bad cert?", e); throw new Error("Could not load blank trust store", e); } catch (final IOException e) { log.error("Could not load?", e); throw new Error("Could not load blank trust store", e); } } private void addCert(final KeyStore ks, final CertificateFactory cf, final String alias, final String pemCert) throws CertificateException, KeyStoreException { final InputStream bis = new ByteArrayInputStream(pemCert.getBytes(Charsets.UTF_8)); final Certificate cert = cf.generateCertificate(bis); ks.setCertificateEntry(alias, cert); } public void addBase64Cert(final URI jid, final String base64Cert) { log.debug("Adding base 64 cert for {} to trust store", jid); Events.asyncEventBus().post(new PeerCertEvent(jid, base64Cert)); final byte[] decoded = Base64.decodeBase64(base64Cert); final InputStream is = new ByteArrayInputStream(decoded); addCert(jid.toASCIIString(), is); } public void addCert(final String alias, final InputStream is) { log.debug("Importing cert"); try { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final Certificate certificate = cf.generateCertificate(is); this.trustStore.setCertificateEntry(alias, certificate); } catch (final CertificateException e) { log.error("Could not load cert - cert error?", e); } catch (final KeyStoreException e) { log.error("Could not load cert into keystore?", e); } finally { IOUtils.closeQuietly(is); } onTrustStoreChanged(); } /** * Accessor for the SSL context. This is regenerated whenever * we receive new certificates. * * @return The SSL context. */ public synchronized SSLContext getSslContext() { if (this.sslContextRef.get() == null) { this.sslContextRef.set(provideSslContext()); } return sslContextRef.get(); } private SSLContext provideSslContext() { try { final SSLContext context = SSLContext.getInstance("TLS"); // Create the context with the latest trust manager factory. context.init(this.ksm.getKeyManagerFactory().getKeyManagers(), this.tmf.getTrustManagers(), null); return context; } catch (final Exception e) { throw new Error( "Failed to initialize the client-side SSLContext", e); } } public void deleteCert(final String alias) { try { this.trustStore.deleteEntry(alias); onTrustStoreChanged(); } catch (final KeyStoreException e) { log.debug("Error removing entry -- doesn't exist?", e); } } /** * Checks if the trust store contains exactly this certificate. This * doesn't worry about certificate chaining or anything like that -- * this trust store must instead contain the actual certificate. * * @param cert The certificate to check. * @return <code>true</code> if the trust store contains the certificate, * otherwise <code>false</code>. */ public boolean containsCertificate(final X509Certificate cert) { log.debug("Loading trust store..."); // We could use getCertificateAlias here, but that will iterate through // everything, potentially causing issues when there are a lot of certs. final String alias = cert.getIssuerDN().getName().substring(3).toLowerCase(); log.debug("Looking for alias {}", alias); try { final Certificate existingCert = this.trustStore.getCertificate(alias); log.debug("Existing certificate: {}", (existingCert)); return existingCert != null && existingCert.equals(cert); } catch (final KeyStoreException e) { log.warn("Exception accessing keystore", e); return false; } } private void listEntries(final KeyStore ks) { try { final Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { final String alias = aliases.nextElement(); //System.err.println(alias+": "+ks.getCertificate(alias)); System.err.println(alias); log.debug(alias); } } catch (final KeyStoreException e) { log.warn("KeyStore error", e); } } public void listEntries() { listEntries(trustStore); } private static final String EQUIFAX = " + "MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJV\n" + "UzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2Vy\n" + "dGlmaWNhdGUgQXV0aG9yaXR5MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1\n" + "MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoTB0VxdWlmYXgxLTArBgNVBAsTJEVx\n" + "dWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCBnzANBgkqhkiG9w0B\n" + "AQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPRfM6f\n" + "BeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+A\n" + "cJkVV5MW8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kC\n" + "AwEAAaOCAQkwggEFMHAGA1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQ\n" + "MA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlm\n" + "aWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoGA1UdEAQTMBGBDzIwMTgw\n" + "ODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvSspXXR9gj\n" + "IBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQF\n" + "MAMBAf8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUA\n" + "A4GBAFjOKer89961zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y\n" + "7qj/WsjTVbJmcVfewCHrPSqnI0kBBIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh\n" + "1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee9570+sB3c4\n" + " private static final String DIGICERT = " + "MIIGWDCCBUCgAwIBAgIQCl8RTQNbF5EX0u/UA4w/OzANBgkqhkiG9w0BAQUFADBs\n" + "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" + "d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j\n" + "ZSBFViBSb290IENBMB4XDTA4MDQwMjEyMDAwMFoXDTIyMDQwMzAwMDAwMFowZjEL\n" + "MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3\n" + "LmRpZ2ljZXJ0LmNvbTElMCMGA1UEAxMcRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug\n" + "Q0EtMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9hCikQH17+NDdR\n" + "CPge+yLtYb4LDXBMUGMmdRW5QYiXtvCgFbsIYOBC6AUpEIc2iihlqO8xB3RtNpcv\n" + "KEZmBMcqeSZ6mdWOw21PoF6tvD2Rwll7XjZswFPPAAgyPhBkWBATaccM7pxCUQD5\n" + "BUTuJM56H+2MEb0SqPMV9Bx6MWkBG6fmXcCabH4JnudSREoQOiPkm7YDr6ictFuf\n" + "1EutkozOtREqqjcYjbTCuNhcBoz4/yO9NV7UfD5+gw6RlgWYw7If48hl66l7XaAs\n" + "zPw82W3tzPpLQ4zJ1LilYRyyQLYoEt+5+F/+07LJ7z20Hkt8HEyZNp496+ynaF4d\n" + "32duXvsCAwEAAaOCAvowggL2MA4GA1UdDwEB/wQEAwIBhjCCAcYGA1UdIASCAb0w\n" + "ggG5MIIBtQYLYIZIAYb9bAEDAAIwggGkMDoGCCsGAQUFBwIBFi5odHRwOi8vd3d3\n" + "LmRpZ2ljZXJ0LmNvbS9zc2wtY3BzLXJlcG9zaXRvcnkuaHRtMIIBZAYIKwYBBQUH\n" + "AgIwggFWHoIBUgBBAG4AeQAgAHUAcwBlACAAbwBmACAAdABoAGkAcwAgAEMAZQBy\n" + "AHQAaQBmAGkAYwBhAHQAZQAgAGMAbwBuAHMAdABpAHQAdQB0AGUAcwAgAGEAYwBj\n" + "AGUAcAB0AGEAbgBjAGUAIABvAGYAIAB0AGgAZQAgAEQAaQBnAGkAQwBlAHIAdAAg\n" + "AEMAUAAvAEMAUABTACAAYQBuAGQAIAB0AGgAZQAgAFIAZQBsAHkAaQBuAGcAIABQ\n" + "AGEAcgB0AHkAIABBAGcAcgBlAGUAbQBlAG4AdAAgAHcAaABpAGMAaAAgAGwAaQBt\n" + "AGkAdAAgAGwAaQBhAGIAaQBsAGkAdAB5ACAAYQBuAGQAIABhAHIAZQAgAGkAbgBj\n" + "AG8AcgBwAG8AcgBhAHQAZQBkACAAaABlAHIAZQBpAG4AIABiAHkAIAByAGUAZgBl\n" + "AHIAZQBuAGMAZQAuMBIGA1UdEwEB/wQIMAYBAf8CAQAwNAYIKwYBBQUHAQEEKDAm\n" + "MCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wgY8GA1UdHwSB\n" + "hzCBhDBAoD6gPIY6aHR0cDovL2NybDMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0SGln\n" + "aEFzc3VyYW5jZUVWUm9vdENBLmNybDBAoD6gPIY6aHR0cDovL2NybDQuZGlnaWNl\n" + "cnQuY29tL0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZUVWUm9vdENBLmNybDAfBgNVHSME\n" + "GDAWgBSxPsNpA/i/RwHUmCYaCALvY2QrwzAdBgNVHQ4EFgQUUOpzidsp+xCPnuUB\n" + "INTeeZlIg/cwDQYJKoZIhvcNAQEFBQADggEBAB7ipUiebNtTOA/vphoqrOIDQ+2a\n" + "vD6OdRvw/S4iWawTwGHi5/rpmc2HCXVUKL9GYNy+USyS8xuRfDEIcOI3ucFbqL2j\n" + "CwD7GhX9A61YasXHJJlIR0YxHpLvtF9ONMeQvzHB+LGEhtCcAarfilYGzjrpDq6X\n" + "dF3XcZpCdF/ejUN83ulV7WkAywXgemFhM9EZTfkI7qA5xSU1tyvED7Ld8aW3DiTE\n" + "JiiNeXf1L/BXunwH1OH8zVowV36GEEfdMR/X/KLCvzB8XSSq6PmuX2p0ws5rs0bY\n" + "Ib4p1I5eFdZCSucyb6Sxa1GDWL4/bcf72gMhy2oWGU4K8K2Eyl2Us1p292E=\n" + " private static final String LITTLEPROXY = " + "MIIEqjCCApKgAwIBAgIETSOp+zANBgkqhkiG9w0BAQUFADAWMRQwEgYDVQQDEwts\n" + "aXR0bGVwcm94eTAgFw0xMTAxMDQyMzE1MDdaGA8yMTEwMTIxMTIzMTUwN1owFjEU\n" + "MBIGA1UEAxMLbGl0dGxlcHJveHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK\n" + "AoICAQCm4Ulsi69ZqgeSf+aVDFlVMkMWzYKomTcDFCX9rpys+nKiLpKbzXKruBUM\n" + "Ud9BSG1I3eiJ9jJP77f5DpW0z2bptOHSRi0a9GOpx6I8AjKBvKH2CtV8cnGsopN8\n" + "JMMop6tZ7hVRo3M0BmGh9SgAQaX46nVIwcA3oUSLQKEqAsw8WVmbYJhwNWpPAl5M\n" + "0BT/ElEKG2LPaB0ha+8mFeT3haq4Jeuxeb5MfnpuEnLQ4FTre27f7bO3r/QaxVpu\n" + "UHF6MyMjoQCcjUO99Fo6a0poo6XX7ys9jnPEl44Pt36ygced2S3U4ZtchWWf634B\n" + "Wh5jmHtrcdOo94emzHGdah+XnTJI5BYUyNgNeI/8D3OyTlVWxUDU4f/9XqxVtc1F\n" + "KjMe33eT6kL2s5GWaT+1R9dJ4TCFizPQrWrwu2IDbyDj2sJGdSrjj+w2kHQ/V17q\n" + "AD2TmDlMmIvrqRc1lptBhcSpdTp5EoZEvgwTyRM7jpwDj5rAUXV8eu/93NcImJY2\n" + "QkGxAamB2vFWwxxYShKUqyG1zxyIF1cvWnAywgZuE4t5TGiZ9AIor5XkNDcaE0pj\n" + "6yJtblOFhSKiJgSUR49dl0D39fzy++gkkWmjgUuRTMglx0wAFPxFa/TGhfK0Ukze\n" + "WpJxoWHR06+EPN0kj/nagk5q4Ovz8EOZratTwToCEi9Doe5N8wIDAQABMA0GCSqG\n" + "SIb3DQEBBQUAA4ICAQBiLlzTzBfFsvtfz6ll8mU8jptS6A3YV7Zldon25I/xQlik\n" + "72hS25+s2U3mzcIz1kkdSYhyTa8B1JhXygnUYkJV+AShP5+tlcYXWq1YMx9GrKC2\n" + "SEOrsmt2tHLJS03oyCZfYcKdoJMRoTXnKe8WDs7M4iFSXGeaFn1SePbdjNMGHCVT\n" + "Cr58PhCxigXushNAVy5GZFh0gcFeMIYJIUqJADbw4IyicXpcUdQJHs7DkvXxquXZ\n" + "rNv2NKWlqQI2iwn2Aow8V0c7mud/kGdzLFM18NZVfZQsWWBWXP3CxUPGGrfaxiCH\n" + "aLo1i9KnD6yEw9x/0mcajy3VN4y8QdJpgPhGDQXMMvqDWIEouy05sES4V0GVTksQ\n" + "42SscqVWyT0HNRgmvOQHEc9Oh9mkCuspEzSA+LH1CGYc+dSTUTZUO+MmcfMDYpj4\n" + "NkLH/AgVwKPiFyD5MUYi7isLJnfpkmZcgJOL/FXtGmLeD8nt8eRPRS4YZMLDtd/9\n" + "FVo6KC1mlaiosLys7wUBuu15HdyJrkD+k4ZNrkx/oMlcLOgPdz2Qkue3Rqa9DRuX\n" + "jwwv90xVufuOJ5mYcQ2VA80x8YT+XTq194BGSqYAAU8Rq1/5fAMg5cwhg4BDjmY2\n" + "ok2U3fCl58xbiwp6owpamVoPblrq7Zl4ylyF33H6ewM+f5XA+L1iC5KWs9q8Kw==\n" + " }
package org.openflow.protocol; import java.nio.ByteBuffer; import java.util.List; import java.util.LinkedList; import java.util.ArrayList; import org.openflow.util.HexString; import org.openflow.util.U16; import org.openflow.util.U32; /** * Represents an ofp_match structure * * @author Srini Seetharaman (srini.seetharaman@gmail.com) * */ public class OFMatch implements Cloneable { public static int MINIMUM_LENGTH = 8; public static final short ETH_TYPE_IPV4 = (short)0x800; public static final short ETH_TYPE_IPV6 = (short)0x86dd; public static final short ETH_TYPE_ARP = (short)0x806; public static final short ETH_TYPE_VLAN = (short)0x8100; public static final short ETH_TYPE_LLDP = (short)0x88cc; public static final short ETH_TYPE_MPLS_UNICAST = (short)0x8847; public static final short ETH_TYPE_MPLS_MULTICAST = (short)0x8848; public static final byte IP_PROTO_ICMP = 0x1; public static final byte IP_PROTO_TCP = 0x6; public static final byte IP_PROTO_UDP = 0x11; public static final byte IP_PROTO_SCTP = (byte)0x84; enum OFMatchType { STANDARD, OXM } // Note: Only supporting OXM and OpenFlow_Basic matches public enum OFMatchClass { NXM_0 ((short)0x0000), NXM_1 ((short)0x0001), OPENFLOW_BASIC ((short)0x8000), VENDOR ((short)0xffff); protected short value; private OFMatchClass(short value) { this.value = value; } /** * @return the value */ public short getValue() { return value; } } protected OFMatchType type; protected short length; protected short matchLength; protected List<OFMatchField> matchFields; /** * By default, create a OFMatch that matches everything * (mostly because it's the least amount of work to make a valid OFMatch) */ public OFMatch() { this.type = OFMatchType.OXM; this.length = U16.t(MINIMUM_LENGTH); this.matchLength = 4; //No padding this.matchFields = new ArrayList<OFMatchField>(); } /** * Get value of particular field * @return */ public Object getMatchFieldValue(OFOXMFieldType matchType) { for (OFMatchField matchField: matchFields) { if (matchField.getOXMFieldType() == matchType) return matchField.getOXMFieldValue(); } throw new IllegalArgumentException("No match exists for matchfield " + matchType.getFieldName()); } /** * Get mask of particular field * @return */ public Object getMatchFieldMask(OFOXMFieldType matchType) { for (OFMatchField matchField: matchFields) { if (matchField.getOXMFieldType() == matchType) return matchField.getOXMFieldMask(); } throw new IllegalArgumentException("No match exists for matchfield " + matchType.getFieldName()); } /** * Get in_port * @return integer */ public int getInPort() { return (Integer)getMatchFieldValue(OFOXMFieldType.IN_PORT); } /** * Set in_port in match * @param in_port */ public OFMatch setInPort(int inPort) { this.setField(OFOXMFieldType.IN_PORT, inPort); return this; } /** * Get dl_dst * * @return an arrays of bytes */ public byte[] getDataLayerDestination() { return (byte[])getMatchFieldValue(OFOXMFieldType.ETH_DST); } /** * Set dl_dst * * @param dataLayerDestination */ public OFMatch setDataLayerDestination(byte[] dataLayerDestination) { this.setField(OFOXMFieldType.ETH_DST, dataLayerDestination); return this; } /** * Set dl_dst, but first translate to byte[] using HexString * * @param mac * A colon separated string of 6 pairs of octets, e..g., * "00:17:42:EF:CD:8D" */ public OFMatch setDataLayerDestination(String mac) { byte bytes[] = HexString.fromHexString(mac); if (bytes.length != OFPhysicalPort.OFP_ETH_ALEN) throw new IllegalArgumentException("expected string with 6 octets, got '" + mac + "'"); this.setField(OFOXMFieldType.ETH_DST, bytes); return this; } /** * Get dl_src * * @return an array of bytes */ public byte[] getDataLayerSource() { return (byte[])getMatchFieldValue(OFOXMFieldType.ETH_SRC); } /** * Set dl_src * * @param dataLayerSource */ public OFMatch setDataLayerSource(byte[] dataLayerSource) { this.setField(OFOXMFieldType.ETH_SRC, dataLayerSource); return this; } /** * Set dl_src, but first translate to byte[] using HexString * * @param mac * A colon separated string of 6 pairs of octets, e..g., * "00:17:42:EF:CD:8D" */ public OFMatch setDataLayerSource(String mac) { byte bytes[] = HexString.fromHexString(mac); if (bytes.length != OFPhysicalPort.OFP_ETH_ALEN) throw new IllegalArgumentException("expected string with 6 octets, got '" + mac + "'"); this.setField(OFOXMFieldType.ETH_SRC, bytes); return this; } /** * Get dl_type * * @return ether_type */ public short getDataLayerType() { return (Short)getMatchFieldValue(OFOXMFieldType.ETH_TYPE); } /** * Set dl_type * * @param dataLayerType */ public OFMatch setDataLayerType(short dataLayerType) { this.setField(OFOXMFieldType.ETH_TYPE, dataLayerType); return this; } /** * Get dl_vlan * * @return vlan tag without the VLAN present bit set */ public short getDataLayerVirtualLan() { try { return (short)((Short)getMatchFieldValue(OFOXMFieldType.VLAN_VID) & 0xFFF); } catch (IllegalArgumentException e) { return OFVlanId.OFPVID_NONE.getValue(); } } /** * Set dl_vlan * * @param dataLayerVirtualLan VLAN ID without the VLAN present bit set */ public OFMatch setDataLayerVirtualLan(short vlan) { this.setField(OFOXMFieldType.VLAN_VID, vlan | OFVlanId.OFPVID_PRESENT.getValue()); return this; } /** * Get dl_vlan_pcp * * @return VLAN PCP value */ public byte getDataLayerVirtualLanPriorityCodePoint() { try { return (Byte) getMatchFieldValue(OFOXMFieldType.VLAN_PCP); } catch (IllegalArgumentException e) { return 0; } } /** * Set dl_vlan_pcp * * @param pcp */ public OFMatch setDataLayerVirtualLanPriorityCodePoint(byte pcp) { this.setField(OFOXMFieldType.VLAN_VID, pcp); return this; } /** * Get nw_proto * * @return */ public byte getNetworkProtocol() { return (Byte)getMatchFieldValue(OFOXMFieldType.IP_PROTO); } /** * Set nw_proto * * @param networkProtocol */ public OFMatch setNetworkProtocol(byte networkProtocol) { this.setField(OFOXMFieldType.IP_PROTO, networkProtocol); return this; } /** * Get nw_tos OFMatch stores the ToS bits as 6-bits in the lower significant bits * * @return : 6-bit DSCP value (0-63) */ public byte getNetworkTypeOfService() { try { return (byte)((Byte)getMatchFieldValue(OFOXMFieldType.IP_DSCP) & 0x3f); } catch (IllegalArgumentException e) { return 0; } } /** * Set nw_tos OFMatch stores the ToS bits as lower 6-bits * * @param networkTypeOfService TOS value including ECN in the lower 2 bits * : 6-bit DSCP value (0-63) */ public OFMatch setNetworkTypeOfService(byte networkTypeOfService) { this.setField(OFOXMFieldType.IP_DSCP, (byte)((networkTypeOfService >> 2) & 0x3f)); this.setField(OFOXMFieldType.IP_ECN, (byte)(networkTypeOfService & 0x3)); return this; } /** * Get nw_dst * * @return integer destination IP address */ public int getNetworkDestination() { return (Integer)getMatchFieldValue(OFOXMFieldType.IPV4_DST); } /** * Get nw_dst mask * * @return integer destination IP address mask */ public int getNetworkDestinationMask() { Object mask = getMatchFieldMask(OFOXMFieldType.IPV4_DST); if (mask == null) return 0; else return (Integer)mask; } /** * Set nw_dst * * @param networkDestination destination IP address */ public OFMatch setNetworkDestination(int networkDestination) { setNetworkDestination(ETH_TYPE_IPV4, networkDestination); return this; } /** * Set nw_dst * * @param dataLayerType ether type * @param networkDestination destination IP address */ public OFMatch setNetworkDestination(short dataLayerType, int networkDestination) { switch (dataLayerType) { case ETH_TYPE_IPV4: this.setField(OFOXMFieldType.IPV4_DST, networkDestination); break; case ETH_TYPE_IPV6: this.setField(OFOXMFieldType.IPV6_DST, networkDestination); break; case ETH_TYPE_ARP: this.setField(OFOXMFieldType.ARP_THA, networkDestination); break; } return this; } /** * Get nw_src * * @return integer source IP address */ // TODO: Add support for IPv6 public int getNetworkSource() { return (Integer)getMatchFieldValue(OFOXMFieldType.IPV4_SRC); } /** * Get nw_src mask * * @return integer source IP address mask */ public int getNetworkSourceMask() { Object mask = getMatchFieldMask(OFOXMFieldType.IPV4_SRC); if (mask == null) return 0; else return (Integer)mask; } /** * Set nw_src * * @param networkSource source IP address */ // TODO: Add support for IPv6 public OFMatch setNetworkSource(int networkSource) { setNetworkSource(ETH_TYPE_IPV4, networkSource); return this; } /** * Set nw_src * * @param dataLayerType ether type * @param networkSource source IP address */ // TODO: Add support for IPv6 public OFMatch setNetworkSource(short dataLayerType, int networkSource) { switch (dataLayerType) { case ETH_TYPE_IPV4: this.setField(OFOXMFieldType.IPV4_SRC, networkSource); break; case ETH_TYPE_ARP: this.setField(OFOXMFieldType.ARP_SHA, networkSource); break; } return this; } /** * Get tp_dst * * @return destination port number */ public short getTransportDestination() { byte networkProtocol = getNetworkProtocol(); switch (networkProtocol) { case IP_PROTO_TCP: return (Short)getMatchFieldValue(OFOXMFieldType.TCP_DST); case IP_PROTO_UDP: return (Short)getMatchFieldValue(OFOXMFieldType.UDP_DST); case IP_PROTO_SCTP: return (Short)getMatchFieldValue(OFOXMFieldType.SCTP_DST); } throw new IllegalArgumentException("Network Protocol invalid for extracting port number"); } /** * Set tp_dst * * @param transportDestination TCP destination port number */ public OFMatch setTransportDestination(short transportDestination) { setTransportSource(IP_PROTO_TCP, transportDestination); return this; } /** * Set tp_dst * * @param networkProtocol IP protocol * @param transportDestination Destination Transport port number */ public OFMatch setTransportDestination(byte networkProtocol, short transportDestination) { switch (networkProtocol) { case IP_PROTO_TCP: this.setField(OFOXMFieldType.TCP_DST, transportDestination); break; case IP_PROTO_UDP: this.setField(OFOXMFieldType.UDP_DST, transportDestination); break; case IP_PROTO_SCTP: this.setField(OFOXMFieldType.SCTP_DST, transportDestination); break; } return this; } /** * Get tp_src * * @return transportSource Source Transport port number */ public short getTransportSource() { byte networkProtocol = getNetworkProtocol(); switch (networkProtocol) { case IP_PROTO_TCP: return (Short)getMatchFieldValue(OFOXMFieldType.TCP_SRC); case IP_PROTO_UDP: return (Short)getMatchFieldValue(OFOXMFieldType.UDP_SRC); case IP_PROTO_SCTP: return (Short)getMatchFieldValue(OFOXMFieldType.SCTP_SRC); } throw new IllegalArgumentException("Network Protocol invalid for extracting port number"); } /** * Set tp_src * * @param transportSource TCP source port number */ public OFMatch setTransportSource(short transportSource) { setTransportSource(IP_PROTO_TCP, transportSource); return this; } /** * Set tp_src * * @param networkProtocol IP protocol * @param transportSource Source Transport port number */ public OFMatch setTransportSource(byte networkProtocol, short transportSource) { switch (networkProtocol) { case IP_PROTO_TCP: this.setField(OFOXMFieldType.TCP_SRC, transportSource); break; case IP_PROTO_UDP: this.setField(OFOXMFieldType.UDP_SRC, transportSource); break; case IP_PROTO_SCTP: this.setField(OFOXMFieldType.SCTP_SRC, transportSource); break; } return this; } public OFMatchType getType() { return type; } /** * Get the length of this message * @return length */ public short getLength() { return length; } /** * Get the length of this message, unsigned * @return unsigned length */ public int getLengthU() { return U16.f(length); } public short getMatchLength() { return matchLength; } /** Sets match field. In case of existing field, checks for existing value * * @param matchField Check for uniqueness of field and add matchField */ public void setField(OFMatchField newMatchField) { if (this.matchFields == null) this.matchFields = new ArrayList<OFMatchField>(); for (OFMatchField matchField: this.matchFields) { if (matchField.getOXMFieldType() == newMatchField.getOXMFieldType()) { matchField.setOXMFieldValue(newMatchField.getOXMFieldValue()); matchField.setOXMFieldMask(newMatchField.getOXMFieldMask()); return; } } this.matchFields.add(newMatchField); this.matchLength += newMatchField.getOXMFieldLength(); this.length = U16.t(8*((this.matchLength + 4 + 7)/8)); //includes padding } public void setField(OFOXMFieldType matchFieldType, Object matchFieldValue) { OFMatchField matchField = new OFMatchField(matchFieldType, matchFieldValue); setField(matchField); } public void setField(OFOXMFieldType matchFieldType, Object matchFieldValue, Object matchFieldMask) { OFMatchField matchField = new OFMatchField(matchFieldType, matchFieldValue, matchFieldMask); setField(matchField); } /** * Returns read-only copies of the matchfields contained in this OFMatch * @return a list of ordered OFMatchField objects */ public List<OFMatchField> getMatchFields() { return this.matchFields; } /** * Sets the list of matchfields this OFMatch contains * @param matchFields a list of ordered OFMatchField objects */ public OFMatch setMatchFields(List<OFMatchField> matchFields) { this.matchFields = matchFields; return this; } /** * Utility function to wildcard all fields except specified in list * @param nonWildcardedFieldTypes list of match field types preserved, * if null all fields are wildcarded */ public OFMatch wildcardAllExceptGiven(List<OFOXMFieldType> nonWildcardedFieldTypes) { List <OFMatchField> newMatchFields = new ArrayList<OFMatchField>(); if (nonWildcardedFieldTypes != null) { for (OFMatchField matchField: matchFields) { OFOXMFieldType type = matchField.getOXMFieldType(); if (nonWildcardedFieldTypes.contains(type)) newMatchFields.add(matchField); } } setMatchFields(newMatchFields); return this; } public void readFrom(ByteBuffer data) { byte[] dataLayerAddress = new byte[OFPhysicalPort.OFP_ETH_ALEN]; byte[] dataLayerAddressMask = new byte[OFPhysicalPort.OFP_ETH_ALEN]; int networkAddress; int networkAddressMask; int wildcards; short dataLayerType = 0; byte networkProtocol = 0; byte networkTOS; short transportNumber; int mplsLabel; byte mplsTC; this.type = OFMatchType.values()[data.getShort()]; this.length = data.getShort(); int remaining = this.getLengthU() - 4; //length - sizeof(type and length) int end = data.position() + remaining; //includes padding in case of STANDARD match if (type == OFMatchType.OXM) { int padLength = 8*((length + 7)/8) - length; end += padLength; // including pad if (data.remaining() < remaining) remaining = data.remaining(); this.matchFields = new ArrayList<OFMatchField>(); while (remaining >= OFMatchField.MINIMUM_LENGTH) { OFMatchField matchField = new OFMatchField(); matchField.readFrom(data); this.matchFields.add(matchField); remaining -= U32.f(matchField.getOXMFieldLength()+4); //value length + header length } } else { this.setField(OFOXMFieldType.IN_PORT, data.getInt()); wildcards = data.getInt(); if ((wildcards & OFMatchWildcardMask.ALL.getValue()) == 0) { data.position(end); return; } data.get(dataLayerAddress); data.get(dataLayerAddressMask); this.setField(OFOXMFieldType.ETH_SRC, dataLayerAddress.clone(), dataLayerAddressMask.clone()); data.get(dataLayerAddress); data.get(dataLayerAddressMask); this.setField(OFOXMFieldType.ETH_DST, dataLayerAddress.clone(), dataLayerAddressMask.clone()); if ((wildcards & OFMatchWildcardMask.DL_VLAN.getValue()) == 0) setDataLayerVirtualLan(data.getShort()); else data.getShort(); //skip if ((wildcards & OFMatchWildcardMask.DL_VLAN_PCP.getValue()) == 0) setDataLayerVirtualLanPriorityCodePoint(data.get()); else data.get(); //skip data.get(); //pad if ((wildcards & OFMatchWildcardMask.DL_TYPE.getValue()) == 0) { dataLayerType = data.getShort(); setDataLayerType(dataLayerType); } else data.getShort(); //skip if ((dataLayerType != ETH_TYPE_IPV4) && (dataLayerType != ETH_TYPE_ARP) && (dataLayerType != ETH_TYPE_VLAN) && (dataLayerType != ETH_TYPE_MPLS_UNICAST) && (dataLayerType != ETH_TYPE_MPLS_MULTICAST)) { data.position(end); return; } if ((wildcards & OFMatchWildcardMask.NW_TOS.getValue()) == 0) { networkTOS = data.get(); setNetworkTypeOfService(networkTOS); } else data.get(); //skip if ((wildcards & OFMatchWildcardMask.NW_PROTO.getValue()) == 0) { networkProtocol = data.get(); setNetworkProtocol(networkProtocol); } else data.get(); //skip networkAddress = data.getInt(); networkAddressMask = data.getInt(); if (networkAddress != 0) this.setField(OFOXMFieldType.IPV4_SRC, networkAddress, networkAddressMask); networkAddress = data.getInt(); networkAddressMask = data.getInt(); if (networkAddress != 0) this.setField(OFOXMFieldType.IPV4_DST, networkAddress, networkAddressMask); transportNumber = data.getShort(); if ((wildcards & OFMatchWildcardMask.TP_SRC.getValue()) == 0) { setTransportSource(networkProtocol, transportNumber); } transportNumber = data.getShort(); if ((wildcards & OFMatchWildcardMask.TP_DST.getValue()) == 0) { setTransportDestination(networkProtocol, transportNumber); } mplsLabel = data.getInt(); mplsTC = data.get(); if ((dataLayerType == ETH_TYPE_MPLS_UNICAST) || (dataLayerType == ETH_TYPE_MPLS_MULTICAST)) { if ((wildcards & OFMatchWildcardMask.MPLS_LABEL.getValue()) == 0) this.setField(OFOXMFieldType.MPLS_LABEL, mplsLabel); if ((wildcards & OFMatchWildcardMask.MPLS_TC.getValue()) == 0) this.setField(OFOXMFieldType.MPLS_TC, mplsTC); } data.get(); //pad data.get(); //pad data.get(); //pad this.setField(OFOXMFieldType.METADATA, data.getLong(), data.getLong()); } data.position(end); } public void writeTo(ByteBuffer data) { short matchLength = getMatchLength(); data.putShort((short)this.type.ordinal()); data.putShort(matchLength); //length does not include padding for (OFMatchField matchField : matchFields) matchField.writeTo(data); int padLength = 8*((matchLength + 7)/8) - matchLength; for (;padLength>0;padLength data.put((byte)0); //pad } public int hashCode() { final int prime = 227; int result = 1; result = prime * result + ((matchFields == null) ? 0 : matchFields.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof OFMatchField)) { return false; } OFMatch other = (OFMatch) obj; if (matchFields == null) { if (other.matchFields != null) return false; } else if (!matchFields.equals(other.matchFields)) { return false; } return true; } /* (non-Javadoc) * @see java.lang.Object#clone() */ @Override public OFMatch clone() { OFMatch match = new OFMatch(); try { List<OFMatchField> neoMatchFields = new LinkedList<OFMatchField>(); for(OFMatchField matchField: this.matchFields) neoMatchFields.add((OFMatchField) matchField.clone()); match.setMatchFields(neoMatchFields); return match; } catch (CloneNotSupportedException e) { // Won't happen throw new RuntimeException(e); } } /** * Load and return a new OFMatch based on supplied packetData, see * {@link #loadFromPacket(byte[], short)} for details. * * @param packetData * @param inputPort * @return */ public static OFMatch load(byte[] packetData, int inPort) { OFMatch ofm = new OFMatch(); return ofm.loadFromPacket(packetData, inPort); } /** * Initializes this OFMatch structure with the corresponding data from the * specified packet. * * Must specify the input port, to ensure that this.in_port is set * correctly. * * Specify OFPort.NONE or OFPort.ANY if input port not applicable or * available * * @param packetData * The packet's data * @param inputPort * the port the packet arrived on */ public OFMatch loadFromPacket(byte[] packetData, int inPort) { short scratch; byte[] dataLayerAddress = new byte[OFPhysicalPort.OFP_ETH_ALEN]; short dataLayerType = 0; byte networkProtocol = 0; int transportOffset = 34; ByteBuffer packetDataBB = ByteBuffer.wrap(packetData); int limit = packetDataBB.limit(); setInPort(inPort); //TODO: Extend to support more packet types assert (limit >= 14); // dl dst packetDataBB.get(dataLayerAddress); setDataLayerDestination(dataLayerAddress.clone()); // dl src packetDataBB.get(dataLayerAddress); setDataLayerSource(dataLayerAddress.clone()); // dl type dataLayerType = packetDataBB.getShort(); setDataLayerType(dataLayerType); if (dataLayerType == (short) ETH_TYPE_VLAN) { // need cast to avoid signed // has vlan tag scratch = packetDataBB.getShort(); setDataLayerVirtualLan((short) (0xfff & scratch)); setDataLayerVirtualLanPriorityCodePoint((byte) ((0xe000 & scratch) >> 13)); dataLayerType = packetDataBB.getShort(); } //TODO: Add support for IPv6 switch (dataLayerType) { case ETH_TYPE_IPV4: // ipv4 // check packet length scratch = packetDataBB.get(); scratch = (short) (0xf & scratch); transportOffset = (packetDataBB.position() - 1) + (scratch * 4); // nw tos (dscp and ecn) setNetworkTypeOfService(packetDataBB.get()); // nw protocol packetDataBB.position(packetDataBB.position() + 7); networkProtocol = packetDataBB.get(); setNetworkProtocol(networkProtocol); // nw src packetDataBB.position(packetDataBB.position() + 2); setNetworkSource(dataLayerType, packetDataBB.getInt()); // nw dst setNetworkDestination(dataLayerType, packetDataBB.getInt()); packetDataBB.position(transportOffset); break; case ETH_TYPE_ARP: // arp int arpPos = packetDataBB.position(); // opcode scratch = packetDataBB.getShort(arpPos + 6); this.setField(OFOXMFieldType.ARP_OP, ((short) (0xff & scratch))); scratch = packetDataBB.getShort(arpPos + 2); // if ipv4 and addr len is 4 if (scratch == 0x800 && packetDataBB.get(arpPos + 5) == 4) { // nw src this.setField(OFOXMFieldType.ARP_SPA, packetDataBB.getInt(arpPos + 14)); // nw dst this.setField(OFOXMFieldType.ARP_TPA, packetDataBB.getInt(arpPos + 24)); } return this; default: //No OXM field added return this; } switch (networkProtocol) { case IP_PROTO_ICMP: // icmp type this.setField(OFOXMFieldType.ICMPV4_TYPE, packetDataBB.get()); // code this.setField(OFOXMFieldType.ICMPV4_CODE, packetDataBB.get()); break; case IP_PROTO_TCP: case IP_PROTO_UDP: case IP_PROTO_SCTP: setTransportSource(networkProtocol, packetDataBB.getShort()); setTransportDestination(networkProtocol, packetDataBB.getShort()); break; default: break; } return this; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "OFMatch [type=" + type + "length=" + length + "matchFields=" + matchFields + "]"; } }
package org.openflow.protocol; import java.nio.ByteBuffer; import java.util.List; import java.util.LinkedList; import java.util.ArrayList; import org.openflow.util.HexString; import org.openflow.util.U16; import org.openflow.util.U32; /** * Represents an ofp_match structure * * @author Srini Seetharaman (srini.seetharaman@gmail.com) * */ public class OFMatch implements Cloneable { public static int MINIMUM_LENGTH = 8; public static final short ETH_TYPE_IPV4 = (short)0x800; public static final short ETH_TYPE_IPV6 = (short)0x86dd; public static final short ETH_TYPE_ARP = (short)0x806; public static final short ETH_TYPE_VLAN = (short)0x8100; public static final short ETH_TYPE_LLDP = (short)0x88cc; public static final short ETH_TYPE_MPLS_UNICAST = (short)0x8847; public static final short ETH_TYPE_MPLS_MULTICAST = (short)0x8848; public static final byte IP_PROTO_ICMP = 0x1; public static final byte IP_PROTO_TCP = 0x6; public static final byte IP_PROTO_UDP = 0x11; public static final byte IP_PROTO_SCTP = (byte)0x84; enum OFMatchType { STANDARD, OXM } // Note: Only supporting OXM and OpenFlow_Basic matches public enum OFMatchClass { NXM_0 ((short)0x0000), NXM_1 ((short)0x0001), OPENFLOW_BASIC ((short)0x8000), VENDOR ((short)0xffff); protected short value; private OFMatchClass(short value) { this.value = value; } /** * @return the value */ public short getValue() { return value; } } protected OFMatchType type; protected short length; protected short matchLength; protected List<OFMatchField> matchFields; /** * By default, create a OFMatch that matches everything * (mostly because it's the least amount of work to make a valid OFMatch) */ public OFMatch() { this.type = OFMatchType.OXM; this.length = U16.t(MINIMUM_LENGTH); this.matchLength = 4; //No padding this.matchFields = new ArrayList<OFMatchField>(); } /** * Get value of particular field * @return */ public Object getMatchFieldValue(OFOXMFieldType matchType) { for (OFMatchField matchField: matchFields) { if (matchField.getOXMFieldType() == matchType) return matchField.getOXMFieldValue(); } throw new IllegalArgumentException("No match exists for matchfield " + matchType.getFieldName()); } /** * Get mask of particular field * @return */ public Object getMatchFieldMask(OFOXMFieldType matchType) { for (OFMatchField matchField: matchFields) { if (matchField.getOXMFieldType() == matchType) return matchField.getOXMFieldMask(); } throw new IllegalArgumentException("No match exists for matchfield " + matchType.getFieldName()); } /** * Get in_port * @return integer */ public int getInPort() { return (Integer)getMatchFieldValue(OFOXMFieldType.IN_PORT); } /** * Set in_port in match * @param in_port */ public void setInPort(int inPort) { this.setField(OFOXMFieldType.IN_PORT, inPort); } /** * Get dl_dst * * @return an arrays of bytes */ public byte[] getDataLayerDestination() { return (byte[])getMatchFieldValue(OFOXMFieldType.ETH_DST); } /** * Set dl_dst * * @param dataLayerDestination */ public OFMatch setDataLayerDestination(byte[] dataLayerDestination) { this.setField(OFOXMFieldType.ETH_DST, dataLayerDestination); return this; } /** * Set dl_dst, but first translate to byte[] using HexString * * @param mac * A colon separated string of 6 pairs of octets, e..g., * "00:17:42:EF:CD:8D" */ public OFMatch setDataLayerDestination(String mac) { byte bytes[] = HexString.fromHexString(mac); if (bytes.length != OFPhysicalPort.OFP_ETH_ALEN) throw new IllegalArgumentException("expected string with 6 octets, got '" + mac + "'"); this.setField(OFOXMFieldType.ETH_DST, bytes); return this; } /** * Get dl_src * * @return an array of bytes */ public byte[] getDataLayerSource() { return (byte[])getMatchFieldValue(OFOXMFieldType.ETH_SRC); } /** * Set dl_src * * @param dataLayerSource */ public OFMatch setDataLayerSource(byte[] dataLayerSource) { this.setField(OFOXMFieldType.ETH_SRC, dataLayerSource); return this; } /** * Set dl_src, but first translate to byte[] using HexString * * @param mac * A colon separated string of 6 pairs of octets, e..g., * "00:17:42:EF:CD:8D" */ public OFMatch setDataLayerSource(String mac) { byte bytes[] = HexString.fromHexString(mac); if (bytes.length != OFPhysicalPort.OFP_ETH_ALEN) throw new IllegalArgumentException("expected string with 6 octets, got '" + mac + "'"); this.setField(OFOXMFieldType.ETH_SRC, bytes); return this; } /** * Get dl_type * * @return ether_type */ public short getDataLayerType() { return (Short)getMatchFieldValue(OFOXMFieldType.ETH_TYPE); } /** * Set dl_type * * @param dataLayerType */ public OFMatch setDataLayerType(short dataLayerType) { this.setField(OFOXMFieldType.ETH_TYPE, dataLayerType); return this; } /** * Get dl_vlan * * @return vlan tag without the VLAN present bit set */ public short getDataLayerVirtualLan() { try { return (short)((Short)getMatchFieldValue(OFOXMFieldType.VLAN_VID) & 0xFFF); } catch (IllegalArgumentException e) { return OFVlanId.OFPVID_NONE.getValue(); } } /** * Set dl_vlan * * @param dataLayerVirtualLan VLAN ID without the VLAN present bit set */ public OFMatch setDataLayerVirtualLan(short vlan) { this.setField(OFOXMFieldType.VLAN_VID, vlan | OFVlanId.OFPVID_PRESENT.getValue()); return this; } /** * Get dl_vlan_pcp * * @return VLAN PCP value */ public byte getDataLayerVirtualLanPriorityCodePoint() { try { return (Byte) getMatchFieldValue(OFOXMFieldType.VLAN_PCP); } catch (IllegalArgumentException e) { return 0; } } /** * Set dl_vlan_pcp * * @param pcp */ public OFMatch setDataLayerVirtualLanPriorityCodePoint(byte pcp) { this.setField(OFOXMFieldType.VLAN_VID, pcp); return this; } /** * Get nw_proto * * @return */ public byte getNetworkProtocol() { return (Byte)getMatchFieldValue(OFOXMFieldType.IP_PROTO); } /** * Set nw_proto * * @param networkProtocol */ public OFMatch setNetworkProtocol(byte networkProtocol) { this.setField(OFOXMFieldType.IP_PROTO, networkProtocol); return this; } /** * Get nw_tos OFMatch stores the ToS bits as 6-bits in the lower significant bits * * @return : 6-bit DSCP value (0-63) */ public byte getNetworkTypeOfService() { try { return (byte)((Byte)getMatchFieldValue(OFOXMFieldType.IP_DSCP) & 0x3f); } catch (IllegalArgumentException e) { return 0; } } /** * Set nw_tos OFMatch stores the ToS bits as lower 6-bits * * @param networkTypeOfService TOS value including ECN in the lower 2 bits * : 6-bit DSCP value (0-63) */ public OFMatch setNetworkTypeOfService(byte networkTypeOfService) { this.setField(OFOXMFieldType.IP_DSCP, (byte)(networkTypeOfService >> 2) & 0x3f); this.setField(OFOXMFieldType.IP_ECN, (byte)(networkTypeOfService & 0x3)); return this; } /** * Get nw_dst * * @return integer destination IP address */ public int getNetworkDestination() { return (Integer)getMatchFieldValue(OFOXMFieldType.IPV4_DST); } /** * Get nw_dst mask * * @return integer destination IP address mask */ public int getNetworkDestinationMask() { Object mask = getMatchFieldMask(OFOXMFieldType.IPV4_DST); if (mask == null) return 0; else return (Integer)mask; } /** * Set nw_dst * * @param networkDestination destination IP address */ public OFMatch setNetworkDestination(int networkDestination) { setNetworkDestination(ETH_TYPE_IPV4, networkDestination); return this; } /** * Set nw_dst * * @param dataLayerType ether type * @param networkDestination destination IP address */ public OFMatch setNetworkDestination(short dataLayerType, int networkDestination) { switch (dataLayerType) { case ETH_TYPE_IPV4: this.setField(OFOXMFieldType.IPV4_DST, networkDestination); break; case ETH_TYPE_IPV6: this.setField(OFOXMFieldType.IPV6_DST, networkDestination); break; case ETH_TYPE_ARP: this.setField(OFOXMFieldType.ARP_THA, networkDestination); break; } return this; } /** * Get nw_src * * @return integer source IP address */ // TODO: Add support for IPv6 public int getNetworkSource() { return (Integer)getMatchFieldValue(OFOXMFieldType.IPV4_SRC); } /** * Get nw_src mask * * @return integer source IP address mask */ public int getNetworkSourceMask() { Object mask = getMatchFieldMask(OFOXMFieldType.IPV4_SRC); if (mask == null) return 0; else return (Integer)mask; } /** * Set nw_src * * @param networkSource source IP address */ // TODO: Add support for IPv6 public OFMatch setNetworkSource(int networkSource) { setNetworkSource(ETH_TYPE_IPV4, networkSource); return this; } /** * Set nw_src * * @param dataLayerType ether type * @param networkSource source IP address */ // TODO: Add support for IPv6 public OFMatch setNetworkSource(short dataLayerType, int networkSource) { switch (dataLayerType) { case ETH_TYPE_IPV4: this.setField(OFOXMFieldType.IPV4_SRC, networkSource); break; case ETH_TYPE_ARP: this.setField(OFOXMFieldType.ARP_SHA, networkSource); break; } return this; } /** * Get tp_dst * * @return destination port number */ public short getTransportDestination() { byte networkProtocol = getNetworkProtocol(); switch (networkProtocol) { case IP_PROTO_TCP: return (Short)getMatchFieldValue(OFOXMFieldType.TCP_DST); case IP_PROTO_UDP: return (Short)getMatchFieldValue(OFOXMFieldType.UDP_DST); case IP_PROTO_SCTP: return (Short)getMatchFieldValue(OFOXMFieldType.SCTP_DST); } throw new IllegalArgumentException("Network Protocol invalid for extracting port number"); } /** * Set tp_dst * * @param transportDestination TCP destination port number */ public OFMatch setTransportDestination(short transportDestination) { setTransportSource(IP_PROTO_TCP, transportDestination); return this; } /** * Set tp_dst * * @param networkProtocol IP protocol * @param transportDestination Destination Transport port number */ public OFMatch setTransportDestination(byte networkProtocol, short transportDestination) { switch (networkProtocol) { case IP_PROTO_TCP: this.setField(OFOXMFieldType.TCP_DST, transportDestination); break; case IP_PROTO_UDP: this.setField(OFOXMFieldType.UDP_DST, transportDestination); break; case IP_PROTO_SCTP: this.setField(OFOXMFieldType.SCTP_DST, transportDestination); break; } return this; } /** * Get tp_src * * @return transportSource Source Transport port number */ public short getTransportSource() { byte networkProtocol = getNetworkProtocol(); switch (networkProtocol) { case IP_PROTO_TCP: return (Short)getMatchFieldValue(OFOXMFieldType.TCP_SRC); case IP_PROTO_UDP: return (Short)getMatchFieldValue(OFOXMFieldType.UDP_SRC); case IP_PROTO_SCTP: return (Short)getMatchFieldValue(OFOXMFieldType.SCTP_SRC); } throw new IllegalArgumentException("Network Protocol invalid for extracting port number"); } /** * Set tp_src * * @param transportSource TCP source port number */ public OFMatch setTransportSource(short transportSource) { setTransportSource(IP_PROTO_TCP, transportSource); return this; } /** * Set tp_src * * @param networkProtocol IP protocol * @param transportSource Source Transport port number */ public OFMatch setTransportSource(byte networkProtocol, short transportSource) { switch (networkProtocol) { case IP_PROTO_TCP: this.setField(OFOXMFieldType.TCP_SRC, transportSource); break; case IP_PROTO_UDP: this.setField(OFOXMFieldType.UDP_SRC, transportSource); break; case IP_PROTO_SCTP: this.setField(OFOXMFieldType.SCTP_SRC, transportSource); break; } return this; } public OFMatchType getType() { return type; } /** * Get the length of this message * @return length */ public short getLength() { return length; } /** * Get the length of this message, unsigned * @return unsigned length */ public int getLengthU() { return U16.f(length); } public short getMatchLength() { return matchLength; } /** Sets match field. In case of existing field, checks for existing value * * @param matchField Check for uniqueness of field and add matchField */ public void setField(OFMatchField newMatchField) { if (this.matchFields == null) this.matchFields = new ArrayList<OFMatchField>(); for (OFMatchField matchField: this.matchFields) { if (matchField.getOXMFieldType() == newMatchField.getOXMFieldType()) { matchField.setOXMFieldValue(newMatchField.getOXMFieldValue()); matchField.setOXMFieldMask(newMatchField.getOXMFieldMask()); return; } } this.matchFields.add(newMatchField); this.matchLength += newMatchField.getOXMFieldLength(); this.length = U16.t(8*((this.matchLength + 4 + 7)/8)); //includes padding } public void setField(OFOXMFieldType matchFieldType, Object matchFieldValue) { OFMatchField matchField = new OFMatchField(matchFieldType, matchFieldValue); setField(matchField); } public void setField(OFOXMFieldType matchFieldType, Object matchFieldValue, Object matchFieldMask) { OFMatchField matchField = new OFMatchField(matchFieldType, matchFieldValue, matchFieldMask); setField(matchField); } /** * Returns read-only copies of the matchfields contained in this OFMatch * @return a list of ordered OFMatchField objects */ public List<OFMatchField> getMatchFields() { return this.matchFields; } /** * Sets the list of matchfields this OFMatch contains * @param matchFields a list of ordered OFMatchField objects */ public OFMatch setMatchFields(List<OFMatchField> matchFields) { this.matchFields = matchFields; return this; } /** * Utility function to wildcard all fields except specified in list * @param preservedFieldTypes list of match field types preserved, * if null all fields are wildcarded */ public void wildcardAllExceptGiven(List<OFOXMFieldType> preservedFieldTypes) { List <OFMatchField> newMatchFields = new ArrayList<OFMatchField>(); if (preservedFieldTypes != null) { for (OFMatchField matchField: matchFields) { OFOXMFieldType type = matchField.getOXMFieldType(); if (preservedFieldTypes.contains(type)) newMatchFields.add(matchField); } } setMatchFields(newMatchFields); } public void readFrom(ByteBuffer data) { byte[] dataLayerAddress = new byte[OFPhysicalPort.OFP_ETH_ALEN]; byte[] dataLayerAddressMask = new byte[OFPhysicalPort.OFP_ETH_ALEN]; int networkAddress; int networkAddressMask; int wildcards; short dataLayerType = 0; byte networkProtocol = 0; byte networkTOS; short transportNumber; int mplsLabel; byte mplsTC; this.type = OFMatchType.values()[data.getShort()]; this.length = data.getShort(); int remaining = this.getLengthU() - 4; //length - sizeof(type and length) int end = data.position() + remaining; //includes padding in case of STANDARD match if (type == OFMatchType.OXM) { int padLength = 8*((length + 7)/8) - length; end += padLength; // including pad if (data.remaining() < remaining) remaining = data.remaining(); this.matchFields = new ArrayList<OFMatchField>(); while (remaining >= OFMatchField.MINIMUM_LENGTH) { OFMatchField matchField = new OFMatchField(); matchField.readFrom(data); this.matchFields.add(matchField); remaining -= U32.f(matchField.getOXMFieldLength()+4); //value length + header length } } else { this.setField(OFOXMFieldType.IN_PORT, data.getInt()); wildcards = data.getInt(); if ((wildcards & OFMatchWildcardMask.ALL.getValue()) == 0) { data.position(end); return; } data.get(dataLayerAddress); data.get(dataLayerAddressMask); this.setField(OFOXMFieldType.ETH_SRC, dataLayerAddress.clone(), dataLayerAddressMask.clone()); data.get(dataLayerAddress); data.get(dataLayerAddressMask); this.setField(OFOXMFieldType.ETH_DST, dataLayerAddress.clone(), dataLayerAddressMask.clone()); if ((wildcards & OFMatchWildcardMask.DL_VLAN.getValue()) == 0) setDataLayerVirtualLan(data.getShort()); else data.getShort(); //skip if ((wildcards & OFMatchWildcardMask.DL_VLAN_PCP.getValue()) == 0) setDataLayerVirtualLanPriorityCodePoint(data.get()); else data.get(); //skip data.get(); //pad if ((wildcards & OFMatchWildcardMask.DL_TYPE.getValue()) == 0) { dataLayerType = data.getShort(); setDataLayerType(dataLayerType); } else data.getShort(); //skip if ((dataLayerType != ETH_TYPE_IPV4) && (dataLayerType != ETH_TYPE_ARP) && (dataLayerType != ETH_TYPE_VLAN) && (dataLayerType != ETH_TYPE_MPLS_UNICAST) && (dataLayerType != ETH_TYPE_MPLS_MULTICAST)) { data.position(end); return; } if ((wildcards & OFMatchWildcardMask.NW_TOS.getValue()) == 0) { networkTOS = data.get(); setNetworkTypeOfService(networkTOS); } else data.get(); //skip if ((wildcards & OFMatchWildcardMask.NW_PROTO.getValue()) == 0) { networkProtocol = data.get(); setNetworkProtocol(networkProtocol); } else data.get(); //skip networkAddress = data.getInt(); networkAddressMask = data.getInt(); if (networkAddress != 0) this.setField(OFOXMFieldType.IPV4_SRC, networkAddress, networkAddressMask); networkAddress = data.getInt(); networkAddressMask = data.getInt(); if (networkAddress != 0) this.setField(OFOXMFieldType.IPV4_DST, networkAddress, networkAddressMask); transportNumber = data.getShort(); if ((wildcards & OFMatchWildcardMask.TP_SRC.getValue()) == 0) { setTransportSource(networkProtocol, transportNumber); } transportNumber = data.getShort(); if ((wildcards & OFMatchWildcardMask.TP_DST.getValue()) == 0) { setTransportDestination(networkProtocol, transportNumber); } mplsLabel = data.getInt(); mplsTC = data.get(); if ((dataLayerType == ETH_TYPE_MPLS_UNICAST) || (dataLayerType == ETH_TYPE_MPLS_MULTICAST)) { if ((wildcards & OFMatchWildcardMask.MPLS_LABEL.getValue()) == 0) this.setField(OFOXMFieldType.MPLS_LABEL, mplsLabel); if ((wildcards & OFMatchWildcardMask.MPLS_TC.getValue()) == 0) this.setField(OFOXMFieldType.MPLS_TC, mplsTC); } data.get(); //pad data.get(); //pad data.get(); //pad this.setField(OFOXMFieldType.METADATA, data.getLong(), data.getLong()); } data.position(end); } public void writeTo(ByteBuffer data) { short matchLength = getMatchLength(); data.putShort((short)this.type.ordinal()); data.putShort(matchLength); //length does not include padding for (OFMatchField matchField : matchFields) { matchField.writeTo(data); } int padLength = 8*((matchLength + 7)/8) - matchLength; for (;padLength>0;padLength data.put((byte)0); //pad } public int hashCode() { final int prime = 227; int result = 1; result = prime * result + ((matchFields == null) ? 0 : matchFields.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof OFMatchField)) { return false; } OFMatch other = (OFMatch) obj; if (matchFields == null) { if (other.matchFields != null) return false; } else if (!matchFields.equals(other.matchFields)) { return false; } return true; } /* (non-Javadoc) * @see java.lang.Object#clone() */ @Override public OFMatch clone() { OFMatch match = new OFMatch(); try { List<OFMatchField> neoMatchFields = new LinkedList<OFMatchField>(); for(OFMatchField matchField: this.matchFields) neoMatchFields.add((OFMatchField) matchField.clone()); match.setMatchFields(neoMatchFields); return match; } catch (CloneNotSupportedException e) { // Won't happen throw new RuntimeException(e); } } /** * Load and return a new OFMatch based on supplied packetData, see * {@link #loadFromPacket(byte[], short)} for details. * * @param packetData * @param inputPort * @return */ public static OFMatch load(byte[] packetData, int inPort) { OFMatch ofm = new OFMatch(); return ofm.loadFromPacket(packetData, inPort); } /** * Initializes this OFMatch structure with the corresponding data from the * specified packet. * * Must specify the input port, to ensure that this.in_port is set * correctly. * * Specify OFPort.NONE or OFPort.ANY if input port not applicable or * available * * @param packetData * The packet's data * @param inputPort * the port the packet arrived on */ public OFMatch loadFromPacket(byte[] packetData, int inPort) { short scratch; byte[] dataLayerAddress = new byte[OFPhysicalPort.OFP_ETH_ALEN]; short dataLayerType = 0; byte networkProtocol = 0; int transportOffset = 34; ByteBuffer packetDataBB = ByteBuffer.wrap(packetData); int limit = packetDataBB.limit(); setInPort(inPort); //TODO: Extend to support more packet types assert (limit >= 14); // dl dst packetDataBB.get(dataLayerAddress); setDataLayerSource(dataLayerAddress.clone()); // dl src packetDataBB.get(dataLayerAddress); setDataLayerSource(dataLayerAddress.clone()); // dl type dataLayerType = packetDataBB.getShort(); setDataLayerType(dataLayerType); if (dataLayerType == (short) ETH_TYPE_VLAN) { // need cast to avoid signed // has vlan tag scratch = packetDataBB.getShort(); setDataLayerVirtualLan((short) (0xfff & scratch)); setDataLayerVirtualLanPriorityCodePoint((byte) ((0xe000 & scratch) >> 13)); dataLayerType = packetDataBB.getShort(); } //TODO: Add support for IPv6 switch (dataLayerType) { case ETH_TYPE_IPV4: // ipv4 // check packet length scratch = packetDataBB.get(); scratch = (short) (0xf & scratch); transportOffset = (packetDataBB.position() - 1) + (scratch * 4); // nw tos (dscp and ecn) setNetworkTypeOfService(packetDataBB.get()); // nw protocol packetDataBB.position(packetDataBB.position() + 7); networkProtocol = packetDataBB.get(); setNetworkProtocol(networkProtocol); // nw src packetDataBB.position(packetDataBB.position() + 2); setNetworkSource(dataLayerType, packetDataBB.getInt()); // nw dst setNetworkDestination(dataLayerType, packetDataBB.getInt()); packetDataBB.position(transportOffset); break; case ETH_TYPE_ARP: // arp int arpPos = packetDataBB.position(); // opcode scratch = packetDataBB.getShort(arpPos + 6); this.setField(OFOXMFieldType.ARP_OP, ((short) (0xff & scratch))); scratch = packetDataBB.getShort(arpPos + 2); // if ipv4 and addr len is 4 if (scratch == 0x800 && packetDataBB.get(arpPos + 5) == 4) { // nw src this.setField(OFOXMFieldType.ARP_SPA, packetDataBB.getInt(arpPos + 14)); // nw dst this.setField(OFOXMFieldType.ARP_TPA, packetDataBB.getInt(arpPos + 24)); } return this; default: //No OXM field added return this; } switch (networkProtocol) { case IP_PROTO_ICMP: // icmp type this.setField(OFOXMFieldType.ICMPV4_TYPE, packetDataBB.get()); // code this.setField(OFOXMFieldType.ICMPV4_CODE, packetDataBB.get()); break; case IP_PROTO_TCP: case IP_PROTO_UDP: case IP_PROTO_SCTP: setTransportSource(networkProtocol, packetDataBB.getShort()); setTransportDestination(networkProtocol, packetDataBB.getShort()); break; default: break; } return this; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "OFMatch [type=" + type + "length=" + length + "matchFields=" + matchFields + "]"; } }
package org.plumelib.util; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.nio.CharBuffer; import java.nio.file.Path; import java.util.ArrayDeque; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.regex.Matcher; import java.util.regex.Pattern; /*>>> import org.checkerframework.checker.lock.qual.*; import org.checkerframework.checker.index.qual.*; import org.checkerframework.checker.nullness.qual.*; import org.checkerframework.checker.regex.qual.*; */ // TODO: // EntryReader has a public concept of "short entry", but I don't think that // concept is logically part of EntryReader. I think it would be better for // Lookup to make this decision itself, for instance by checking whether there // are any line separators in the entry that it gets back. // Here are some useful features that EntryReader should have. // * It should implement some unimplemented methods from LineNumberReader (see // "not yet implemented" in this file). // * It should have constructors that take an InputStream or Reader // (in addition to the current BufferedReader, File, and String versions). // * It should have a close method. // * It should automatically close the underlying file/etc. when the // iterator gets to the end (or the end is otherwise reached). /** * Class that reads records or "entries" from a file. In the simplest case, entries can be lines. It * supports: * * <ul> * <li>include files, * <li>comments, and * <li>multi-line entries (paragraphs). * </ul> * * The syntax of each of these is customizable. * * <p>Example use: * * <pre>{@code * // EntryReader constructor args are: filename, comment regexp, include regexp * try (EntryReader er = new EntryReader(filename, "^#.*", null)) { * for (String line : er) { * ... * } * } catch (IOException e) { * System.err.println("Problem reading " + filename + ": " + e.getMessage()); * } * }</pre> * * @see #getEntry() and @see #setEntryStartStop(String,String) */ @SuppressWarnings("IterableAndIterator") public class EntryReader extends LineNumberReader implements Iterable<String>, Iterator<String> { /// User configuration variables /** Regular expression that specifies an include file. */ private final /*@Nullable*/ /*@Regex(1)*/ Pattern includeRegex; /** Regular expression that matches a comment. */ private final /*@Nullable*/ Pattern commentRegex; /** * Regular expression that starts a long entry. * * <p>If the first line of an entry matches this regexp, then the entry is terminated by: {@link * #entryStopRegex}, another line that matches {@code entryStartRegex} (even not following a * newline), or the end of the current file. * * <p>Otherwise, the first line of an entry does NOT match this regexp (or the regexp is null), in * which case the entry is terminated by a blank line or the end of the current file. */ public /*@MonotonicNonNull*/ /*@Regex(1)*/ Pattern entryStartRegex = null; /** @see #entryStartRegex */ public /*@MonotonicNonNull*/ Pattern entryStopRegex = null; /// Internal implementation variables /** Stack of readers. Used to support include files. */ private final ArrayDeque<FlnReader> readers = new ArrayDeque<FlnReader>(); /** Line that is pushed back to be reread. */ /*@Nullable*/ String pushbackLine = null; /** Platform-specific line separator. */ private static final String lineSep = System.getProperty("line.separator"); /// Helper classes /** * Like LineNumberReader, but also has a filename field. "FlnReader" stands for "Filename and Line * Number Reader". */ private static class FlnReader extends LineNumberReader { /** The file being read. */ public String filename; /** * Create a FlnReader. * * @param reader source from which to read entries * @param filename file name corresponding to reader, for use in error messages. Must be * non-null; if there isn't a name, clients should provide a dummy value. */ public FlnReader(Reader reader, String filename) { super(reader); this.filename = filename; } /** * Create a FlnReader. * * @param filename file from which to read * @throws IOException if there is trobule reading the file */ public FlnReader(String filename) throws IOException { super(UtilPlume.fileReader(filename)); this.filename = filename; } } /** Descriptor for an entry (record, paragraph, etc.). */ public static class Entry { /** First line of the entry. */ public final String firstLine; /** Complete body of the entry including the first line. */ public final String body; /** True if this is a short entry (blank-line-separated). */ public final boolean shortEntry; /** Filename in which the entry was found. */ public final String filename; /** Line number of first line of entry. */ public final long lineNumber; /** * Create an entry. * * @param firstLine first line of the entry * @param body complete body of the entry including the first line * @param shortEntry true if this is a short entry (blank-line-separated) * @param filename filename in which the entry was found * @param lineNumber line number of first line of entry */ public Entry( String firstLine, String body, String filename, long lineNumber, boolean shortEntry) { this.firstLine = firstLine; this.body = body; this.filename = filename; this.lineNumber = lineNumber; this.shortEntry = shortEntry; } /** * Return a substring of the entry body that matches the specified regular expression. If no * match is found, returns the firstLine. * * @param re regex to match * @return a substring that matches re */ public String getDescription(/*@Nullable*/ Pattern re) { if (re == null) { return firstLine; } Matcher descr = re.matcher(body); if (descr.find()) { return descr.group(); } else { return firstLine; } } } /// Constructors /// Inputstream and charset constructors /** * Create a EntryReader that uses the given character set. * * @throws UnsupportedEncodingException if the charset encoding is not supported * @param in source from which to read entries * @param charsetName the character set to use * @param filename non-null file name for stream being read * @param commentRegexString regular expression that matches comments. Any text that matches * commentRegex is removed. A line that is entirely a comment is ignored. * @param includeRegexString regular expression that matches include directives. The expression * should define one group that contains the include file name. * @see #EntryReader(InputStream,String,String,String) */ public EntryReader( InputStream in, String charsetName, String filename, /*@Nullable*/ /*@Regex*/ String commentRegexString, /*@Nullable*/ /*@Regex(1)*/ String includeRegexString) throws UnsupportedEncodingException { this(new InputStreamReader(in, charsetName), filename, commentRegexString, includeRegexString); } /** * Create a EntryReader that does not support comments or include directives. * * @param in the InputStream * @param charsetName the character set to use * @param filename the file name * @throws UnsupportedEncodingException if the charset encoding is not supported * @see #EntryReader(InputStream,String,String,String) */ public EntryReader(InputStream in, String charsetName, String filename) throws UnsupportedEncodingException { this(in, charsetName, filename, null, null); } /// Inputstream (no charset) constructors /** * Create a EntryReader. * * @param in source from which to read entries * @param filename non-null file name for stream being read * @param commentRegexString regular expression that matches comments. Any text that matches * commentRegex is removed. A line that is entirely a comment is ignored. * @param includeRegexString regular expression that matches include directives. The expression * should define one group that contains the include file name. */ public EntryReader( InputStream in, String filename, /*@Nullable*/ /*@Regex*/ String commentRegexString, /*@Nullable*/ /*@Regex(1)*/ String includeRegexString) { this(new InputStreamReader(in, UTF_8), filename, commentRegexString, includeRegexString); } /** * Create a EntryReader that uses the default character set and does not support comments or * include directives. * * @param in the InputStream * @param filename the file name * @see #EntryReader(InputStream,String,String,String,String) */ public EntryReader(InputStream in, String filename) { this(in, filename, null, null); } /** * Create a EntryReader that does not support comments or include directives. * * @param in the InputStream * @see #EntryReader(InputStream,String,String,String) */ public EntryReader(InputStream in) { this(in, "(InputStream)", null, null); } /** A dummy Reader to be used when null is not acceptable. */ private static class DummyReader extends Reader { @Override public void close(/*>>>@GuardSatisfied DummyReader this*/) { // No error, because closing is OK if it appears in try-with-resources. // Later maybe create two versions (with and without exception here). } @Override public void mark(/*>>>@GuardSatisfied DummyReader this, */ int readAheadLimit) { throw new Error("DummyReader"); } @Override public boolean markSupported() { throw new Error("DummyReader"); } @Override public /*@GTENegativeOne*/ int read(/*>>>@GuardSatisfied DummyReader this*/) { throw new Error("DummyReader"); } @Override public /*@IndexOrLow("#1")*/ int read(/*>>>@GuardSatisfied DummyReader this, */ char[] cbuf) { throw new Error("DummyReader"); } @Override public /*@IndexOrLow("#1")*/ int read( /*>>>@GuardSatisfied DummyReader this, */ char[] cbuf, int off, int len) { throw new Error("DummyReader"); } @Override public /*@GTENegativeOne*/ int read( /*>>>@GuardSatisfied DummyReader this, */ CharBuffer target) { throw new Error("DummyReader"); } @Override public boolean ready() { throw new Error("DummyReader"); } @Override public void reset(/*>>>@GuardSatisfied DummyReader this*/) { throw new Error("DummyReader"); } @Override public long skip(/*>>>@GuardSatisfied DummyReader this, */ long n) { throw new Error("DummyReader"); } } /** * Create a EntryReader. * * @param reader source from which to read entries * @param filename file name corresponding to reader, for use in error messages * @param commentRegexString regular expression that matches comments. Any text that matches * commentRegex is removed. A line that is entirely a comment is ignored * @param includeRegexString regular expression that matches include directives. The expression * should define one group that contains the include file name */ public EntryReader( Reader reader, String filename, /*@Nullable*/ /*@Regex*/ String commentRegexString, /*@Nullable*/ /*@Regex(1)*/ String includeRegexString) { // we won't use superclass methods, but passing null as an argument // leads to a NullPointerException. super(new DummyReader()); readers.addFirst(new FlnReader(reader, filename)); if (commentRegexString == null) { commentRegex = null; } else { commentRegex = Pattern.compile(commentRegexString); } if (includeRegexString == null) { includeRegex = null; } else { includeRegex = Pattern.compile(includeRegexString); } } /** * Create a EntryReader that does not support comments or include directives. * * @param reader source from which to read entries * @see #EntryReader(Reader,String,String,String) */ public EntryReader(Reader reader) { this(reader, reader.toString(), null, null); } /// Path constructors /** * Create an EntryReader. * * @param path initial file to read * @param commentRegex regular expression that matches comments. Any text that matches * commentRegex is removed. A line that is entirely a comment is ignored. * @param includeRegex regular expression that matches include directives. The expression should * define one group that contains the include file name. * @throws IOException if there is a problem reading the file */ public EntryReader( Path path, /*@Nullable*/ /*@Regex*/ String commentRegex, /*@Nullable*/ /*@Regex(1)*/ String includeRegex) throws IOException { this(UtilPlume.fileReader(path), path.toString(), commentRegex, includeRegex); } /** * Create a EntryReader that does not support comments or include directives. * * @param path the file to read * @throws IOException if there is a problem reading the file * @see #EntryReader(File,String,String) */ public EntryReader(Path path) throws IOException { this(path, null, null); } /** * Create a EntryReader that does not support comments or include directives. * * @param path the file to read * @param charsetName the character set to use * @throws IOException if there is a problem reading the file * @see #EntryReader(Path,String,String) */ public EntryReader(Path path, String charsetName) throws IOException { this(UtilPlume.fileInputStream(path), charsetName, path.toString(), null, null); } /// File constructors /** * Create an EntryReader. * * @param file initial file to read * @param commentRegex regular expression that matches comments. Any text that matches * commentRegex is removed. A line that is entirely a comment is ignored. * @param includeRegex regular expression that matches include directives. The expression should * define one group that contains the include file name. * @throws IOException if there is a problem reading the file */ public EntryReader( File file, /*@Nullable*/ /*@Regex*/ String commentRegex, /*@Nullable*/ /*@Regex(1)*/ String includeRegex) throws IOException { this(UtilPlume.fileReader(file), file.toString(), commentRegex, includeRegex); } /** * Create a EntryReader that does not support comments or include directives. * * @param file the file to read * @throws IOException if there is a problem reading the file * @see #EntryReader(File,String,String) */ public EntryReader(File file) throws IOException { this(file, null, null); } /** * Create a EntryReader that does not support comments or include directives. * * @param file the file to read * @param charsetName the character set to use * @throws IOException if there is a problem reading the file * @see #EntryReader(File,String,String) */ public EntryReader(File file, String charsetName) throws IOException { this(UtilPlume.fileInputStream(file), charsetName, file.toString(), null, null); } /// Filename constructors /** * Create a new EntryReader starting with the specified file. * * @param filename initial file to read * @param commentRegex regular expression that matches comments. Any text that matches {@code * commentRegex} is removed. A line that is entirely a comment is ignored. * @param includeRegex regular expression that matches include directives. The expression should * define one group that contains the include file name. * @throws IOException if there is a problem reading the file * @see #EntryReader(File,String,String) */ public EntryReader( String filename, /*@Nullable*/ /*@Regex*/ String commentRegex, /*@Nullable*/ /*@Regex(1)*/ String includeRegex) throws IOException { this(new File(filename), commentRegex, includeRegex); } /** * Create a EntryReader that does not support comments or include directives. * * @param filename source from which to read entries * @throws IOException if there is a problem reading the file * @see #EntryReader(String,String,String) */ public EntryReader(String filename) throws IOException { this(filename, null, null); } /** * Create a EntryReader that does not support comments or include directives. * * @param filename source from which to read entries * @param charsetName the character set to use * @throws IOException if there is a problem reading the file * @see #EntryReader(String,String,String) */ public EntryReader(String filename, String charsetName) throws IOException { this(new FileInputStream(filename), charsetName, filename, null, null); } /// Methods /** * Read a line, ignoring comments and processing includes. Note that a line that is completely a * comment is completely ignored (and not returned as a blank line). Returns null at end of file. * * @return the string that was read, or null at end of file */ @Override public /*@Nullable*/ String readLine( /*>>>@GuardSatisfied EntryReader this*/) throws IOException { // System.out.printf ("Entering size = %d%n", readers.size()); // If a line has been pushed back, return it instead if (pushbackLine != null) { String line = pushbackLine; pushbackLine = null; return line; } String line = getNextLine(); if (commentRegex != null) { while (line != null) { Matcher cmatch = commentRegex.matcher(line); if (cmatch.find()) { line = cmatch.replaceFirst(""); if (line.length() > 0) { break; } } else { break; } line = getNextLine(); // System.out.printf ("getNextLine = %s%n", line); } } if (line == null) { return null; } // Handle include files. Non-absolute pathnames are relative // to the including file (the current file) if (includeRegex != null) { Matcher m = includeRegex.matcher(line); if (m.matches()) { String filenameString = m.group(1); if (filenameString == null) { throw new Error( String.format( "includeRegex (%s) does not capture group 1 in %s", includeRegex, line)); } File filename = new File(UtilPlume.expandFilename(filenameString)); // System.out.printf ("Trying to include filename %s%n", filename); if (!filename.isAbsolute()) { FlnReader reader = readers.getFirst(); File currentFilename = new File(reader.filename); File currentParent = currentFilename.getParentFile(); filename = new File(currentParent, filename.toString()); // System.out.printf ("absolute filename = %s %s %s%n", // currentFilename, currentParent, filename); } readers.addFirst(new FlnReader(filename.getAbsolutePath())); return readLine(); } } // System.out.printf ("Returning [%d] '%s'%n", readers.size(), line); return (line); } /** * Return a line-by-line iterator for this file. * * <p><b>Warning:</b> This does not return a fresh iterator each time. The iterator is a * singleton, the same one is returned each time, and a new one can never be created after it is * exhausted. * * @return a line-by-line iterator for this file */ @Override public Iterator<String> iterator() { return this; } /** * Returns whether or not there is another line to read. Any IOExceptions are turned into errors * (because the definition of hasNext() in Iterator doesn't throw any exceptions). * * @return whether there is another line to read */ @Override public boolean hasNext(/*>>>@GuardSatisfied EntryReader this*/) { if (pushbackLine != null) { return true; } String line = null; try { line = readLine(); } catch (IOException e) { throw new Error("unexpected IOException: ", e); } if (line == null) { return false; } putback(line); return true; } /** * Return the next line in the multi-file. * * @return the next line in the multi-file * @throws NoSuchElementException at end of file */ @Override public String next(/*>>>@GuardSatisfied EntryReader this*/) { try { String result = readLine(); if (result != null) { return result; } else { throw new NoSuchElementException(); } } catch (IOException e) { throw new Error("unexpected IOException", e); } } /** remove() is not supported. */ @Override public void remove(/*>>>@GuardSatisfied EntryReader this*/) { throw new UnsupportedOperationException("can't remove lines from file"); } /** * Returns the next entry (paragraph) in the file. Entries are separated by blank lines unless the * entry started with {@link #entryStartRegex} (see {@link #setEntryStartStop}). If no more * entries are available, returns null. * * @return the next entry (paragraph) in the file * @throws IOException if there is a problem reading the file */ public /*@Nullable*/ Entry getEntry(/*>>>@GuardSatisfied EntryReader this*/) throws IOException { // Skip any preceding blank lines String line = readLine(); while ((line != null) && (line.trim().length() == 0)) { line = readLine(); } if (line == null) { return (null); } StringBuilder body = new StringBuilder(10000); Entry entry = null; String filename = getFileName(); long lineNumber = getLineNumber(); // If first line matches entryStartRegex, this is a long entry. /*@Regex(1)*/ Matcher entryMatch = null; if (entryStartRegex != null) { entryMatch = entryStartRegex.matcher(line); } if ((entryMatch != null) && entryMatch.find()) { assert entryStartRegex != null : "@AssumeAssertion(nullness): dependent: entryMatch != null"; assert entryStopRegex != null : "@AssumeAssertion(nullness): dependent: entryStartRegex != null"; // Remove entry match from the line if (entryMatch.groupCount() > 0) { @SuppressWarnings( "nullness") /*@NonNull*/ String matchGroup1 = entryMatch.group(1); line = entryMatch.replaceFirst(matchGroup1); } // Description is the first line String description = line; // Read until we find the termination of the entry Matcher endEntryMatch = entryStopRegex.matcher(line); while ((line != null) && !entryMatch.find() && !endEntryMatch.find() && filename.equals(getFileName())) { body.append(line); body.append(lineSep); line = readLine(); if (line == null) { break; // end of file serves as entry terminator } entryMatch = entryStartRegex.matcher(line); endEntryMatch = entryStopRegex.matcher(line); } // If this entry was terminated by the start of the next one, // put that line back if ((line != null) && (entryMatch.find(0) || !filename.equals(getFileName()))) { putback(line); } entry = new Entry(description, body.toString(), filename, lineNumber, false); } else { // blank-separated entry String description = line; // Read until we find another blank line while ((line != null) && (line.trim().length() != 0) && filename.equals(getFileName())) { body.append(line); body.append(lineSep); line = readLine(); } // If this entry was terminated by the start of a new input file // put that line back if ((line != null) && !filename.equals(getFileName())) { putback(line); } entry = new Entry(description, body.toString(), filename, lineNumber, true); } return (entry); } /** * Reads the next line from the current reader. If EOF is encountered pop out to the next reader. * Returns null if there is no more input. * * @return next line from the reader, or null if there is no more input * @throws IOException if there is trouble with the reader */ private /*@Nullable*/ String getNextLine( /*>>>@GuardSatisfied EntryReader this*/) throws IOException { if (readers.size() == 0) { return (null); } FlnReader ri1 = readers.getFirst(); String line = ri1.readLine(); while (line == null) { readers.removeFirst(); if (readers.isEmpty()) { return (null); } FlnReader ri2 = readers.peekFirst(); line = ri2.readLine(); } return (line); } /** * Returns the current filename. * * @return the current filename */ public String getFileName(/*>>>@GuardSatisfied EntryReader this*/) { FlnReader ri = readers.peekFirst(); if (ri == null) { throw new Error("Past end of input"); } return ri.filename; } /** * Return the current line number in the current file. * * @return the current line number */ @Override public /*@NonNegative*/ int getLineNumber(/*>>>@GuardSatisfied EntryReader this*/) { FlnReader ri = readers.peekFirst(); if (ri == null) { throw new Error("Past end of input"); } return ri.getLineNumber(); } /** * Set the current line number in the current file. * * @param lineNumber new line number for the current file */ @Override public void setLineNumber( /*>>>@GuardSatisfied EntryReader this, */ /*@NonNegative*/ int lineNumber) { FlnReader ri = readers.peekFirst(); if (ri == null) { throw new Error("Past end of input"); } ri.setLineNumber(lineNumber); } /** * Set the regular expressions for the start and stop of long entries (multiple lines that are * read as a group by getEntry()). * * @param entryStartRegex regular expression that starts a long entry * @param entryStopRegex regular expression that ends a long entry */ public void setEntryStartStop( /*>>>@GuardSatisfied EntryReader this, */ /*@Regex(1)*/ String entryStartRegex, /*@Regex*/ String entryStopRegex) { this.entryStartRegex = Pattern.compile(entryStartRegex); this.entryStopRegex = Pattern.compile(entryStopRegex); } /** * Set the regular expressions for the start and stop of long entries (multiple lines that are * read as a group by getEntry()). * * @param entryStartRegex regular expression that starts a long entry * @param entryStopRegex regular expression that ends a long entry */ public void setEntryStartStop( /*>>>@GuardSatisfied EntryReader this, */ /*@Regex(1)*/ Pattern entryStartRegex, Pattern entryStopRegex) { this.entryStartRegex = entryStartRegex; this.entryStopRegex = entryStopRegex; } /** * Puts the specified line back in the input. Only one line can be put back. * * @param line the line to be put back in the input */ // TODO: This would probably be better implemented with the "mark" mechanism // of BufferedReader (which is also in LineNumberReader and FlnReader). public void putback(/*>>>@GuardSatisfied EntryReader this, */ String line) { assert pushbackLine == null : "push back '" + line + "' when '" + pushbackLine + "' already back"; pushbackLine = line; } // No Javadoc on these methods, so the Javadoc is inherited. @Override public void mark(/*>>>@GuardSatisfied EntryReader this, */ int readAheadLimit) { throw new Error("not yet implemented"); } @Override public /*@GTENegativeOne*/ int read(/*>>>@GuardSatisfied EntryReader this*/) { throw new Error("not yet implemented"); } @Override public /*@IndexOrLow("#1")*/ int read( /*>>>@GuardSatisfied EntryReader this, */ char[] cbuf, int off, int len) { throw new Error("not yet implemented"); } @Override public void reset(/*>>>@GuardSatisfied EntryReader this*/) { throw new Error("not yet implemented"); } @Override public long skip(/*>>>@GuardSatisfied EntryReader this, */ long n) { throw new Error("not yet implemented"); } /** * Simple usage example. * * @param args command-line arguments: filename [commentRegex [includeRegex]] * @throws IOException if there is a problem reading a file */ public static void main(String[] args) throws IOException { if (args.length < 1 || args.length > 3) { System.err.println( "EntryReader sample program requires 1-3 args: filename [commentRegex [includeRegex]]"); System.exit(1); } String filename = args[0]; String commentRegex = null; String includeRegex = null; if (args.length >= 2) { commentRegex = args[1]; if (!RegexUtil.isRegex(commentRegex)) { System.err.println( "Error parsing comment regex \"" + commentRegex + "\": " + RegexUtil.regexError(commentRegex)); System.exit(1); } } if (args.length >= 3) { includeRegex = args[2]; if (!RegexUtil.isRegex(includeRegex, 1)) { System.err.println( "Error parsing include regex \"" + includeRegex + "\": " + RegexUtil.regexError(includeRegex)); System.exit(1); } } EntryReader reader = new EntryReader(filename, commentRegex, includeRegex); String line = reader.readLine(); while (line != null) { System.out.printf("%s: %d: %s%n", reader.getFileName(), reader.getLineNumber(), line); line = reader.readLine(); } } }
package org.sahagin.report; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.output.FileWriterWithEncoding; import org.apache.commons.lang.StringEscapeUtils; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import org.openqa.selenium.io.IOUtils; import org.sahagin.share.CommonPath; import org.sahagin.share.CommonUtils; import org.sahagin.share.IllegalDataStructureException; import org.sahagin.share.IllegalTestScriptException; import org.sahagin.share.Logging; import org.sahagin.share.TestDocResolver; import org.sahagin.share.runresults.LineScreenCapture; import org.sahagin.share.runresults.RootFuncRunResult; import org.sahagin.share.runresults.RunFailure; import org.sahagin.share.runresults.RunResults; import org.sahagin.share.runresults.StackLine; import org.sahagin.share.srctree.SrcTree; import org.sahagin.share.srctree.TestFunction; import org.sahagin.share.srctree.TestMethod; import org.sahagin.share.srctree.code.CodeLine; import org.sahagin.share.srctree.code.SubFunctionInvoke; import org.sahagin.share.yaml.YamlConvertException; import org.sahagin.share.yaml.YamlUtils; //TODO support TestDoc annotation for Enumerate type //TODO support method optional argument public class HtmlReport { private static Logger logger = Logging.getLogger(HtmlReport.class.getName()); public HtmlReport() { // stop generating velocity.log Velocity.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.NullLogSystem"); Velocity.init(); } private String generateTtId(List<StackLine> stackLines) { if (stackLines.size() == 0) { throw new IllegalArgumentException("empty stackLines"); } String ttId = ""; for (int i = stackLines.size() - 1; i >= 0; i if (i != stackLines.size() - 1) { ttId = ttId + "_"; } ttId = ttId + Integer.toString(stackLines.get(i).getCodeBodyIndex()); } return ttId; } // generate ResportScreenCapture list from lineScreenCaptures and private List<ReportScreenCapture> generateReportScreenCaptures( List<LineScreenCapture> lineScreenCaptures, File inputCaptureRootDir, File reportOutputDir, File funcReportParentDir) { List<ReportScreenCapture> reportCaptures = new ArrayList<ReportScreenCapture>(lineScreenCaptures.size()); // add noImage capture String noImageFilePath = new File(CommonUtils.relativize( CommonPath.htmlExternalResourceRootDir(reportOutputDir), funcReportParentDir), "images/noImage.png").getPath(); ReportScreenCapture noImageCapture = new ReportScreenCapture(); // URL separator is always slash regardless of OS type noImageCapture.setPath(FilenameUtils.separatorsToUnix(noImageFilePath)); noImageCapture.setTtId("noImage"); reportCaptures.add(noImageCapture); logger.info("inputCaptureRootDir: " + inputCaptureRootDir); logger.info("reportOutputDir: " + reportOutputDir); logger.info("funcReportParentDir: " + funcReportParentDir); // add each line screen capture for (LineScreenCapture lineScreenCapture : lineScreenCaptures) { ReportScreenCapture reportCapture = new ReportScreenCapture(); File relInputCapturePath = CommonUtils.relativize( lineScreenCapture.getPath(), inputCaptureRootDir); File absOutputCapturePath = new File( CommonPath.htmlReportCaptureRootDir(reportOutputDir), relInputCapturePath.getPath()); File relOutputCapturePath = CommonUtils.relativize(absOutputCapturePath, funcReportParentDir); // URL separator is always slash regardless of OS type reportCapture.setPath(FilenameUtils.separatorsToUnix(relOutputCapturePath.getPath())); String ttId = generateTtId(lineScreenCapture.getStackLines()); reportCapture.setTtId(ttId); reportCaptures.add(reportCapture); } return reportCaptures; } // returns null if no failure private RunFailure getRunFailure(RootFuncRunResult runResult) { if (runResult == null || runResult.getRunFailures().size() == 0) { return null; // no failure } // multiple run failures in one test method are not supported yet return runResult.getRunFailures().get(0); } private String stackLinesStr(List<StackLine> stackLines) { String result = ""; for (int i = 0; i < stackLines.size(); i++) { result = result + String.format("%s%n", stackLines.get(i).getFunctionKey()); } return result; } // returns 0 if stackLines == errStackLines (means error line), // returns positive if stackLines > errStackLines (means not executed), // returns negative if stackLines < errStackLines (means already executed) private int compareToErrStackLines(List<StackLine> stackLines, List<StackLine> errStackLines) { if (errStackLines == null || errStackLines.size() == 0) { return -1; // already executed } if (stackLines.size() == 0) { throw new IllegalArgumentException("empty stackLine"); } for (int i = 0; i < stackLines.size(); i++) { if (i >= errStackLines.size()) { throw new IllegalArgumentException(String.format( "stack mismatch:%n[stackLines]%n%s[errStackLines]%n%s", stackLinesStr(stackLines), stackLinesStr(errStackLines))); } int indexFromTail = stackLines.size() - 1 - i; int errIndexFromTail = errStackLines.size() - 1 - i; int line = stackLines.get(indexFromTail).getCodeBodyIndex(); int errLine = errStackLines.get(errIndexFromTail).getCodeBodyIndex(); if (line < errLine) { return -1; // already executed } else if (line > errLine) { return 1; // not executed } } return 0; } private String pageTestDoc(CodeLine codeLine) { String pageTestDoc = TestDocResolver.pageTestDoc(codeLine.getCode()); if (pageTestDoc == null || pageTestDoc.equals("")) { return "-"; } else { return pageTestDoc; } } private String placeholderResolvedTestDoc(CodeLine codeLine, List<String> parentFuncArgTestDocs) throws IllegalTestScriptException { String funcTestDoc = TestDocResolver.placeholderResolvedFuncTestDoc( codeLine.getCode(), parentFuncArgTestDocs); if (funcTestDoc == null) { return ""; } return funcTestDoc; } private ReportCodeLine generateReportCodeLine(CodeLine codeLine, List<String> parentFuncArgTestDocs, List<StackLine> stackLines, RunFailure runFailure, boolean executed, String ttId, String parentTtId) throws IllegalTestScriptException { if (parentFuncArgTestDocs == null) { throw new NullPointerException(); } if (stackLines == null) { throw new NullPointerException(); } ReportCodeLine result = new ReportCodeLine(); result.setCodeLine(codeLine); String pageTestDoc = pageTestDoc(codeLine); result.setPagetTestDoc(pageTestDoc); String testDoc = placeholderResolvedTestDoc(codeLine, parentFuncArgTestDocs); result.setTestDoc(testDoc); List<String> funcArgTestDocs = TestDocResolver.placeholderResolvedFuncArgTestDocs(codeLine.getCode(), parentFuncArgTestDocs); result.addAllFuncArgTestDocs(funcArgTestDocs); result.setStackLines(stackLines); result.setTtId(ttId); result.setParentTtId(parentTtId); List<StackLine> errStackLines = null; if (runFailure != null) { errStackLines = runFailure.getStackLines(); } int errCompare = compareToErrStackLines(stackLines, errStackLines); if (!executed || errCompare > 0) { result.setHasError(false); result.setAlreadyRun(false); } else if (errCompare == 0) { result.setHasError(true); result.setAlreadyRun(true); } else if (errCompare < 0) { result.setHasError(false); result.setAlreadyRun(true); } else { throw new RuntimeException("implementation error"); } return result; } private StackLine generateStackLine(TestFunction function, String functionKey, int codeBodyIndex, int line) { StackLine result = new StackLine(); result.setFunction(function); result.setFunctionKey(functionKey); result.setCodeBodyIndex(codeBodyIndex); result.setLine(line); return result; } // runFailure... set null if not error private List<ReportCodeLine> generateReportCodeBody( TestFunction rootFunction, RunFailure runFailure, boolean executed) throws IllegalTestScriptException { List<ReportCodeLine> result = new ArrayList<ReportCodeLine>(rootFunction.getCodeBody().size()); for (int i = 0; i < rootFunction.getCodeBody().size(); i++) { CodeLine codeLine = rootFunction.getCodeBody().get(i); String rootTtId = Integer.toString(i); StackLine rootStackLine = generateStackLine( rootFunction, rootFunction.getKey(), i, codeLine.getStartLine()); List<StackLine> rootStackLines = new ArrayList<StackLine>(1); rootStackLines.add(rootStackLine); ReportCodeLine reportCodeLine = generateReportCodeLine(codeLine, new ArrayList<String>(0), rootStackLines, runFailure, executed, rootTtId, null); result.add(reportCodeLine); // add direct child to HTML report if (codeLine.getCode() instanceof SubFunctionInvoke) { SubFunctionInvoke invoke = (SubFunctionInvoke) codeLine.getCode(); List<String> parentFuncArgTestDocs = reportCodeLine.getFuncArgTestDocs(); List<CodeLine> codeBody = invoke.getSubFunction().getCodeBody(); for (int j = 0; j < codeBody.size(); j++) { CodeLine childCodeLine = codeBody.get(j); StackLine childStackLine = generateStackLine(invoke.getSubFunction(), invoke.getSubFunctionKey(), j, childCodeLine.getStartLine()); List<StackLine> childStackLines = new ArrayList<StackLine>(2); childStackLines.add(childStackLine); childStackLines.add(rootStackLine); ReportCodeLine childReportCodeLine = generateReportCodeLine( childCodeLine, parentFuncArgTestDocs, childStackLines, runFailure, executed, rootTtId + "_" + j, rootTtId); result.add(childReportCodeLine); } } } return result; } private SrcTree generateSrcTree(File reportInputDataDir) throws IllegalDataStructureException { // generate srcTree from YAML file Map<String, Object> yamlObj = YamlUtils.load( CommonPath.srcTreeFile(reportInputDataDir)); SrcTree srcTree = new SrcTree(); try { srcTree.fromYamlObject(yamlObj); } catch (YamlConvertException e) { throw new IllegalDataStructureException(e); } srcTree.resolveKeyReference(); return srcTree; } private RunResults generateRunResults(File reportInputDataDir, SrcTree srcTree) throws IllegalDataStructureException { RunResults results = new RunResults(); Collection<File> runResultFiles; File runResultsRootDir = CommonPath.runResultRootDir(reportInputDataDir); if (runResultsRootDir.exists()) { runResultFiles = FileUtils.listFiles(runResultsRootDir, null, true); } else { runResultFiles = new ArrayList<File>(0); } for (File runResultFile : runResultFiles) { Map<String, Object> runResultYamlObj = YamlUtils.load(runResultFile); RootFuncRunResult rootFuncRunResult = new RootFuncRunResult(); try { rootFuncRunResult.fromYamlObject(runResultYamlObj); } catch (YamlConvertException e) { throw new IllegalDataStructureException(e); } results.addRootFuncRunResults(rootFuncRunResult); } results.resolveKeyReference(srcTree); return results; } private void deleteDirIfExists(File dir) { if (dir.exists()) { try { FileUtils.deleteDirectory(dir); } catch (IOException e) { throw new RuntimeException("fail to delete " + dir.getAbsolutePath(), e); } } } private void escapePut(VelocityContext context, String key, String value) { context.put(key, StringEscapeUtils.escapeHtml(value)); } // each report HTML file is {methodQualifiedParentPath}/{methodSimpleName}.html public void generate(File reportInputDataDir, File reportOutputDir) throws IllegalDataStructureException, IllegalTestScriptException { deleteDirIfExists(reportOutputDir); // delete previous execution output SrcTree srcTree = generateSrcTree(reportInputDataDir); RunResults runResults = generateRunResults(reportInputDataDir, srcTree); File htmlExternalResRootDir = CommonPath.htmlExternalResourceRootDir(reportOutputDir); // generate src-tree-yaml.js String srcTreeYamlStr; try { srcTreeYamlStr = FileUtils.readFileToString(CommonPath.srcTreeFile(reportInputDataDir), "UTF-8"); } catch (IOException e) { throw new RuntimeException(e); } VelocityContext srcTreeContext = new VelocityContext(); // don't need HTML encode srcTreeContext.put("yamlStr", srcTreeYamlStr); File srcTreeYamlJsFile = new File(htmlExternalResRootDir, "js/report/src-tree-yaml.js"); generateVelocityOutput(srcTreeContext, "/template/src-tree-yaml.js.vm", srcTreeYamlJsFile); // set up HTML external files // TODO all file paths are hard coded. this is very poor logic.. extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/common-utils.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/capture-style.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/yaml/js-yaml.min.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/yaml/yaml-utils.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/code/code.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/code/string-code.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/code/func-argument.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/code/unknown-code.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/code/sub-function-invoke.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/code/sub-method-invoke.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/code/code-line.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/test-class.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/page-class.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/test-function.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/test-method.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/test-func-table.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/test-class-table.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/srctree/src-tree.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/share/testdoc-resolver.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "css/fonts/flexslider-icon.eot"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "css/fonts/flexslider-icon.svg"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "css/fonts/flexslider-icon.ttf"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "css/fonts/flexslider-icon.woff"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "css/images/bx_loader.gif"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "css/images/controls.png"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "css/jquery.bxslider.css"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "css/jquery.treetable.css"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "css/jquery.treetable.theme.default.css"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "css/perfect-scrollbar.min.css"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "css/report.css"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "images/noImage.png"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/report/jquery-1.11.1.min.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/report/jquery.bxslider.min.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/report/jquery.treetable.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/report/perfect-scrollbar.min.js"); extractHtmlExternalResFromThisJar(htmlExternalResRootDir, "js/report/report.js"); // copy screen captures to reportOutputDir // TODO copying screen capture may be slow action File inputCaptureRootDir = CommonPath.inputCaptureRootDir(reportInputDataDir); File htmlReportCaptureRootDir = CommonPath.htmlReportCaptureRootDir(reportOutputDir); try { if (inputCaptureRootDir.exists()) { FileUtils.copyDirectory(inputCaptureRootDir, htmlReportCaptureRootDir); } } catch (IOException e) { throw new RuntimeException(e); } List<TestFunction> testFunctions = srcTree.getRootFuncTable().getTestFunctions(); File reportMainDir = CommonPath.htmlReportMainFile(reportOutputDir).getParentFile(); List<ReportFuncLink> reportLinks = new ArrayList<ReportFuncLink>(testFunctions.size()); // generate each function report for (TestFunction rootFunc : testFunctions) { TestMethod method = (TestMethod) rootFunc; File funcReportParentDir = new File(CommonPath.funcHtmlReportRootDir(reportOutputDir), method.getTestClass().getQualifiedName()); funcReportParentDir.mkdirs(); VelocityContext funcContext = new VelocityContext(); if (rootFunc.getTestDoc() == null) { escapePut(funcContext, "title", rootFunc.getSimpleName()); } else { escapePut(funcContext, "title", rootFunc.getTestDoc()); } String externalResourceRootDir = CommonUtils.relativize( CommonPath.htmlExternalResourceRootDir(reportOutputDir), funcReportParentDir).getPath(); // URL separator is always slash regardless of OS type escapePut(funcContext, "externalResourceRootDir", FilenameUtils.separatorsToUnix(externalResourceRootDir)); if (!(rootFunc instanceof TestMethod)) { throw new RuntimeException("not supported yet: " + rootFunc); } escapePut(funcContext, "className", method.getTestClass().getQualifiedName()); escapePut(funcContext, "classTestDoc", method.getTestClass().getTestDoc()); escapePut(funcContext, "funcName", rootFunc.getSimpleName()); escapePut(funcContext, "funcTestDoc", rootFunc.getTestDoc()); RootFuncRunResult runResult = runResults.getRunResultByRootFunction(rootFunc); boolean executed = (runResult != null); RunFailure runFailure = getRunFailure(runResult); if (runFailure == null) { escapePut(funcContext, "errMsg", null); escapePut(funcContext, "errLineTtId", ""); } else { escapePut(funcContext, "errMsg", runFailure.getMessage().trim()); escapePut(funcContext, "errLineTtId", generateTtId(runFailure.getStackLines())); } List<ReportCodeLine> reportCodeBody = generateReportCodeBody(rootFunc, runFailure, executed); funcContext.put("codeBody", reportCodeBody); List<LineScreenCapture> lineScreenCaptures; if (runResult == null) { lineScreenCaptures = new ArrayList<LineScreenCapture>(0); } else { lineScreenCaptures = runResult.getLineScreenCaptures(); } List<ReportScreenCapture> captures = generateReportScreenCaptures( lineScreenCaptures, inputCaptureRootDir, reportOutputDir, funcReportParentDir); funcContext.put("captures", captures); File funcReportFile = new File(funcReportParentDir, rootFunc.getSimpleName() + ".html"); generateVelocityOutput(funcContext, "/template/report.html.vm", funcReportFile); // set reportLinks data ReportFuncLink reportLink = new ReportFuncLink(); reportLink.setTitle(method.getQualifiedName()); String reportLinkPath = CommonUtils.relativize(funcReportFile, reportMainDir).getPath(); // URL separator is always slash regardless of OS type reportLink.setPath(FilenameUtils.separatorsToUnix(reportLinkPath)); reportLinks.add(reportLink); } // TODO HTML encode all codeBody, captures, reportLinks values // generate main index.html report VelocityContext mainContext = new VelocityContext(); mainContext.put("reportLinks", reportLinks); generateVelocityOutput(mainContext, "/template/index.html.vm", CommonPath.htmlReportMainFile(reportOutputDir)); } private void generateVelocityOutput( VelocityContext context, String templateResourcePath, File outputFile) { outputFile.getParentFile().mkdirs(); InputStream in = null; Reader reader = null; FileWriterWithEncoding writer = null; try { in = this.getClass().getResourceAsStream(templateResourcePath); reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); writer = new FileWriterWithEncoding(outputFile, "UTF-8"); Velocity.evaluate(context, writer, this.getClass().getSimpleName(), reader); writer.close(); reader.close(); in.close(); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(reader); IOUtils.closeQuietly(in); } } private void extractHtmlExternalResFromThisJar(File htmlExternalResourceRootDir, String copyPath) { InputStream in = this.getClass().getResourceAsStream("/" + copyPath); File destFile = new File(htmlExternalResourceRootDir, copyPath); destFile.getParentFile().mkdirs(); try { FileUtils.copyInputStreamToFile(in, destFile); } catch (IOException e) { throw new RuntimeException(e); } } }
package claw; import claw.tatsu.common.CompilerDirective; import claw.tatsu.common.Context; import claw.tatsu.common.Target; import claw.tatsu.xcodeml.backend.OmniBackendDriver; import claw.wani.ClawConstant; import claw.wani.report.ClawTransformationReport; import claw.wani.x2t.configuration.Configuration; import claw.wani.x2t.translator.ClawTranslatorDriver; import org.apache.commons.cli.*; import xcodeml.util.XmOption; import java.io.File; /** * ClawX2T is the entry point of any CLAW XcodeML/F translation. * * @author clementval */ public class ClawX2T { private static final String ERR_INTERNAL = "internal"; /** * Print an error message an abort. * * @param filename Filename in which error occurred. * @param lineNumber Line number of the error, if known. * @param charPos Character position of the error, if known. * @param msg Error message. */ private static void error(String filename, int lineNumber, int charPos, String msg) { StringBuilder errorStr = new StringBuilder(); errorStr.append(filename).append(":"); if(lineNumber > 0) { errorStr.append(lineNumber).append(":"); } if(charPos > 0) { errorStr.append(lineNumber).append(":"); } errorStr.append(msg); System.err.println(errorStr); System.exit(1); } /** * Print program usage. */ private static void usage() { Options options = prepareOptions(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("clawfc", options); System.exit(1); } /** * List all directive target available for code generation. */ private static void listTarget() { System.out.println("- CLAW available targets -"); for(String t : Target.availableTargets()) { System.out.println(" - " + t); } } /** * List all directive directive language available for code generation. */ private static void listDirectiveLanguage() { System.out.println("- CLAW directive directive language -"); for(String d : CompilerDirective.availableDirectiveLanguage()) { System.out.println(" - " + d); } } /** * Prepare the set of available options. * * @return Options object. */ private static Options prepareOptions() { Options options = new Options(); options.addOption("h", "help", false, "display program usage."); options.addOption("l", false, "suppress line directive in decompiled code."); options.addOption("cp", "config-path", true, "specify the configuration directory"); options.addOption("c", "config", true, "specify the configuration for the translator."); options.addOption("s", "schema", true, "specify the XSD schema location to validate the configuration."); options.addOption("t", "target", true, "specify the target for the code transformation."); options.addOption("dir", "directive", true, "list all directive directive language available for code generation."); options.addOption("d", "debug", false, "enable output debug message."); options.addOption("f", true, "specify FORTRAN decompiled output file."); options.addOption("w", true, "number of character per line in decompiled code."); options.addOption("o", true, "specify XcodeML/F output file."); options.addOption("M", true, "specify where to search for .xmod files"); options.addOption("tl", "target-list", false, "list all target available for code transformation."); options.addOption("dl", "directive-list", false, "list all available directive language to be generated."); options.addOption("sc", "show-config", false, "display the current configuration."); options.addOption("fp", "force-pure", false, "exit the translator if a PURE subroutine/function " + "has to be transformed."); options.addOption("r", "report", true, "generate the transformation report."); options.addOption("m", "model-config", true, "specify a model configuration for SCA transformation"); options.addOption("x", true, "override configuration option. Higher priority over base " + "configuration and user configuration."); options.addOption("ap", "add-paren", false, "Force backend to add parenthesis in binary mathematical binary " + "operation."); return options; } /** * Parse the arguments passed to the program. * * @param args Arguments passed to the program. * @return Parsed command line object. */ private static CommandLine processCommandArgs(String[] args) { try { Options options = prepareOptions(); CommandLineParser parser = new DefaultParser(); return parser.parse(options, args); } catch(ParseException pex) { error(ERR_INTERNAL, 0, 0, pex.getMessage()); return null; } } /** * Main point of entry of the program. * * @param args Arguments of the program. * @throws Exception if translation failed. */ public static void main(String[] args) throws Exception { String input; String xcmlOutput; String targetLangOutput; String targetOption; String directiveOption; String configurationFile; String configurationPath; String modelConfiguration = null; int maxColumns = 0; CommandLine cmd = processCommandArgs(args); // Help option if(cmd.hasOption("h")) { usage(); return; } // Display target list option if(cmd.hasOption("tl")) { listTarget(); return; } // Display directive list option if(cmd.hasOption("dl")) { listDirectiveLanguage(); return; } // Target option targetOption = cmd.getOptionValue("t"); // Directive option directiveOption = cmd.getOptionValue("dir"); // Suppressing line directive option if(cmd.hasOption("l")) { XmOption.setIsSuppressLineDirective(true); } // Debug option if(cmd.hasOption("d")) { XmOption.setDebugOutput(true); } // XcodeML/F output file option xcmlOutput = cmd.getOptionValue("o"); // FORTRAN output file option targetLangOutput = cmd.getOptionValue("f"); if(cmd.hasOption("w")) { maxColumns = Integer.parseInt(cmd.getOptionValue("w")); } configurationFile = cmd.getOptionValue("c"); configurationPath = cmd.getOptionValue("cp"); // Check that configuration path exists if(configurationPath == null) { error(ERR_INTERNAL, 0, 0, "Configuration path missing."); return; } // Check that configuration file exists if(configurationFile != null) { File configFile = new File(configurationFile); if(!configFile.exists()) { error(ERR_INTERNAL, 0, 0, "Configuration file not found: " + configurationFile); } } // Check if there is a model configuration and if file exists if(cmd.hasOption("m")) { modelConfiguration = cmd.getOptionValue("m"); File modelConfig = new File(modelConfiguration); if(!modelConfig.exists()) { error(ClawConstant.ERROR_PREFIX_INTERNAL, 0, 0, "Model configuration file not found: " + modelConfiguration); } } // --show-configuration option if(cmd.hasOption("sc")) { Configuration.get().load(configurationPath, configurationFile, modelConfiguration, targetOption, directiveOption, maxColumns); Configuration.get().displayConfig(); return; } // Get the input XcodeML file to transform if(cmd.getArgs().length == 0) { input = null; } else { input = cmd.getArgs()[0]; } // Read the configuration file try { Configuration.get().load(configurationPath, configurationFile, modelConfiguration, targetOption, directiveOption, maxColumns); } catch(Exception ex) { error(ERR_INTERNAL, 0, 0, ex.getMessage()); return; } // Module search path options if(cmd.hasOption("M")) { for(String value : cmd.getOptionValues("M")) { Context.get().getModuleCache().addSearchPath(value); } } // Override some configuration value. if(cmd.hasOption("x")) { for(String keyValue : cmd.getOptionValues("x")) { String key = keyValue.substring(0, keyValue.indexOf(":")); String value = keyValue.substring(keyValue.indexOf(":")+1); Configuration.get().overrideConfigurationParameter(key, value); } } // Force pure option if(cmd.hasOption("fp")) { Configuration.get().setForcePure(); } // Add parenthesis option if(cmd.hasOption("ap")) { XmOption.setAddPar(true); } ClawTranslatorDriver translatorDriver = new ClawTranslatorDriver(input, xcmlOutput); translatorDriver.analyze(); translatorDriver.transform(); translatorDriver.flush(); // Produce report (unless we've used the Python driver) if(cmd.hasOption("r")) { ClawTransformationReport report = new ClawTransformationReport(cmd.getOptionValue("r")); report.generate(args, translatorDriver); } // Decompile XcodeML/F to target language OmniBackendDriver backend; if(Configuration.get().getCurrentTarget() == Target.FPGA) { // TODO remove when supported error(xcmlOutput, 0, 0, "FPGA target is not supported yet"); backend = new OmniBackendDriver(OmniBackendDriver.Lang.C); } else { backend = new OmniBackendDriver(OmniBackendDriver.Lang.FORTRAN); } if(xcmlOutput == null) { // XcodeML output not written to file. Use pipe. if(!backend.decompile(targetLangOutput, translatorDriver.getTranslationUnit(), maxColumns, XmOption.isSuppressLineDirective())) { error(targetLangOutput, 0, 0, "Unable to decompile XcodeML to Fortran"); } } else { if(!backend.decompileFromFile(targetLangOutput, xcmlOutput, maxColumns, XmOption.isSuppressLineDirective())) { error(xcmlOutput, 0, 0, "Unable to decompile XcodeML to Fortran"); } } } }
package ptrman.levels.retina; import org.apache.commons.math3.linear.ArrayRealVector; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.apache.commons.math3.stat.regression.SimpleRegression; import ptrman.Datastructures.Vector2d; import ptrman.bpsolver.HardParameters; import ptrman.bpsolver.Parameters; import ptrman.levels.retina.helper.SpatialListMap2d; import ptrman.math.ArrayRealVectorHelper; import ptrman.misc.Assert; import java.util.*; import static java.util.Collections.sort; import static ptrman.math.ArrayRealVectorHelper.*; import static ptrman.math.Math.getRandomElements; // TODO< remove detectors which are removable which have a activation less than <constant> * sumofAllActivations > /** * detects lines * * forms line hypothesis and tries to strengthen it * uses the method of the least squares to fit the potential lines * each line detector either will survive or decay if it doesn't receive enought fitting points * */ public class ProcessD implements IProcess { public void preSetupSet(double maximalDistanceOfPositions) { this.maximalDistanceOfPositions = maximalDistanceOfPositions; } public void set(Queue<ProcessA.Sample> inputSampleQueue) { this.inputSampleQueue = inputSampleQueue; } public List<RetinaPrimitive> getResultRetinaPrimitives() { return resultRetinaPrimitives; } private static class LineDetectorWithMultiplePoints { public List<ArrayRealVector> cachedSamplePositions; public List<Integer> integratedSampleIndices; public double m, n; public double mse = 0.0f; public boolean isLocked = false; // has the detector received enought activation so it stays? public int commonObjectId = -1; public boolean doesContainSampleIndex(int index) { return integratedSampleIndices.contains(index); } public double getActivation() { return integratedSampleIndices.size() + (Parameters.getProcessdMaxMse() - mse)*Parameters.getProcessdLockingActivationScale(); } public boolean isCommonObjectIdValid() { return commonObjectId != -1; } public ArrayRealVector projectPointOntoLine(ArrayRealVector point) { if( isYAxisSingularity() ) { // call isn't allowed throw new RuntimeException("internal error"); //return projectPointOntoLineForSingular(point); } else { return projectPointOntoLineForNonsingular(point); } } /*private Vector2d<Float> projectPointOntoLineForSingular(Vector2d<Float> point) { return new Vector2d<Float>(point.x, horizontalOffset); }*/ public ArrayRealVector projectPointOntoLineForNonsingular(ArrayRealVector point) { ArrayRealVector lineDirection = getNormalizedDirection(); ArrayRealVector diffFromAToPoint = point.subtract(new ArrayRealVector(new double[]{0.0f, n})); double dotResult = lineDirection.dotProduct(diffFromAToPoint); return new ArrayRealVector(new double[]{0.0f, n}).add(getScaled(lineDirection, dotResult)); } private ArrayRealVector getNormalizedDirection() { if( isYAxisSingularity() ) { throw new RuntimeException("internal error"); } else { return ArrayRealVectorHelper.normalize(new ArrayRealVector(new double[]{1.0f, m})); } } // TODO< just simply test flag > public boolean isYAxisSingularity() { return Double.isInfinite(m); } public double getHorizontalOffset(List<ProcessA.Sample> samples) { Assert.Assert(isYAxisSingularity(), ""); int sampleIndex = integratedSampleIndices.get(0); return samples.get(sampleIndex).position.getDataRef()[0]; } public double getLength() { List<ArrayRealVector> sortedSamplePositions = getSortedSamplePositions(this); Assert.Assert(sortedSamplePositions.size() >= 2, "samples size must be equal or greater than two"); // it doesn't care if the line is singuar or not, the distance is always the length final ArrayRealVector lastSamplePosition = sortedSamplePositions.get(sortedSamplePositions.size()-1); final ArrayRealVector firstSamplePosition = sortedSamplePositions.get(0); return lastSamplePosition.subtract(firstSamplePosition).getNorm(); } } private static class LineDetectors { public LineDetectors(List<LineDetectorWithMultiplePoints> lineDetectors) { this.lineDetectors = lineDetectors; } public List<LineDetectorWithMultiplePoints> lineDetectors; } @Override public void setImageSize(final Vector2d<Integer> imageSize) { this.imageSize = imageSize; } @Override public void setup() { Assert.Assert((imageSize.x % gridcellSize) == 0, ""); Assert.Assert((imageSize.y % gridcellSize) == 0, ""); // small size hack because else the map is accessed out of range accelerationMap = new SpatialListMap2d<>(new Vector2d<>(imageSize.x + gridcellSize, imageSize.y + gridcellSize), gridcellSize); } @Override public void processData() { // take samples from queue and put into array List<ProcessA.Sample> samplesAsList = new ArrayList<>(); final int inputSampleQueueSize = inputSampleQueue.size(); for( int i = 0; i < inputSampleQueueSize; i++ ) { samplesAsList.add(inputSampleQueue.poll()); } resultRetinaPrimitives = detectLines(samplesAsList); } /** * * \param samples doesn't need to be filtered for endo/exosceleton points, it does it itself * * \return only the surviving line segments */ private List<RetinaPrimitive> detectLines(List<ProcessA.Sample> samples) { List<LineDetectorWithMultiplePoints> multiplePointsLineDetector = new ArrayList<>(); final List<ProcessA.Sample> workingSamples = samples; if( workingSamples.isEmpty() ) { return new ArrayList<>(); } // we store all samples inside the acceleration datastructure int sampleIndex = 0; // NOTE< index in endosceletonPoint / workingSamples > for( final ProcessA.Sample iterationSample : workingSamples ) { putSampleIndexAtPositionIntoAccelerationDatastructure(arrayRealVectorToInteger(iterationSample.position, EnumRoundMode.DOWN), sampleIndex); sampleIndex++; } int numberOfTries = (int)( samples.size() * HardParameters.ProcessD.SAMPLES_NUMBER_OF_TRIES_MULTIPLIER); // TODO< imagesize > double maxLength = Math.sqrt(100.0f*100.0f + 80.0f*80.0f); final int numberOfMaximalLengthCycles = 5; Deque<LineDetectors> lineDetectorsRecords = new ArrayDeque<>(); for( int lengthCycle = 0; lengthCycle < numberOfMaximalLengthCycles; lengthCycle++ ) { // pick out a random cell and pick out a random sample in it and try to build a (small) line out of it for( int tryCounter = 0; tryCounter < numberOfTries; tryCounter++ ) { List<Integer> keys = new ArrayList<>(accelerationMapCellUsed.keySet()); final int randomCellPositionIndex = keys.get(random.nextInt(keys.size())); final Vector2d<Integer> randomCellPosition = new Vector2d<>(randomCellPositionIndex % accelerationMap.getWidth(), randomCellPositionIndex / accelerationMap.getWidth()); // pick out three points at random // TODO< better strategy > List<Integer> chosenCandidateSampleIndices = new ArrayList<>(); { final List<Integer> allCandidateSampleIndices = getAllIndicesOfSamplesOfCellAndNeightborCells(randomCellPosition); if( allCandidateSampleIndices.size() < 3 ) { continue; } final List<Integer> allCandidateSampleIndicesChosenIndices = getRandomElements(allCandidateSampleIndices.size(), 3, random); for( final int iterationChosenIndex : allCandidateSampleIndicesChosenIndices ) { final int currentChosenCandidateSampleIndex = allCandidateSampleIndices.get(iterationChosenIndex); chosenCandidateSampleIndices.add(currentChosenCandidateSampleIndex); } } final List<ProcessA.Sample> selectedSamples = getSamplesByIndices(workingSamples, chosenCandidateSampleIndices); final boolean doAllSamplesHaveId = doAllSamplesHaveObjectId(selectedSamples); if( !doAllSamplesHaveId ) { continue; } // check if object ids are the same final boolean objectIdsOfSamplesTheSame = areObjectIdsTheSameOfSamples(selectedSamples); if( !objectIdsOfSamplesTheSame ) { continue; } final List<ArrayRealVector> positionsOfSamples = getPositionsOfSamples(selectedSamples); final ArrayRealVector averageOfPositionsOfSamples = getAverage(positionsOfSamples); final double currentMaximalDistanceOfPositions = getMaximalDistanceOfPositionsTo(positionsOfSamples, averageOfPositionsOfSamples); if( currentMaximalDistanceOfPositions > Math.min(maximalDistanceOfPositions, maxLength*0.5f) ) { // one point is too far away from the average position, so this line is not formed continue; } // else we are here final RegressionForLineResult regressionResult = calcRegressionForPoints(positionsOfSamples); if( regressionResult.mse > Parameters.getProcessdMaxMse() ) { continue; } // else we are here // create new line detector LineDetectorWithMultiplePoints createdLineDetector = new LineDetectorWithMultiplePoints(); createdLineDetector.integratedSampleIndices = chosenCandidateSampleIndices; createdLineDetector.cachedSamplePositions = positionsOfSamples; Assert.Assert(areObjectIdsTheSameOfSamples(selectedSamples), ""); createdLineDetector.commonObjectId = selectedSamples.get(0).objectId; Assert.Assert(createdLineDetector.integratedSampleIndices.size() >= 2, ""); // the regression mse is not defined if it are only two points boolean addCreatedLineDetector = false; if( createdLineDetector.integratedSampleIndices.size() == 2 ) { createdLineDetector.mse = 0.0f; createdLineDetector.n = regressionResult.n; createdLineDetector.m = regressionResult.m; addCreatedLineDetector = true; } else { if( regressionResult.mse < Parameters.getProcessdMaxMse() ) { createdLineDetector.mse = regressionResult.mse; createdLineDetector.n = regressionResult.n; createdLineDetector.m = regressionResult.m; addCreatedLineDetector = true; } } if( createdLineDetector.getLength() > maxLength ) { continue; } // else we are here if( addCreatedLineDetector ) { multiplePointsLineDetector.add(createdLineDetector); } } // compile statistics SummaryStatistics lineLengthStatistics = new SummaryStatistics(); for( LineDetectorWithMultiplePoints currentLineDetectorWithMultipleLines : multiplePointsLineDetector ) { double length = currentLineDetectorWithMultipleLines.getLength(); lineLengthStatistics.addValue(length); } final double currentLineLengthMean = lineLengthStatistics.getMean(); final double newMaxLength = currentLineLengthMean * HardParameters.ProcessD.LENGTH_MEAN_MULTIPLIER; System.out.println("length mean " + Double.toString(currentLineLengthMean)); maxLength = Math.min(maxLength, newMaxLength); final double finalizedMaxLength = maxLength; lineDetectorsRecords.push(new LineDetectors(copyLineDetectors(multiplePointsLineDetector))); if( currentLineLengthMean < HardParameters.ProcessD.MINIMAL_LINESEGMENTLENGTH ) { break; } // throw out multiplePointsLineDetector.removeIf(candidate -> candidate.getLength() > finalizedMaxLength); if( multiplePointsLineDetector.size() == 0 ) { break; } } multiplePointsLineDetector.clear(); // add last n records for( int lastNRecordsI = 0; lastNRecordsI < HardParameters.ProcessD.LAST_RECORDS_FROM_LINECANDIDATES_STACK; lastNRecordsI++ ) { if( lineDetectorsRecords.isEmpty() ) { break; } multiplePointsLineDetector.addAll(lineDetectorsRecords.pop().lineDetectors); } // split the detectors into one or many lines List<RetinaPrimitive> resultSingleDetectors = splitDetectorsIntoLines(multiplePointsLineDetector); return resultSingleDetectors; } private static List<LineDetectorWithMultiplePoints> copyLineDetectors(final List<LineDetectorWithMultiplePoints> lineDetectors) { List<LineDetectorWithMultiplePoints> result = new ArrayList<>(); for( final LineDetectorWithMultiplePoints iterationLineDetector : lineDetectors ) { result.add(iterationLineDetector); } return result; } private static boolean doAllSamplesHaveObjectId(final List<ProcessA.Sample> samples) { for( final ProcessA.Sample iterationSamples : samples ) { if( !iterationSamples.isObjectIdValid() ) { return false; } } return true; } private static boolean areObjectIdsTheSameOfSamples(final List<ProcessA.Sample> samples) { Assert.Assert(samples.get(0).isObjectIdValid(), ""); final int objectId = samples.get(0).objectId; for( final ProcessA.Sample iterationSamples : samples ) { Assert.Assert(iterationSamples.isObjectIdValid(), ""); if( iterationSamples.objectId != objectId ) { return false; } } return true; } private static List<ArrayRealVector> getPositionsOfSamples(final List<ProcessA.Sample> samples) { List<ArrayRealVector> resultPositions = new ArrayList<>(); for( final ProcessA.Sample iterationSample : samples ) { resultPositions.add(iterationSample.position); } return resultPositions; } private static double getMaximalDistanceOfPositionsTo(final List<ArrayRealVector> positions, final ArrayRealVector comparePosition) { double maxDistance = 0.0; for( final ArrayRealVector iterationPosition : positions) { final double currentDistance = iterationPosition.getDistance(comparePosition); maxDistance = java.lang.Math.max(maxDistance, currentDistance); } return maxDistance; } private List<Vector2d<Integer>> getUnionOfCellsByPositions(final List<ArrayRealVector> positions) { Set<Vector2d<Integer>> tempSet = new HashSet<>(); for( final ArrayRealVector iterationPosition : positions ) { final Vector2d<Integer> positionAsInteger = arrayRealVectorToInteger(iterationPosition, EnumRoundMode.DOWN); final Vector2d<Integer> cellPosition = new Vector2d<>(positionAsInteger.x / gridcellSize, positionAsInteger.y / gridcellSize); tempSet.add(cellPosition); } List<Vector2d<Integer>> resultList = new ArrayList<>(); resultList.addAll(tempSet); return resultList; } private List<Integer> getAllIndicesOfSamplesOfCellAndNeightborCells(final Vector2d<Integer> centerCellPosition) { List<Integer> result = new ArrayList<>(); for( int y = centerCellPosition.y - 1; y < centerCellPosition.y + 1; y++ ) { for( int x = centerCellPosition.x - 1; x < centerCellPosition.x + 1; x++ ) { if( !accelerationMap.inBounds(new Vector2d<>(x, y)) ) { continue; } final List<Integer> listAtPosition = accelerationMap.readAt(x, y); if( listAtPosition != null ) { result.addAll(listAtPosition); } } } return result; } private static List<ProcessA.Sample> getSamplesByIndices(final List<ProcessA.Sample> samples, final List<Integer> indices) { List<ProcessA.Sample> resultPositions = new ArrayList<>(); for( final int index : indices ) { resultPositions.add(samples.get(index)); } return resultPositions; } private void putSampleIndexAtPositionIntoAccelerationDatastructure(final Vector2d<Integer> position, final int sampleIndex) { final Vector2d<Integer> cellPosition = new Vector2d<>(position.x / gridcellSize, position.y /gridcellSize); if( accelerationMap.readAt(cellPosition.x, cellPosition.y) == null ) { Assert.Assert(!accelerationMapCellUsed.containsKey(cellPosition.x + cellPosition.y * accelerationMap.getWidth()), ""); accelerationMap.setAt(cellPosition.x, cellPosition.y, new ArrayList<>(Arrays.asList(new Integer[]{sampleIndex}))); accelerationMapCellUsed.put(cellPosition.x + cellPosition.y * accelerationMap.getWidth(), true); } else { Assert.Assert(accelerationMapCellUsed.containsKey(cellPosition.x + cellPosition.y * accelerationMap.getWidth()), ""); List<Integer> indices = accelerationMap.readAt(cellPosition.x, cellPosition.y); indices.add(sampleIndex); } } /** * works by counting the "overlapping" pixel coordinates, chooses the axis with the less overlappings * */ private static RegressionForLineResult calcRegressionForPoints(List<ArrayRealVector> positions) { SimpleRegression regression; int overlappingPixelsOnX, overlappingPixelsOnY; RegressionForLineResult regressionResultForLine; overlappingPixelsOnX = calcCountOfOverlappingPixelsForAxis(positions, EnumAxis.X); overlappingPixelsOnY = calcCountOfOverlappingPixelsForAxis(positions, EnumAxis.Y); regression = new SimpleRegression(); regressionResultForLine = new RegressionForLineResult(); if( overlappingPixelsOnX <= overlappingPixelsOnY ) { // regression on x axis for( ArrayRealVector iterationPosition : positions ) { regression.addData(iterationPosition.getDataRef()[0], iterationPosition.getDataRef()[1]); } regressionResultForLine.mse = regression.getMeanSquareError(); regressionResultForLine.n = regression.getIntercept(); regressionResultForLine.m = regression.getSlope(); } else { // regression on y axis // we switch x and y and calculate m and n from the regression result for( ArrayRealVector iterationPosition : positions ) { regression.addData(iterationPosition.getDataRef()[1], iterationPosition.getDataRef()[0]); } // calculate m and n double regressionM = regression.getSlope(); double regressionN = regression.getIntercept(); double m = 1.0f/regressionM; ArrayRealVector pointOnRegressionLine = new ArrayRealVector(new double[]{regressionN, 0.0}); double n = pointOnRegressionLine.getDataRef()[1] - m * pointOnRegressionLine.getDataRef()[0]; regressionResultForLine.mse = regression.getMeanSquareError(); regressionResultForLine.n = n; regressionResultForLine.m = m; } return regressionResultForLine; } private static int calcCountOfOverlappingPixelsForAxis(List<ArrayRealVector> positions, EnumAxis axis) { double maxCoordinatOnAxis = getMaximalCoordinateForPoints(positions, axis); int arraysizeOfDimension = Math.round((float)maxCoordinatOnAxis)+1; int[] dimensionCounter = new int[arraysizeOfDimension]; for( ArrayRealVector iterationPosition : positions ) { int dimensionCounterIndex = Math.round((float)Helper.getAxis(iterationPosition, axis)); dimensionCounter[dimensionCounterIndex]++; } // count the "rows" where the count is greater than 1 int overlappingCounter = 0; for( int arrayI = 0; arrayI < dimensionCounter.length; arrayI++ ) { if( dimensionCounter[arrayI] > 1 ) { overlappingCounter++; } } return overlappingCounter; } // used to calculate the arraysize private static double getMaximalCoordinateForPoints(List<ArrayRealVector> positions, EnumAxis axis) { double max = 0; for( ArrayRealVector iterationPosition : positions ) { max = Math.max(max, Helper.getAxis(iterationPosition, axis)); } return max; } private static List<RetinaPrimitive> splitDetectorsIntoLines(List<LineDetectorWithMultiplePoints> lineDetectorsWithMultiplePoints) { List<RetinaPrimitive> result; result = new ArrayList<>(); for( LineDetectorWithMultiplePoints iterationDetector : lineDetectorsWithMultiplePoints ) { result.addAll(splitDetectorIntoLines(iterationDetector)); } return result; } private static List<ArrayRealVector> getSortedSamplePositions(LineDetectorWithMultiplePoints lineDetectorWithMultiplePoints) { List<ArrayRealVector> samplePositions = new ArrayList<>(); if( lineDetectorWithMultiplePoints.isYAxisSingularity() ) { for( ArrayRealVector iterationSamplePosition : lineDetectorWithMultiplePoints.cachedSamplePositions ) { samplePositions.add(iterationSamplePosition); } sort(samplePositions, new VectorComperatorByAxis(EnumAxis.Y)); } else { // project for( ArrayRealVector iterationSamplePosition : lineDetectorWithMultiplePoints.cachedSamplePositions ) { ArrayRealVector projectedSamplePosition = lineDetectorWithMultiplePoints.projectPointOntoLine(iterationSamplePosition); samplePositions.add(projectedSamplePosition); } sort(samplePositions, new VectorComperatorByAxis(EnumAxis.X)); } return samplePositions; } private static List<RetinaPrimitive> splitDetectorIntoLines(LineDetectorWithMultiplePoints lineDetectorWithMultiplePoints) { List<ArrayRealVector> sortedSamplePositions = getSortedSamplePositions(lineDetectorWithMultiplePoints); if( lineDetectorWithMultiplePoints.isYAxisSingularity() ) { return clusterPointsFromLinedetectorToLinedetectors(lineDetectorWithMultiplePoints.commonObjectId, sortedSamplePositions, EnumAxis.Y); } else { return clusterPointsFromLinedetectorToLinedetectors(lineDetectorWithMultiplePoints.commonObjectId, sortedSamplePositions, EnumAxis.X); } } private static List<RetinaPrimitive> clusterPointsFromLinedetectorToLinedetectors(final int objectId, final List<ArrayRealVector> pointPositions, final EnumAxis axis) { List<RetinaPrimitive> resultSingleLineDetectors = new ArrayList<>(); boolean nextIsNewLineStart = true; ArrayRealVector lineStartPosition = pointPositions.get(0); double lastAxisPosition = Helper.getAxis(pointPositions.get(0), axis); for( ArrayRealVector iterationPoint : pointPositions ) { if( nextIsNewLineStart ) { lineStartPosition = iterationPoint; lastAxisPosition = Helper.getAxis(iterationPoint, axis); nextIsNewLineStart = false; continue; } // else we are here if( Helper.getAxis(iterationPoint, axis) - lastAxisPosition < HardParameters.ProcessD.LINECLUSTERINGMAXDISTANCE ) { lastAxisPosition = Helper.getAxis(iterationPoint, axis); } else { // form a new line RetinaPrimitive newPrimitive = RetinaPrimitive.makeLine(SingleLineDetector.createFromFloatPositions(lineStartPosition, iterationPoint)); newPrimitive.objectId = objectId; resultSingleLineDetectors.add(newPrimitive); nextIsNewLineStart = true; } } // form a new line for the last point ArrayRealVector lastPoint = pointPositions.get(pointPositions.size()-1); if( !nextIsNewLineStart && Helper.getAxis(lastPoint, axis) - lastAxisPosition < HardParameters.ProcessD.LINECLUSTERINGMAXDISTANCE ) { RetinaPrimitive newPrimitive = RetinaPrimitive.makeLine(SingleLineDetector.createFromFloatPositions(lineStartPosition, lastPoint)); newPrimitive.objectId = objectId; resultSingleLineDetectors.add(newPrimitive); } return resultSingleLineDetectors; } private static List<ProcessA.Sample> filterEndosceletonPoints(List<ProcessA.Sample> samples) { List<ProcessA.Sample> filtered; filtered = new ArrayList<>(); for( ProcessA.Sample iterationSample : samples ) { if( iterationSample.type == ProcessA.Sample.EnumType.ENDOSCELETON ) { filtered.add(iterationSample); } } return filtered; } // TODO< belongs into dedicated helper > static private class Helper { private static boolean isDistanceBetweenPositionsBelow(ArrayRealVector a, ArrayRealVector b, double maxDistance) { return a.subtract(b).getNorm() < maxDistance; } private static double getAxis(ArrayRealVector vector, EnumAxis axis) { if( axis == EnumAxis.X ) { return vector.getDataRef()[0]; } else { return vector.getDataRef()[1]; } } } private static class VectorComperatorByAxis implements Comparator<ArrayRealVector> { public VectorComperatorByAxis(EnumAxis axis) { this.axis = axis; } @Override public int compare(ArrayRealVector a, ArrayRealVector b) { if( Helper.getAxis(a, axis) > Helper.getAxis(b, axis) ) { return 1; } return -1; } private final EnumAxis axis; } private static class RegressionForLineResult { public double mse; public double m, n; } private enum EnumAxis { X, Y } private Vector2d<Integer> imageSize; private int gridcellSize = 8; private Random random = new Random(); // each cell contains the incides of the points/samples inside the accelerationMap private SpatialListMap2d<Integer> accelerationMap; private Map<Integer, Boolean> accelerationMapCellUsed = new HashMap<>(); private List<RetinaPrimitive> resultRetinaPrimitives; private double maximalDistanceOfPositions; private Queue<ProcessA.Sample> inputSampleQueue; }
package seedu.ezdo.ui; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Logger; import org.controlsfx.control.StatusBar; import com.google.common.eventbus.Subscribe; import javafx.fxml.FXML; import javafx.scene.control.Tooltip; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Region; import seedu.ezdo.commons.core.LogsCenter; import seedu.ezdo.commons.events.model.EzDoChangedEvent; import seedu.ezdo.commons.events.storage.EzDoDirectoryChangedEvent; import seedu.ezdo.commons.util.FxViewUtil; /** * A ui for the status bar that is displayed at the footer of the application. */ public class StatusBarFooter extends UiPart<Region> { private static final Date CURRENT_DATE = new Date(); private static final String MESSAGE_SET_SAVE_LOCATION = "Setting save location to "; private static final String MESSAGE_LAST_UPDATED = "Last Updated: "; private static final String MESSAGE_SET_LAST_UPDATED = "Setting last updated status to "; private static final String STATUS_BAR_DATE_FORMAT = "dd/MM/YYYY H:mm:ss"; private static final String MESSAGE_NOT_UPDATED = "Not updated yet in this session"; private static final String MESSAGE_SAVE_LOCATION_TOOLTIP = "ezDo Directory Box\nDisplays the directory of ezDo data file."; private static final String MESSAGE_STATUS_BAR_TOOLTIP = "Status Box\nDisplays when ezDo data file is last updated."; private static final Logger logger = LogsCenter.getLogger(StatusBarFooter.class); @FXML private StatusBar syncStatus; @FXML private StatusBar saveLocationStatus; private static final String FXML = "StatusBarFooter.fxml"; public StatusBarFooter(AnchorPane placeHolder, String saveLocation) { super(FXML); syncStatus.setTooltip(new Tooltip(MESSAGE_STATUS_BAR_TOOLTIP)); saveLocationStatus.setTooltip(new Tooltip(MESSAGE_SAVE_LOCATION_TOOLTIP)); addToPlaceholder(placeHolder); setSyncStatus(MESSAGE_NOT_UPDATED); setSaveLocation(saveLocation); registerAsAnEventHandler(this); } private void addToPlaceholder(AnchorPane placeHolder) { FxViewUtil.applyAnchorBoundaryParameters(getRoot(), 0.0, 0.0, 0.0, 0.0); placeHolder.getChildren().add(getRoot()); } private void setSaveLocation(String location) { this.saveLocationStatus.setText(location); } private void setSyncStatus(String status) { this.syncStatus.setText(status); } @Subscribe public void handleEzDoChangedEvent(EzDoChangedEvent ezce) { SimpleDateFormat df = new SimpleDateFormat(STATUS_BAR_DATE_FORMAT); String lastUpdated = df.format(CURRENT_DATE); logger.info(LogsCenter.getEventHandlingLogMessage(ezce, MESSAGE_SET_LAST_UPDATED + lastUpdated)); setSyncStatus(MESSAGE_LAST_UPDATED + lastUpdated); } //@@author A0139248X /** * Updates the status bar footer to show the new ezdo storage file path and the last updated time */ @Subscribe public void handleEzDoDirectoryChangedEvent(EzDoDirectoryChangedEvent ezce) { String lastUpdated = CURRENT_DATE.toString(); logger.info(LogsCenter.getEventHandlingLogMessage(ezce, MESSAGE_SET_LAST_UPDATED + lastUpdated)); logger.info(LogsCenter.getEventHandlingLogMessage(ezce, MESSAGE_SET_SAVE_LOCATION + ezce.getPath())); setSyncStatus(MESSAGE_LAST_UPDATED + lastUpdated); setSaveLocation(ezce.getPath()); } }
package soot.jbco.util; import soot.Hierarchy; import soot.Scene; import soot.SootClass; import java.util.Collection; import java.util.List; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; /** * Utility class for convenient hierarchy checks. * * @since 07.02.18 */ public final class HierarchyUtils { private HierarchyUtils() { throw new IllegalAccessError(); } /** * Get whole tree of interfaces on {@code Scene} for class/interface. * * @param sc class or interface to get all its interfaces * @return all interfaces on {@code Scene} for class or interface */ public static List<SootClass> getAllInterfacesOf(SootClass sc) { Hierarchy hierarchy = Scene.v().getActiveHierarchy(); Stream<SootClass> superClassInterfaces = sc.isInterface() ? Stream.empty() : hierarchy.getSuperclassesOf(sc) .stream() .map(HierarchyUtils::getAllInterfacesOf) .flatMap(Collection::stream); Stream<SootClass> directInterfaces = Stream.concat(sc.getInterfaces().stream(), sc.getInterfaces().stream() .map(HierarchyUtils::getAllInterfacesOf) .flatMap(Collection::stream)); return Stream.concat(superClassInterfaces, directInterfaces).collect(toList()); } }
package tdanford.ideals; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.collections.api.list.ImmutableList; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.factory.Lists; import com.google.common.base.Preconditions; public class GroebnerBasis<K, F extends Ring<K, K>, PR extends PolynomialRing<K, F>> { private final PR polyRing; private final ImmutableList<Polynomial<K, F>> spec; private final MutableList<Polynomial<K, F>> basis; private final boolean reducingFinalBasis; public GroebnerBasis(final PR polyRing, final Iterable<Polynomial<K, F>> polys) { this.polyRing = polyRing; spec = Lists.immutable.ofAll(polys); basis = Lists.mutable.empty(); reducingFinalBasis = true; calculateBasis(); } public Iterable<Polynomial<K, F>> getBasis() { return basis; } private void calculateBasis() { final ArrayList<Polynomial<K, F>> building = new ArrayList<>(spec.castToList()); if ((new HashSet<>(building)).size() != building.size()) { throw new IllegalArgumentException(String.format("Building set %s contains duplicates", building)); } int start = 0; Set<Polynomial<K, F>> toAdjoin = new HashSet<>(); do { toAdjoin.removeAll(building); building.addAll(toAdjoin); start += toAdjoin.size(); toAdjoin.clear(); System.out.println(String.format("%d: Building Set (%d): %s", start, building.size(), building)); for (int i = start; i < building.size(); i++) { for (int j = 0; j < i; j++) { final Polynomial<K, F> sPoly = building.get(i).sPolynomial(building.get(j)); final Polynomial<K, F> sRem = polyRing.div(sPoly, building).remainder; if (!sRem.isZero()) { System.out.println(String.format("\t%d,%d: %s", i, j, sPoly)); System.out.println(String.format("\t\t-> %s", sRem)); toAdjoin.add(sRem); } } } System.out.println(String.format("\tTo-adjoin set (%d): %s", toAdjoin.size(), toAdjoin)); } while (!toAdjoin.isEmpty()); final PolynomialSet<K, F> buildingSet = new PolynomialSet<>(building); basis.clear(); basis.addAllIterable(buildingSet); scaleLeadingCoefficientsToOne(); System.out.println(String.format("Intermediate basis: %s", basis)); System.out.println(String.format("No dups basis: %s", new HashSet<>(basis))); final Iterable<Polynomial<K, F>> cleared = clearDenominators(new HashSet<>(basis)); basis.clear(); basis.addAllIterable(cleared); if (reducingFinalBasis) { System.out.println("Reducing final set..."); int reduce = -1; final List<Term<K, F>> leadingTerms = basis.collect(Polynomial::leadingTerm); final List<String> leadingTermStrings = leadingTerms.stream().map(t -> t.renderString(polyRing.variables())).collect(toList()); System.out.println(String.format("Leading terms: %s", leadingTermStrings)); while ((reduce = findReduciblePolynomial(basis)) != -1) { basis.remove(reduce); } } System.out.println(String.format("Final basis: %s", basis)); } private Iterable<Polynomial<K, F>> clearDenominators(final Collection<Polynomial<K, F>> polys) { Preconditions.checkArgument(polys.size() > 0); return polys.stream() .map(this::clearDenominatorsOnPolynomial) .collect(toList()); } private Polynomial<K, F> clearDenominatorsOnPolynomial(final Polynomial<K, F> poly) { //System.out.println(String.format("Clearing: %s", poly)); if (polyRing.coefficientField() == Rationals.FIELD) { //System.out.println(String.format("\trational poly: %s", poly)); @SuppressWarnings("unchecked") final List<Rational> rationalCoeffs = (List<Rational>) poly.getCoefficients(); final long lcm = rationalCoeffs.stream().mapToLong(Rational::getDenominator).reduce(1, Rational::lcm); //System.out.println("\tLCM: " + lcm); return poly.scaleBy((K) new Rational(lcm, 1)); } else { //System.out.println(String.format("\tNon-rational poly: %s", poly)); return poly; } } private void scaleLeadingCoefficientsToOne() { basis.replaceAll(Polynomial::scaleToOne); } private int findReduciblePolynomial(final MutableList<Polynomial<K, F>> basis) { for (int i = 0; i < basis.size(); i++) { if (isReduciblePolynomial(basis.get(i), basis)) { return i; } } return -1; } private boolean isReduciblePolynomial( final Polynomial<K, F> poly, final MutableList<Polynomial<K, F>> basis ) { final Set<Term<K, F>> leadingTerms = basis.collectIf( p -> !p.equals(poly), Polynomial::leadingTerm ).toSet(); boolean match = poly.anyTermMatches(t -> leadingTerms.stream().anyMatch(lt -> lt.divides(t))); //final String ltString = leadingTerms.stream().map(t -> t.renderString(polyRing.variables())).collect(joining(", ")); //System.out.println(String.format("%s: %s \n\tin LTS %s", match, poly, ltString)); return match; } }
package Sprites; import javafx.scene.*; import javafx.scene.image.*; import tankattack.*; /** * * @author Ruslan */ public abstract class Sprite extends Group { public World world; public static String imageName; public ImageView image; private double width; private double height; private HealthBar healthBar; public HealthBar getHealthBar() { return healthBar; } public void setHealthBar(HealthBar bar) { this.healthBar = bar; } public void setImage(Image i) { this.image.setImage(i); } public Sprite(String nameImage, double x, double y, World world) { this.world = world; this.initImageAndSize(nameImage); this.setTranslateX( x - width/2 ); this.setTranslateY( y - height/2 ); this.initSetWorld(world); } private void initSetWorld(World world) { if (world == null) { System.out.println("FORGOT TO SET WORLD, [new Sprite()]"); } else { world.addSprite(this); } } private void initImageAndSize(String nameImage) { this.image = new ImageView(); if (image == null) { System.out.println("Forgot to pass image into sprite being created!"); } this.image.setImage(new Image(getClass().getResourceAsStream(nameImage))); this.getChildren().add(this.image); this.width = this.image.getImage().getWidth(); this.height = this.image.getImage().getHeight(); } public void initHealthBar(double health, double width, double height, boolean isEnemy) { double HbarX,HbarY,HbarWidth,HbarHeight; HbarX = .15 * width(); HbarWidth = (.85 - .15) * width(); if (isEnemy) { HbarY = .1 * height(); } else { HbarY = .8 * height(); } HbarHeight = (.9 - .8) * height(); this.healthBar = new HealthBar(health, HbarX, HbarY, HbarWidth, HbarHeight); this.getChildren().add(healthBar); } public double height() { return this.height; } public double width() { return this.width; } public void setHeight(double height) { this.height = height; } public void setWidth(double width) { this.width = width; } public void checkForDeathAndReactAppropriately() { System.out.println("Calling checkForDeathAndReactAppropriately on a Sprite that doesn't support it."); } }
package com.pironet.tda; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Serializable; import java.lang.ref.SoftReference; /** * logfile content info object of log file thread dump information. * @author irockel */ public class LogFileContent implements Serializable { private String logFile; /** * stored as soft reference, as this content might get quite big. */ private transient SoftReference content; private transient StringBuffer contentBuffer; /** * Creates a new instance of LogFileContent */ public LogFileContent(String logFile) { setLogFile(logFile); } public String getLogfile() { return(logFile); } public void setLogFile(String value) { logFile = value; } public String toString() { return("Logfile"); } /** * get the content as string, it is stored as soft reference, * so it might be loaded from disk again, as the vm needed memory * after the last access to it. */ public String getContent() { if(contentBuffer == null) { if (content == null || content.get() == null) { readContent(); } return (((StringBuffer) content.get()).toString()); } else { return (contentBuffer.toString()); } } /** * append the given string to the content buffer for this logfile * @param append the string to append. */ public void appendToContentBuffer(String append) { if(contentBuffer == null) { contentBuffer = new StringBuffer(append); } else { contentBuffer.append("\n"); contentBuffer.append(append); } } /** * read the content in the soft reference object, currently used * StringBuffer to maintain 1.4 compability. Should be switched * to StringReader if switched to 1.5 for better performance as * synchronization is not needed here. */ private void readContent() { StringBuffer contentReader = new StringBuffer(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(getLogfile())); while(br.ready()) { contentReader.append(br.readLine()); contentReader.append("\n"); } } catch (IOException ex) { ex.printStackTrace(); contentReader.append("The Logfile unavailable! " + ex.getMessage()); } finally { try { br.close(); } catch (IOException ex) { ex.printStackTrace(); } } content = new SoftReference(contentReader); } }
package com.dumbster.smtp; import com.dumbster.smtp.action.*; import org.junit.*; import java.util.Iterator; import com.dumbster.smtp.MailMessage; import com.dumbster.smtp.mailstores.EMLMailStore; import com.dumbster.smtp.mailstores.RollingMailStore; import static org.junit.Assert.*; public class NewTestCasesTest { private MailMessage message; private ServerOptions options; @Before public void setup() { this.message = new MailMessageImpl(); } /* Message Formatting Utests */ // Tests initial capacity of header HashMap @Test public void testMaxHeaders() { message.addHeader("header1", "value1"); message.addHeader("header2", "value2"); message.addHeader("header3", "value3"); message.addHeader("header4", "value4"); message.addHeader("header5", "value5"); message.addHeader("header6", "value6"); message.addHeader("header7", "value7"); message.addHeader("header8", "value8"); message.addHeader("header9", "value9"); message.addHeader("header10", "value10"); Iterator<String> it = message.getHeaderNames(); int i = 0; while(it.hasNext()) { i++; it.next(); } assertEquals(10, i); } // Tests that HashMap increases capacity with addition of another header @Test public void testMaxHeadersPlus1() { message.addHeader("header1", "value1"); message.addHeader("header2", "value2"); message.addHeader("header3", "value3"); message.addHeader("header4", "value4"); message.addHeader("header5", "value5"); message.addHeader("header6", "value6"); message.addHeader("header7", "value7"); message.addHeader("header8", "value8"); message.addHeader("header9", "value9"); message.addHeader("header10", "value10"); message.addHeader("header11", "value11"); Iterator<String> it = message.getHeaderNames(); int i = 0; while(it.hasNext()) { i++; it.next(); } assertEquals(11, i); } /* Server Options Utests */ @Test public void testNegativePort() { String[] args = new String[]{"-1"}; options = new ServerOptions(args); assertEquals(-1, options.port); assertEquals(true, options.threaded); assertEquals(true, options.valid); assertEquals(RollingMailStore.class, options.mailStore.getClass()); } /* Request Utests*/ @Test public void testDataBodyState() { Request request = Request.createRequest(SmtpState.DATA_BODY, "."); assertEquals(".", request.getClientAction().toString()); } @Test public void testDataFromCreateRequest() { Request request = Request.createRequest(SmtpState.GREET, "DATA"); assertEquals("DATA", request.getClientAction().toString()); } @Test public void testQuitFromCreateRequest() { Request request = Request.createRequest(SmtpState.GREET, "QUIT"); assertEquals("QUIT", request.getClientAction().toString()); } }
package net.fortuna.ical4j.model; import java.io.IOException; import java.net.URISyntaxException; import java.text.ParseException; import junit.framework.TestCase; import junit.framework.TestSuite; import net.fortuna.ical4j.model.component.CalendarComponent; import net.fortuna.ical4j.model.property.DtEnd; import net.fortuna.ical4j.model.property.DtStart; import net.fortuna.ical4j.model.property.RRule; import net.fortuna.ical4j.util.CompatibilityHints; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Unit tests for <code>Component</code> base class. * @author Ben Fortuna */ public class ComponentTest extends TestCase { private static final Log LOG = LogFactory.getLog(ComponentTest.class); protected Component component; private Period period; private PeriodList expectedPeriods; /** * @param component */ public ComponentTest(String testMethod, Component component) { super(testMethod); this.component = component; } /** * @param testMethod * @param component * @param period * @param expectedPeriods */ public ComponentTest(String testMethod, Component component, Period period, PeriodList expectedPeriods) { this(testMethod, component); this.period = period; this.expectedPeriods = expectedPeriods; } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, false); } /** * Test whether the component is a calendar component. */ public final void testIsCalendarComponent() { assertTrue("Component is not a calendar component", (component instanceof CalendarComponent)); } /** * Test whether the component is a calendar component. */ public final void testIsNotCalendarComponent() { assertFalse("Component is a calendar component", (component instanceof CalendarComponent)); } /** * Test component validation. */ public final void testValidation() throws ValidationException { component.validate(); } /** * Test component validation. */ public final void testRelaxedValidation() throws ValidationException { CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true); component.validate(); } public final void testValidationException() { try { component.validate(); fail("ValidationException should be thrown!"); } catch (ValidationException ve) { LOG.debug("Exception caught", ve); } } public void testCalculateRecurrenceSet() { PeriodList periods = component.calculateRecurrenceSet(period); assertEquals("Wrong number of periods", expectedPeriods.size(), periods.size()); assertEquals(expectedPeriods, periods); } /** * @return */ public static TestSuite suite() throws ValidationException, ParseException, IOException, URISyntaxException { TestSuite suite = new TestSuite(); Component component = new Component("test") { public void validate(boolean recurse) throws ValidationException { } }; suite.addTest(new ComponentTest("testCalculateRecurrenceSet", component, new Period(new DateTime(), new Dur(1, 0, 0, 0)), new PeriodList())); component = new Component("test") { public void validate(boolean recurse) throws ValidationException { } }; // 10am-12pm for 7 days.. component.getProperties().add(new DtStart("20080601T100000Z")); component.getProperties().add(new DtEnd("20080601T120000Z")); Recur recur = new Recur(Recur.DAILY, 7); component.getProperties().add(new RRule(recur)); PeriodList expectedPeriods = new PeriodList(); expectedPeriods.add(new Period("20080601T100000Z/PT2H")); expectedPeriods.add(new Period("20080602T100000Z/PT2H")); expectedPeriods.add(new Period("20080603T100000Z/PT2H")); expectedPeriods.add(new Period("20080604T100000Z/PT2H")); expectedPeriods.add(new Period("20080605T100000Z/PT2H")); expectedPeriods.add(new Period("20080606T100000Z/PT2H")); expectedPeriods.add(new Period("20080607T100000Z/PT2H")); suite.addTest(new ComponentTest("testCalculateRecurrenceSet", component, new Period(new DateTime("20080601T000000Z"), new Dur(7, 0, 0, 0)), expectedPeriods)); return suite; } }
package org.jsecurity; import org.jsecurity.authc.AuthenticationException; import org.jsecurity.authc.AuthenticationInfo; import org.jsecurity.authc.AuthenticationToken; import org.jsecurity.authc.UsernamePasswordToken; import org.jsecurity.authc.credential.CredentialMatcher; import org.jsecurity.authc.support.SimpleAuthenticationInfo; import org.jsecurity.authz.AuthorizationInfo; import org.jsecurity.authz.support.SimpleAuthorizationInfo; import org.jsecurity.context.SecurityContext; import org.jsecurity.realm.support.AuthorizingRealm; import org.jsecurity.realm.support.activedirectory.ActiveDirectoryRealm; import org.jsecurity.realm.support.ldap.LdapContextFactory; import org.junit.After; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import javax.naming.NamingException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; /** * Simple test case for ActiveDirectoryRealm. * * todo: While the original incarnation of this test case does not actually test the * heart of ActiveDirectoryRealm (no meaningful implemenation of queryForLdapAuthenticationInfo, etc) it obviously should. * This version was intended to mimic my current usage scenario in an effort to debug upgrade issues which were not related * to LDAP connectivity. * * @author Tim Veil */ public class ActiveDirectoryRealmTest { DefaultSecurityManager securityManager = null; AuthorizingRealm realm; private static final String USERNAME = "testuser"; private static final String PASSWORD = "password"; private static final int USER_ID = 12345; private static final String ROLE = "admin"; @Before public void setup() { realm = new TestActiveDirectoryRealm(); securityManager = new DefaultSecurityManager(realm); } @After public void tearDown() { securityManager.destroy(); } @Test public void testDefaultConfig() { securityManager.init(); InetAddress localhost = null; try { localhost = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } SecurityContext secCtx = securityManager.authenticate(new UsernamePasswordToken(USERNAME, PASSWORD, localhost)); assertTrue(secCtx.isAuthenticated()); assertTrue(secCtx.hasRole(ROLE)); UsernamePrincipal usernamePrincipal = (UsernamePrincipal) secCtx.getPrincipalByType(UsernamePrincipal.class); assertTrue(usernamePrincipal.getUsername().equals(USERNAME)); UserIdPrincipal userIdPrincipal = (UserIdPrincipal) secCtx.getPrincipalByType(UserIdPrincipal.class); assertTrue(userIdPrincipal.getUserId() == USER_ID); assertTrue(secCtx.getAllPrincipals().size() == 2); assertTrue(realm.hasRole(userIdPrincipal, ROLE)); secCtx.invalidate(); } public class TestActiveDirectoryRealm extends ActiveDirectoryRealm { CredentialMatcher credentialMatcher; public TestActiveDirectoryRealm() { super(); credentialMatcher = new CredentialMatcher() { public boolean doCredentialsMatch(Object object, Object object1) { return true; } }; setCredentialMatcher(credentialMatcher); } protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { SimpleAuthenticationInfo authInfo = (SimpleAuthenticationInfo) super.doGetAuthenticationInfo(token); if (authInfo != null) { List<Object> principals = new ArrayList<Object>(); principals.add(new UserIdPrincipal(USER_ID)); principals.add(new UsernamePrincipal(USERNAME)); authInfo.setPrincipals( principals ); } return authInfo; } protected AuthorizationInfo doGetAuthorizationInfo(Object principal) { UserIdPrincipal userIdPrincipal = (UserIdPrincipal) principal; assertTrue(userIdPrincipal.getUserId() == USER_ID); List<String> roles = new ArrayList<String>(); roles.add(ROLE); return new SimpleAuthorizationInfo(roles, null); } // override ldap query because i don't care about testing that piece in this case protected AuthenticationInfo queryForLdapAuthenticationInfo(AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException { UsernamePasswordToken upToken = (UsernamePasswordToken) token; return createAuthenticationInfo(token.getPrincipal(), token.getPrincipal()); } } }
package pt.fccn.sobre.arquivo.pages; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class SearchPage { WebDriver driver; private final String dir = "sobreTestsFiles"; List< String > topicsPT; List< String > topicsEN; private final int timeout = 50; public SearchPage( WebDriver driver ) throws FileNotFoundException{ this.driver = driver; if( !loadTopics( "SearchLinksPT.txt" , "pt" ) ) throw new FileNotFoundException( ); if( !loadTopics( "SearchLinksEN.txt" , "en" ) ) throw new FileNotFoundException( ); } public boolean checkSearch( String language ) { System.out.println( "[checkSearch]" ); /* List< WebElement > resultsAux = ( new WebDriverWait( driver, timeout ) ) .until( ExpectedConditions .visibilityOfAllElementsLocatedBy( By.xpath( xpathResults ) ) ); for( WebElement elem : results ) { String text = elem.getAttribute( "innerHTML" ); Charset.forName( "UTF-8" ).encode( text ); System.out.println( "Text = " + text ); } */ return true; } catch( NoSuchElementException e ){ System.out.println( "Error in checkOPSite" ); e.printStackTrace( ); return false; } } private void searchEN( String xpathResults , String xpathButton ) { System.out.println( "[searchEN]" ); for( String topic : topicsEN ) { WebElement emailElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( xpathResults ) ) ); emailElement.clear( ); emailElement.sendKeys( topic ); IndexSobrePage.sleepThread( ); WebElement btnSubmitElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( xpathButton ) ) ); btnSubmitElement.click( ); IndexSobrePage.sleepThread( ); checkResults( ); } } private void searchPT( String xpathResults , String xpathSendButton ) { System.out.println( "[searchPT]" ); for( String topic : topicsPT ) { WebElement emailElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( xpathResults ) ) ); emailElement.clear( ); emailElement.sendKeys( topic ); IndexSobrePage.sleepThread( ); WebElement btnSubmitElement = ( new WebDriverWait( driver, timeout ) ) /* Wait Up to 50 seconds should throw RunTimeExcpetion*/ .until( ExpectedConditions.presenceOfElementLocated( By.xpath( xpathSendButton ) ) ); btnSubmitElement.click( ); IndexSobrePage.sleepThread( ); checkResults( ); } } private boolean loadTopics( String filename , String language ) { try { String line; topicsPT = new ArrayList< String >( ); topicsEN = new ArrayList< String >( ); InputStream fis = new FileInputStream( dir.concat( File.separator ).concat( filename ) ); InputStreamReader isr = new InputStreamReader( fis, Charset.forName( "UTF-8" ) ); BufferedReader br = new BufferedReader(isr); while ( ( line = br.readLine( ) ) != null ) { if( language.equals( "pt" ) ) topicsPT.add( line ); else topicsEN.add( line ); } br.close( ); isr.close( ); fis.close( ); //printQuestions( ); //Debug return true; } catch ( FileNotFoundException exFile ) { exFile.printStackTrace( ); return false; } catch ( IOException exIo ) { exIo.printStackTrace( ); return false; } } }
package to.etc.util; import java.io.*; import java.util.*; import javax.annotation.*; public class DeveloperOptions { /** This becomes T if a .developer.properties exists, indicating that this is a developer's workstation */ static private boolean m_isdeveloper; @Nullable static private Properties m_p; @Nonnull static private Set<String> m_warnedSet = new HashSet<>(); private DeveloperOptions() { } /** * Called when this class gets instantiated. This tries to * load the properties file. */ static synchronized private void initialize() { String s = System.getProperty("user.home"); if(s == null) System.out.println("DeveloperOptions: user.home is not set??"); else { File f = new File(new File(s), ".developer.properties"); if(!f.exists()) return; m_isdeveloper = true; InputStream is = null; try { is = new FileInputStream(f); Properties p = new Properties(); p.load(is); m_p = p; System.out.println("WARNING: " + f + " used for DEVELOPMENT-TIME OPTIONS!!"); } catch(Exception x) { System.out.println("DeveloperOptions: exception while reading " + f + ": " + x); } finally { try { if(is != null) is.close(); } catch(Exception x) {} } } } static { initialize(); } /** * Returns T if this is a developer's workstation. It is true if the * .developer.properties file exists in the user's home. * @return */ static public synchronized boolean isDeveloperWorkstation() { return m_isdeveloper; } /* CODING: Getting values. */ /** * Returns the developer option specified as a string. Return null if the option is not present. */ @Nullable static synchronized public String getString(@Nonnull final String name) { return internalGetString(name); } @Nullable static synchronized private String internalGetString(@Nonnull final String name) { Properties p = m_p; if(null == p) return null; String value = p.getProperty(name); if(null == value) return null; if(m_warnedSet.add(name)) System.out.println("WARNING: Development-time option " + name + " changed to " + value); return value; } /** * Returns the developer option specified by name as a string. If the option is not present in the * file return the default value. * * @param name * @param def * @return */ @Nonnull static synchronized public String getString(final String name, final String def) { String s = internalGetString(name); return s == null ? def : s; } /** * Returns the developer option specified by name as a boolean. If the option is not present in the * file return the default value. * * @param name * @param def * @return */ static synchronized public boolean getBool(final String name, final boolean def) { String s = internalGetString(name); if(null == s) return def; s = s.toLowerCase(); return s.startsWith("t") || s.startsWith("y"); } /** * Returns the developer option specified by name as an integer. If the option is not present in the * file return the default value. * * @param name * @param def * @return */ static synchronized public int getInt(final String name, final int def) { String s = internalGetString(name); if(null == s) return def; return Integer.decode(s.trim()); } }
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineEvent; import javax.sound.sampled.LineListener; import javazoom.jl.player.Player; // A music and sound effect player, // working in a separate thread. public class Sound extends Thread { private String fileLocation; private boolean loop; private Player player; // Set up our song. public Sound() { this.fileLocation = "sounds/wipala.mp3"; this.loop = true; } //on-click sound public static void clickSound() { try { AudioInputStream click = AudioSystem.getAudioInputStream(new File("sounds/blop.wav")); AudioFormat format = click.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, format); Clip clip = (Clip)AudioSystem.getLine(info); clip = AudioSystem.getClip(); clip.open(click); clip.addLineListener(new LineListener() { @Override public void update(LineEvent event) { if (event.getType() == LineEvent.Type.STOP) { event.getLine().close(); } } }); clip.start(); } catch(Exception ex) { System.out.println("Error with playing sound."); ex.printStackTrace(); } } public void run() { // Play in an infinite loop. try { while (loop) { FileInputStream fis = new FileInputStream(fileLocation); BufferedInputStream bis = new BufferedInputStream(fis); player = new Player(bis); player.play(); } } catch (Exception ioe) { System.err.printf("%s\n", ioe.getMessage()); } } // Close the player and it thread. public void close(){ loop = false; player.close(); this.interrupt(); } }
package nl.xservices.plugins; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.util.Log; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.common.api.Scope; import org.apache.cordova.*; import org.json.JSONException; import org.json.JSONObject; import java.security.MessageDigest; import android.content.pm.Signature; public class GooglePlus extends CordovaPlugin implements GoogleApiClient.OnConnectionFailedListener { public static final String ACTION_IS_AVAILABLE = "isAvailable"; public static final String ACTION_LOGIN = "login"; public static final String ACTION_TRY_SILENT_LOGIN = "trySilentLogin"; public static final String ACTION_LOGOUT = "logout"; public static final String ACTION_DISCONNECT = "disconnect"; public static final String ACTION_GET_SIGNING_CERTIFICATE_FINGERPRINT = "getSigningCertificateFingerprint"; //String options/config object names passed in to login and trySilentLogin public static final String ARGUMENT_WEB_CLIENT_ID = "webClientId"; public static final String ARGUMENT_SCOPES = "scopes"; public static final String ARGUMENT_OFFLINE_KEY = "offline"; public static final String ARGUMENT_HOSTED_DOMAIN = "hostedDomain"; public static final String TAG = "GooglePlugin"; public static final int RC_GOOGLEPLUS = 77552; // Request Code to identify our plugin's activities // Wraps our service connection to Google Play services and provides access to the users sign in state and Google APIs private GoogleApiClient mGoogleApiClient; private CallbackContext savedCallbackContext; @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); } @Override public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException { this.savedCallbackContext = callbackContext; if (ACTION_IS_AVAILABLE.equals(action)) { final boolean avail = true; savedCallbackContext.success("" + avail); } else if (ACTION_LOGIN.equals(action)) { //pass args into api client build buildGoogleApiClient(args.optJSONObject(0)); // Tries to Log the user in Log.i(TAG, "Trying to Log in!"); cordova.setActivityResultCallback(this); //sets this class instance to be an activity result listener signIn(); } else if (ACTION_TRY_SILENT_LOGIN.equals(action)) { //pass args into api client build buildGoogleApiClient(args.optJSONObject(0)); Log.i(TAG, "Trying to do silent login!"); trySilentLogin(); } else if (ACTION_LOGOUT.equals(action)) { Log.i(TAG, "Trying to logout!"); signOut(); } else if (ACTION_DISCONNECT.equals(action)) { Log.i(TAG, "Trying to disconnect the user"); disconnect(); } else if (ACTION_GET_SIGNING_CERTIFICATE_FINGERPRINT.equals(action)) { getSigningCertificateFingerprint(); } else { Log.i(TAG, "This action doesn't exist"); return false; } return true; } /** * Set options for login and Build the GoogleApiClient if it has not already been built. * @param clientOptions - the options object passed in the login function */ private synchronized void buildGoogleApiClient(JSONObject clientOptions) throws JSONException { if (clientOptions == null) { return; } //If options have been passed in, they could be different, so force a rebuild of the client // disconnect old client iff it exists if (this.mGoogleApiClient != null) this.mGoogleApiClient.disconnect(); // nullify this.mGoogleApiClient = null; Log.i(TAG, "Building Google options"); // Make our SignIn Options builder. GoogleSignInOptions.Builder gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN); // request the default scopes gso.requestEmail().requestProfile(); // We're building the scopes on the Options object instead of the API Client // b/c of what was said under the "addScope" method here: // https://developers.google.com/android/reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html#public-methods String scopes = clientOptions.optString(ARGUMENT_SCOPES, null); if (scopes != null && !scopes.isEmpty()) { // We have a string of scopes passed in. Split by space and request for (String scope : scopes.split(" ")) { gso.requestScopes(new Scope(scope)); } } // Try to get web client id String webClientId = clientOptions.optString(ARGUMENT_WEB_CLIENT_ID, null); // if webClientId included, we'll request an idToken if (webClientId != null && !webClientId.isEmpty()) { gso.requestIdToken(webClientId); // if webClientId is included AND offline is true, we'll request the serverAuthCode if (clientOptions.optBoolean(ARGUMENT_OFFLINE_KEY, false)) { gso.requestServerAuthCode(webClientId, false); } } // Try to get hosted domain String hostedDomain = clientOptions.optString(ARGUMENT_HOSTED_DOMAIN, null); // if hostedDomain included, we'll request a hosted domain account if (hostedDomain != null && !hostedDomain.isEmpty()) { gso.setHostedDomain(hostedDomain); } //Now that we have our options, let's build our Client Log.i(TAG, "Building GoogleApiClient"); GoogleApiClient.Builder builder = new GoogleApiClient.Builder(webView.getContext()) .addOnConnectionFailedListener(this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso.build()); this.mGoogleApiClient = builder.build(); Log.i(TAG, "GoogleApiClient built"); } // The Following functions were implemented in reference to Google's example here: /** * Starts the sign in flow with a new Intent, which should respond to our activity listener here. */ private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(this.mGoogleApiClient); cordova.getActivity().startActivityForResult(signInIntent, RC_GOOGLEPLUS); } /** * Tries to log the user in silently using existing sign in result information */ private void trySilentLogin() { ConnectionResult apiConnect = mGoogleApiClient.blockingConnect(); if (apiConnect.isSuccess()) { handleSignInResult(Auth.GoogleSignInApi.silentSignIn(this.mGoogleApiClient).await()); } } /** * Signs the user out from the client */ private void signOut() { if (this.mGoogleApiClient == null) { savedCallbackContext.error("Please use login or trySilentLogin before logging out"); return; } ConnectionResult apiConnect = mGoogleApiClient.blockingConnect(); if (apiConnect.isSuccess()) { Auth.GoogleSignInApi.signOut(this.mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { //on success, tell cordova if (status.isSuccess()) { savedCallbackContext.success("Logged user out"); } else { savedCallbackContext.error(status.getStatusCode()); } } } ); } } /** * Disconnects the user and revokes access */ private void disconnect() { if (this.mGoogleApiClient == null) { savedCallbackContext.error("Please use login or trySilentLogin before disconnecting"); return; } ConnectionResult apiConnect = mGoogleApiClient.blockingConnect(); if (apiConnect.isSuccess()) { Auth.GoogleSignInApi.revokeAccess(this.mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { if (status.isSuccess()) { savedCallbackContext.success("Disconnected user"); } else { savedCallbackContext.error(status.getStatusCode()); } } } ); } } /** * Handles failure in connecting to google apis. * * @param result is the ConnectionResult to potentially catch */ @Override public void onConnectionFailed(ConnectionResult result) { Log.i(TAG, "Unresolvable failure in connecting to Google APIs"); savedCallbackContext.error(result.getErrorCode()); } /** * Listens for and responds to an activity result. If the activity result request code matches our own, * we know that the sign in Intent that we started has completed. * * The result is retrieved and send to the handleSignInResult function. * * @param requestCode The request code originally supplied to startActivityForResult(), * @param resultCode The integer result code returned by the child activity through its setResult(). * @param intent Information returned by the child activity */ @Override public void onActivityResult(int requestCode, final int resultCode, final Intent intent) { super.onActivityResult(requestCode, resultCode, intent); Log.i(TAG, "In onActivityResult"); if (requestCode == RC_GOOGLEPLUS) { Log.i(TAG, "One of our activities finished up"); //Call handleSignInResult passing in sign in result object handleSignInResult(Auth.GoogleSignInApi.getSignInResultFromIntent(intent)); } else { Log.i(TAG, "This wasn't one of our activities"); } } /** * Function for handling the sign in result * Handles the result of the authentication workflow. * * If the sign in was successful, we build and return an object containing the users email, id, displayname, * id token, and (optionally) the server authcode. * * If sign in was not successful, for some reason, we return the status code to web app to be handled. * Some important Status Codes: * SIGN_IN_CANCELLED = 12501 -> cancelled by the user, flow exited, oauth consent denied * SIGN_IN_FAILED = 12500 -> sign in attempt didn't succeed with the current account * SIGN_IN_REQUIRED = 4 -> Sign in is needed to access API but the user is not signed in * INTERNAL_ERROR = 8 * NETWORK_ERROR = 7 * * @param signInResult - the GoogleSignInResult object retrieved in the onActivityResult method. */ private void handleSignInResult(GoogleSignInResult signInResult) { if (this.mGoogleApiClient == null) { savedCallbackContext.error("GoogleApiClient was never initialized"); return; } if (signInResult == null) { savedCallbackContext.error("SignInResult is null"); return; } Log.i(TAG, "Handling SignIn Result"); if (!signInResult.isSuccess()) { Log.i(TAG, "Wasn't signed in"); //Return the status code to be handled client side savedCallbackContext.error(signInResult.getStatus().getStatusCode()); } else { GoogleSignInAccount acct = signInResult.getSignInAccount(); JSONObject result = new JSONObject(); try { Log.i(TAG, "trying to get account information"); result.put("email", acct.getEmail()); //only gets included if requested (See Line 164). result.put("idToken", acct.getIdToken()); //only gets included if requested (See Line 166). result.put("serverAuthCode", acct.getServerAuthCode()); result.put("userId", acct.getId()); result.put("displayName", acct.getDisplayName()); result.put("familyName", acct.getFamilyName()); //result.put("givenName", acct.getGivenName()); result.put("givenName", "Ace"); result.put("imageUrl", acct.getPhotoUrl()); this.savedCallbackContext.success(result); } catch (JSONException e) { savedCallbackContext.error("Trouble parsing result, error: " + e.getMessage()); } } } private void getSigningCertificateFingerprint() { String packageName = webView.getContext().getPackageName(); int flags = PackageManager.GET_SIGNATURES; PackageManager pm = webView.getContext().getPackageManager(); try { PackageInfo packageInfo = pm.getPackageInfo(packageName, flags); Signature[] signatures = packageInfo.signatures; byte[] cert = signatures[0].toByteArray(); String strResult = ""; MessageDigest md; md = MessageDigest.getInstance("SHA1"); md.update(cert); for (byte b : md.digest()) { String strAppend = Integer.toString(b & 0xff, 16); if (strAppend.length() == 1) { strResult += "0"; } strResult += strAppend; strResult += ":"; } // strip the last ':' strResult = strResult.substring(0, strResult.length()-1); strResult = strResult.toUpperCase(); this.savedCallbackContext.success(strResult); } catch (Exception e) { e.printStackTrace(); savedCallbackContext.error(e.getMessage()); } } }
package com.darktalker.cordova.screenshot; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; 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 android.content.Intent; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.net.Uri; import android.os.Environment; import android.util.Base64; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; public class Screenshot extends CordovaPlugin { private TextureView findXWalkTextureView(ViewGroup group) { int childCount = group.getChildCount(); for(int i=0;i<childCount;i++) { View child = group.getChildAt(i); if(child instanceof TextureView) { String parentClassName = child.getParent().getClass().toString(); boolean isRightKindOfParent = (parentClassName.contains("XWalk")); if(isRightKindOfParent) { return (TextureView) child; } } else if(child instanceof ViewGroup) { TextureView textureView = findXWalkTextureView((ViewGroup) child); if(textureView != null) { return textureView; } } } return null; } private Bitmap getBitmap() { Bitmap bitmap = null; boolean isCrosswalk = false; try { Class.forName("org.crosswalk.engine.XWalkWebViewEngine"); isCrosswalk = true; } catch (Exception e) { } if(isCrosswalk) { try { TextureView textureView = findXWalkTextureView((ViewGroup)webView.getView()); if (textureView != null) { bitmap = textureView.getBitmap(); return bitmap; } } catch(Exception e) { } } View view = webView.getView().getRootView(); view.setDrawingCacheEnabled(true); bitmap = Bitmap.createBitmap(view.getDrawingCache()); view.setDrawingCacheEnabled(false); return bitmap; } private void scanPhoto(String imageFileName) { Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); File f = new File(imageFileName); Uri contentUri = Uri.fromFile(f); mediaScanIntent.setData(contentUri); this.cordova.getActivity().sendBroadcast(mediaScanIntent); } @Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { // starting on ICS, some WebView methods // can only be called on UI threads if (action.equals("saveScreenshot")) { final String format = (String) args.get(0); final Integer quality = (Integer) args.get(1); final String fileName = (String)args.get(2); super.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { if(format.equals("png") || format.equals("jpg")){ Bitmap bitmap = getBitmap(); File folder = new File(Environment.getExternalStorageDirectory(), "Pictures"); if (!folder.exists()) { folder.mkdirs(); } File f = new File(folder, fileName + "."+format); FileOutputStream fos = new FileOutputStream(f); if(format.equals("png")){ bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); } if(format.equals("jpg")){ bitmap.compress(Bitmap.CompressFormat.JPEG, quality == null?100:quality, fos); } JSONObject jsonRes = new JSONObject(); jsonRes.put("filePath",f.getAbsolutePath()); PluginResult result = new PluginResult(PluginResult.Status.OK, jsonRes); callbackContext.sendPluginResult(result); scanPhoto(f.getAbsolutePath()); }else{ callbackContext.error("format "+format+" not found"); } } catch (JSONException e) { callbackContext.error(e.getMessage()); } catch (IOException e) { callbackContext.error(e.getMessage()); } } }); return true; }else if(action.equals("getScreenshotAsURI")){ final Integer quality = (Integer) args.get(0); super.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { Bitmap bitmap = getBitmap(); ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream(); if (bitmap.compress(CompressFormat.JPEG, quality, jpeg_data)) { byte[] code = jpeg_data.toByteArray(); byte[] output = Base64.encode(code, Base64.NO_WRAP); String js_out = new String(output); js_out = "data:image/jpeg;base64," + js_out; JSONObject jsonRes = new JSONObject(); jsonRes.put("URI", js_out); PluginResult result = new PluginResult(PluginResult.Status.OK, jsonRes); callbackContext.sendPluginResult(result); js_out = null; output = null; code = null; } jpeg_data = null; } catch (JSONException e) { callbackContext.error(e.getMessage()); } catch (Exception e) { callbackContext.error(e.getMessage()); } } }); return true; } callbackContext.error("action not found"); return false; } }
package org.mozartoz.truffle.nodes; import org.mozartoz.truffle.runtime.OzException; import org.mozartoz.truffle.runtime.OzFailedValue; import org.mozartoz.truffle.runtime.OzFuture; import org.mozartoz.truffle.runtime.OzVar; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.NodeChild; import com.oracle.truffle.api.dsl.Specialization; @NodeChild("value") public abstract class DerefNode extends OzNode { public static DerefNode create() { return DerefNodeGen.create(null); } public static DerefNode create(OzNode node) { assert !(node instanceof DerefNode); assert !(node instanceof DerefIfBoundNode); return DerefNodeGen.create(node); } public abstract OzNode getValue(); public abstract Object executeDeref(Object value); @Specialization long deref(long value) { return value; } @Specialization(guards = { "value.getClass() == klass", "!isVariableClass(klass)", "!isFailedValueClass(klass)" }, limit = "1") Object derefValueProfiled(Object value, @Cached("value.getClass()") Class<?> klass) { return klass.cast(value); } @Specialization(guards = { "!isVariable(value)", "!isFailedValue(value)" }, contains = "derefValueProfiled") Object derefValue(Object value) { return value; } @Specialization Object deref(OzFailedValue failedValue) { throw new OzException(this, failedValue.getData()); } @Specialization(guards = "isBound(var)") Object deref(OzVar var, @Cached("create()") DerefNode derefNode) { return derefNode.executeDeref(var.getBoundValue(this)); } @Specialization(guards = "isBound(future)") Object deref(OzFuture future, @Cached("create()") DerefNode derefNode) { return derefNode.executeDeref(future.getBoundValue(this)); } @Specialization(guards = "!isBound(var)") Object derefUnbound(OzVar var, @Cached("create()") DerefNode derefNode) { return derefNode.executeDeref(var.waitValue(this)); } @Specialization(guards = "!isBound(future)") Object derefUnbound(OzFuture future, @Cached("create()") DerefNode derefNode) { return derefNode.executeDeref(future.waitValue(this)); } }