answer
stringlengths
17
10.2M
package com.tendersaucer.joe; import com.badlogic.gdx.graphics.Color; import com.tendersaucer.joe.util.RandomUtils; import java.util.Arrays; import java.util.Collections; import java.util.List; public final class ColorScheme { private static final ColorScheme instance = new ColorScheme(); private static final float MIN_SHADE_BRIGHTNESS = 0.95f; private static final float MAX_SHADE_BRIGHTNESS = 1.05f; public enum ColorType { PRIMARY, SECONDARY } public enum ReturnType { SHARED, NEW } // http://paletton.com/#uid=70f0s0kllllaFw0g0qFqFg0w0aF private static Color[][] colorSchemes = new Color[][] { new Color[] { new Color(121 / 255.0f, 173 / 255.0f, 173 / 255.0f, 1), new Color(255 / 255.0f, 229 / 255.0f, 179 / 255.0f, 1), new Color(255 / 255.0f, 183 / 255.0f, 179 / 255.0f, 1) } }; private Color secondaryColor; private Color primaryColor; private ColorScheme() { } public static ColorScheme getInstance() { return instance; } public void reset() { // TODO: Is MathUtils.random legit? List<Color[]> colorBankList = Arrays.asList(colorSchemes); Collections.shuffle(colorBankList); colorSchemes = new Color[colorSchemes.length][colorSchemes[0].length]; colorBankList.toArray(colorSchemes); Color[] colorScheme = colorSchemes[RandomUtils.pickIndex(colorSchemes)]; primaryColor = colorScheme[RandomUtils.pickIndex(colorScheme)]; secondaryColor = primaryColor; while (secondaryColor == primaryColor) { secondaryColor = colorScheme[RandomUtils.pickIndex(colorScheme)]; } } public Color getPrimaryColor(ReturnType returnType) { if (returnType == ReturnType.SHARED) { return primaryColor; } return new Color(primaryColor); } public Color getSecondaryColor(ReturnType returnType) { if (returnType == ReturnType.SHARED) { return secondaryColor; } return new Color(secondaryColor); } public Color getShadedPrimaryColor() { Color color = getPrimaryColor(ReturnType.NEW); color.mul(RandomUtils.pickFromRange(MIN_SHADE_BRIGHTNESS, MAX_SHADE_BRIGHTNESS)).clamp(); return color; } public Color getShadedSecondaryColor() { Color color = getSecondaryColor(ReturnType.NEW); color.mul(RandomUtils.pickFromRange(MIN_SHADE_BRIGHTNESS, MAX_SHADE_BRIGHTNESS)).clamp(); return color; } public ColorType isShadeOf(Color color) { return dist(color, primaryColor) < dist(color, secondaryColor) ? ColorType.PRIMARY : ColorType.SECONDARY; } private double dist(Color x, Color y) { return Math.pow(x.r - y.r, 2) + Math.pow(x.g - y.g, 2) + Math.pow(x.b - y.b, 2); } }
package org.truth; import org.truth.subjects.Subject; import org.truth.subjects.SubjectFactory; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; @GwtCompatible public class AbstractVerb { private final FailureStrategy failureStrategy; public AbstractVerb(FailureStrategy failureStrategy) { this.failureStrategy = failureStrategy; } protected FailureStrategy getFailureStrategy() { return failureStrategy; } /** * Triggers the failure strategy with an empty failure message */ public void fail() { failureStrategy.fail(""); } /** * Triggers the failure strategy with the given failure message */ public void fail(String message) { failureStrategy.fail(message); } /** * The recommended method of extension of Truth to new types, which is * documented in {@link DelegationTest }. * * @see DelegationTest * @param factory a SubjectFactory<S, T> implementation * @returns A custom verb for the type returned by the SubjectFactory */ public <S extends Subject<S,T>, T, SF extends SubjectFactory<S, T>> DelegatedVerb<S, T> about(SF factory) { return new DelegatedVerb<S, T>(getFailureStrategy(), factory); } /** * A special Verb implementation which wraps a SubjectFactory */ public static class DelegatedVerb<S extends Subject<S,T>, T> extends AbstractVerb { private final SubjectFactory<S, T> factory; public DelegatedVerb(FailureStrategy fs, SubjectFactory<S, T> factory) { super(fs); this.factory = factory; } public S that(T target) { return factory.getSubject(getFailureStrategy(), target); } } @GwtIncompatible("org.truth.IteratingVerb") public <T> IteratingVerb<T> in(Iterable<T> data) { return new IteratingVerb<T>(data, getFailureStrategy()); } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.util.Collections; import java.util.Enumeration; import java.util.Objects; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter; import javax.swing.text.Highlighter.HighlightPainter; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; public final class MainPanel extends JPanel { private final JTextField field = new JTextField("foo"); private transient HighlightTreeCellRenderer renderer; private final JTree tree = new JTree() { @Override public void updateUI() { setCellRenderer(null); super.updateUI(); renderer = new HighlightTreeCellRenderer(); setCellRenderer(renderer); EventQueue.invokeLater(MainPanel.this::fireDocumentChangeEvent); } }; private MainPanel() { super(new BorderLayout()); field.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { fireDocumentChangeEvent(); } @Override public void removeUpdate(DocumentEvent e) { fireDocumentChangeEvent(); } @Override public void changedUpdate(DocumentEvent e) { /* not needed */ } }); JPanel n = new JPanel(new BorderLayout()); n.add(field); n.setBorder(BorderFactory.createTitledBorder("Search")); add(n, BorderLayout.NORTH); add(new JScrollPane(tree)); setPreferredSize(new Dimension(320, 240)); } public void fireDocumentChangeEvent() { String q = field.getText(); renderer.setQuery(q); TreePath root = tree.getPathForRow(0); collapseAll(tree, root); if (!q.isEmpty()) { searchTree(tree, root, q); } } private static void searchTree(JTree tree, TreePath path, String q) { TreeNode node = (TreeNode) path.getLastPathComponent(); if (Objects.isNull(node)) { return; } else if (node.toString().startsWith(q)) { tree.expandPath(path.getParentPath()); } if (!node.isLeaf()) { // Java 9: Collections.list(node.children()) Collections.list((Enumeration<?>) node.children()) .forEach(n -> searchTree(tree, path.pathByAddingChild(n), q)); } } private static void collapseAll(JTree tree, TreePath parent) { TreeNode node = (TreeNode) parent.getLastPathComponent(); if (!node.isLeaf()) { // Java 9: Collections.list(node.children()) Collections.list((Enumeration<?>) node.children()) .forEach(n -> collapseAll(tree, parent.pathByAddingChild(n))); } tree.collapsePath(parent); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class HighlightTreeCellRenderer implements TreeCellRenderer { private static final Color SELECTION_BGC = new Color(0xDC_F0_FF); private static final HighlightPainter HIGHLIGHT = new DefaultHighlightPainter(Color.YELLOW); private String query; private final JTextField renderer = new JTextField() { @Override public void updateUI() { super.updateUI(); setOpaque(true); setBorder(BorderFactory.createEmptyBorder()); setForeground(Color.BLACK); setBackground(Color.WHITE); setEditable(false); } }; public void setQuery(String query) { this.query = query; } @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { String txt = Objects.toString(value, ""); renderer.getHighlighter().removeAllHighlights(); renderer.setText(txt); renderer.setBackground(selected ? SELECTION_BGC : Color.WHITE); if (query != null && !query.isEmpty() && txt.startsWith(query)) { try { renderer.getHighlighter().addHighlight(0, query.length(), HIGHLIGHT); } catch (BadLocationException ex) { // should never happen RuntimeException wrap = new StringIndexOutOfBoundsException(ex.offsetRequested()); wrap.initCause(ex); throw wrap; } } return renderer; } }
package edu.oakland.OUSoft.database; import edu.oakland.OUSoft.items.Course; import edu.oakland.OUSoft.items.Instructor; import edu.oakland.OUSoft.items.Person; import edu.oakland.OUSoft.items.Student; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class OUPeopleTest { private OUPeople db; @BeforeEach void setUp() { db = new OUPeople(); } @Test void addCourse() { Course testCourse = new Course("testCourse"); Instructor testInstructor = new Instructor("TestInstructorID"); testCourse.setInstructor(testInstructor); db.addCourse(testCourse); assertTrue(db.getCourses().contains(testCourse), "addCourse did not add a course"); } @Test void addCourseOverload() { Course testCourse = new Course("testCourse"); Instructor testInstructor = new Instructor("TestInstructorID"); db.addCourse(testCourse, testInstructor); assertTrue(db.getCourses().contains(testCourse), "addCourse did not add a course when passed a course and instructor"); } @Test void addCourseNoInstructor() { Course testCourse = new Course("testCourse"); //Must have an instructor boolean threwExceptionForNoInstructor = false; try { db.addCourse(testCourse); } catch (IllegalArgumentException shouldThrow) { threwExceptionForNoInstructor = true; } assertTrue(threwExceptionForNoInstructor, "addCourse did not throw an exception for a course not having a valid Instructor"); } @Test void enroll() { Course testCourse = new Course("testCourse"); Student testStudent = new Student("TestStudentID"); Enrollment testEnrollment = new Enrollment(testCourse, testStudent); Enrollment returnedEnrollment = db.enroll(testStudent, testCourse); assertNotNull(returnedEnrollment, "enroll returned null"); assertEquals(testEnrollment, returnedEnrollment, "enroll return did not equal the expected Enrollment"); } @Test void withdraw() { Course testCourse = new Course("testCourse"); Student testStudent = new Student("TestStudentID"); Enrollment enrollment = db.enroll(testStudent, testCourse); assertNotNull(db.getEnrollment(testStudent, testCourse), "Enroll didn't work"); db.withdraw(testStudent, testCourse); assertNull(db.getEnrollment(testStudent, testCourse), "withdraw didn't withdraw"); } @Test void getEnrollment() { Course testCourse = new Course("testCourse"); Student testStudent = new Student("TestStudentID"); assertNull(db.getEnrollment(testStudent, testCourse), "Magically got enrolled somehow"); Enrollment returnedEnrollment = db.enroll(testStudent, testCourse); assertEquals(returnedEnrollment, db.getEnrollment(testStudent, testCourse), "getEnrollment did not return the same as enroll()"); } @Test void getEnrollmentsForCourse() { Course testCourse = new Course("testCourse"); Student testStudent = new Student("TestStudentID"); Student testStudent2 = new Student("TestStudentID2"); assertEquals(0, db.getEnrollments(testCourse).size(), "getEnrollments (for course) magically obtained an Enrollment"); Enrollment returnedEnrollment = db.enroll(testStudent, testCourse); Enrollment returnedEnrollment2 = db.enroll(testStudent2, testCourse); List<Enrollment> enrollments = db.getEnrollments(testCourse); assertTrue(enrollments.contains(returnedEnrollment), "getEnrollments (for course) did not contain an Enrollment it should have"); assertTrue(enrollments.contains(returnedEnrollment2), "getEnrollments (for course) did not contain an Enrollment it should have"); } @Test void getEnrollmentsForStudent() { Course testCourse = new Course("testCourse"); Course testCourse2 = new Course("testCourse2"); Student testStudent = new Student("TestStudentID"); assertEquals(0, db.getEnrollments(testStudent).size(), "getEnrollments (for student) magically obtained an Enrollment"); Enrollment returnedEnrollment = db.enroll(testStudent, testCourse); Enrollment returnedEnrollment2 = db.enroll(testStudent, testCourse2); List<Enrollment> enrollments = db.getEnrollments(testStudent); assertTrue(enrollments.contains(returnedEnrollment), "getEnrollments (for student) did not contain an Enrollment it should have"); assertTrue(enrollments.contains(returnedEnrollment2), "getEnrollments (for student) did not contain an Enrollment it should have"); } @Test void studentIsEnrolled() { Course testCourse = new Course("testCourse"); Student testStudent = new Student("TestStudentID"); assertFalse(db.studentIsEnrolled(testStudent, testCourse), "Student magically got enrolled"); db.enroll(testStudent, testCourse); assertTrue(db.studentIsEnrolled(testStudent, testCourse), "Student did not get enrolled"); } @Test void numberStudentsEnrolled() { Course testCourse = new Course("testCourse"); Student testStudent = new Student("TestStudentID"); Student testStudent2 = new Student("TestStudentID2"); assertEquals(0, db.numberStudentsEnrolled(testCourse), "Should be no one enrolled"); db.enroll(testStudent, testCourse); assertEquals(1, db.numberStudentsEnrolled(testCourse), "Should be one person enrolled"); db.enroll(testStudent2, testCourse); assertEquals(2, db.numberStudentsEnrolled(testCourse), "Should be two people enrolled"); db.withdraw(testStudent, testCourse); assertEquals(1, db.numberStudentsEnrolled(testCourse), "Should be one person enrolled"); //Call enroll again when they are already enrolled that course db.enroll(testStudent2, testCourse); assertEquals(1, db.numberStudentsEnrolled(testCourse), "numberStudentsEnrolled says more students got enrolled after the same person was enrolled again"); } @Test void numberCoursesEnrolled() { Course testCourse = new Course("testCourse"); Course testCourse2 = new Course("testCourse2"); Student testStudent = new Student("TestStudentID"); assertEquals(0, db.numberCoursesEnrolled(testStudent), "Should be no courses enrolled"); db.enroll(testStudent, testCourse); assertEquals(1, db.numberCoursesEnrolled(testStudent), "Should be one course enrolled"); db.enroll(testStudent, testCourse2); assertEquals(2, db.numberCoursesEnrolled(testStudent), "Should be two courses enrolled"); db.withdraw(testStudent, testCourse); assertEquals(1, db.numberCoursesEnrolled(testStudent), "Should be one course enrolled"); //Call enroll again when they are already enrolled that course db.enroll(testStudent, testCourse2); assertEquals(1, db.numberCoursesEnrolled(testStudent), "numberCoursesEnrolled says more courses got enrolled after the same course was enrolled again"); } @Test void retrievePersonByID() { assertEquals(null, db.retrievePersonByID("NULL"), "Person magically appeared in database"); Person testPerson = new Person("ID"); db.addPerson(testPerson); assertEquals(testPerson, db.retrievePersonByID("ID"), "Person retrieved by ID did not match person added"); } @Test void retrieveStudentByID() { assertEquals(null, db.retrieveStudentByID("NULL"), "Person magically appeared in database"); Student testStudent = new Student("ID"); db.addPerson(testStudent); assertEquals(testStudent, db.retrieveStudentByID("ID"), "Student retrieved by ID did not match person added"); //Check not in wrong category assertEquals(null, db.retrieveOtherByID("ID"), "Retrieved a student from an improper sub-database"); assertEquals(null, db.retrieveInstructorByID("ID"), "Retrieved a student from an improper sub-database"); } @Test void retrieveInstructorByID() { assertEquals(null, db.retrieveInstructorByID("NULL"), "Person magically appeared in database"); Instructor testInstructor = new Instructor("ID"); db.addPerson(testInstructor); assertEquals(testInstructor, db.retrieveInstructorByID("ID"), "Instructor retrieved by ID did not match person added"); //Check not in wrong category assertEquals(null, db.retrieveStudentByID("ID"), "Retrieved an instructor from an improper sub-database"); assertEquals(null, db.retrieveOtherByID("ID"), "Retrieved an instructor from an improper sub-database"); } @Test void retrieveOtherByID() { assertEquals(null, db.retrieveOtherByID("NULL"), "Person magically appeared in database"); Person testPerson = new Person("ID"); db.addPerson(testPerson); assertEquals(testPerson, db.retrieveOtherByID("ID"), "Other retrieved by ID did not match person added"); //Check not in wrong category assertEquals(null, db.retrieveStudentByID("ID"), "Retrieved a person from an improper sub-database"); assertEquals(null, db.retrieveInstructorByID("ID"), "Retrieved a person from an improper sub-database"); } @Test void addPerson() { Person testPerson = new Person("ID"); db.addPerson(testPerson); assertTrue(db.getPeople().contains(testPerson), "Did not add a person"); } @Test void removeStudent() { Student testStudent = new Student("ID"); db.addPerson(testStudent); db.removeStudent(testStudent); assertFalse(db.getStudents().contains(testStudent), "Did not remove a student"); } @Test void removeInstructor() { Instructor testInstructor = new Instructor("ID"); db.addPerson(testInstructor); db.removeInstructor(testInstructor); assertFalse(db.getInstructors().contains(testInstructor), "Did not remove an instructor"); } @Test void removeOther() { Person testPerson = new Person("ID"); db.addPerson(testPerson); db.removeOther(testPerson); assertFalse(db.getPeople().contains(testPerson), "Did not remove an other"); } @Test void removePerson() { Person testPerson = new Person("ID"); db.addPerson(testPerson); db.removePerson(testPerson); assertFalse(db.getPeople().contains(testPerson), "Did not remove a person"); } @Test void removeStudentByID() { Student testStudent = new Student("ID"); db.addPerson(testStudent); db.removeStudentByID("ID"); assertFalse(db.getStudents().contains(testStudent), "Did not remove a student by ID"); } @Test void removeInstructorByID() { Instructor testInstructor = new Instructor("ID"); db.addPerson(testInstructor); db.removeInstructorByID("ID"); assertFalse(db.getInstructors().contains(testInstructor), "Did not remove an instructor by ID"); } @Test void removeOtherByID() { Person testPerson = new Person("ID"); db.addPerson(testPerson); db.removeOtherByID("ID"); assertFalse(db.getPeople().contains(testPerson), "Did not remove an other by ID"); } @Test void removePersonByID() { Person testPerson = new Person("ID"); db.addPerson(testPerson); db.removePersonByID("ID"); assertFalse(db.getPeople().contains(testPerson), "Did not remove a person by ID"); } }
package GUI; import java.awt.GridLayout; import javax.swing.JFrame; public class MainFrame extends JFrame { public MainFrame () { this.setSize(800, 600); this.setLayout(new GridLayout(8,3,0,0)); } }
package com.cloud.agent.dao; import com.cloud.utils.component.Manager; /** * StorageDao is an abstraction layer for what the agent will use for storage. * */ public interface StorageComponent extends Manager { String get(String key); void persist(String key, String value); }
package com.cgogolin.penandpdf; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.ArrayDeque; import java.util.LinkedList; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Region; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Parcelable; import android.view.ViewGroup; import android.view.View; import android.view.View.OnLayoutChangeListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.preference.PreferenceManager; import android.util.Log; interface TextProcessor { void onStartLine(); void onWord(TextWord word); void onEndLine(); void onEndText(); } class TextSelector { final private TextWord[][] mText; final private RectF mSelectBox; private float mStartLimit = Float.NEGATIVE_INFINITY; private float mEndLimit = Float.POSITIVE_INFINITY; public TextSelector(TextWord[][] text, RectF selectBox) { mText = text; mSelectBox = selectBox; } public TextSelector(TextWord[][] text, RectF selectBox, float startLimit, float endLimit) { mStartLimit = startLimit; mEndLimit = endLimit; mText = text; mSelectBox = selectBox; } public void select(TextProcessor tp) { if (mText == null || mSelectBox == null) return; ArrayList<TextWord[]> lines = new ArrayList<TextWord[]>(); for (TextWord[] line : mText) if (line[0].bottom > mSelectBox.top && line[0].top < mSelectBox.bottom) lines.add(line); Iterator<TextWord[]> it = lines.iterator(); while (it.hasNext()) { TextWord[] line = it.next(); boolean firstLine = line[0].top < mSelectBox.top; boolean lastLine = line[0].bottom > mSelectBox.bottom; float start = mStartLimit; float end = mEndLimit; if (firstLine && lastLine) { start = Math.min(mSelectBox.left, mSelectBox.right); end = Math.max(mSelectBox.left, mSelectBox.right); } else if (firstLine) { start = mSelectBox.left; } else if (lastLine) { end = mSelectBox.right; } tp.onStartLine(); for (TextWord word : line) { if (word.right > start && word.left < end) tp.onWord(word); } tp.onEndLine(); } tp.onEndText(); } } public abstract class PageView extends ViewGroup implements MuPDFView { private static final int SELECTION_COLOR = 0x8033B5E5; private static final int GRAYEDOUT_COLOR = 0x30000000; private static final int SEARCHRESULTS_COLOR = 0x3033B5E5; private static final int HIGHLIGHTED_SEARCHRESULT_COLOR = 0xFF33B5E5; private static final int LINK_COLOR = 0xFF33B5E5; private static final int BOX_COLOR = 0xFF33B5E5; private static final int BACKGROUND_COLOR = 0xFFFFFFFF; private static final int ERASER_INNER_COLOR = 0xFFFFFFFF; private static final int ERASER_OUTER_COLOR = 0xFF000000; private static final int PROGRESS_DIALOG_DELAY = 200; protected final Context mContext; private ViewGroup mParent; protected int mPageNumber; protected Point mSize; // Size of page at minimum zoom protected float mSourceScale; private float docRelXmax = Float.NEGATIVE_INFINITY; private float docRelXmin = Float.POSITIVE_INFINITY; private boolean mIsBlank; private boolean mHighlightLinks; // private ImageView mEntireView; // Image rendered at minimum zoom private PatchView mEntireView; // Page rendered at minimum zoom private Bitmap mEntireBm; private Matrix mEntireMat; // private AsyncTask<Void,Void,Void> mDrawEntire; private PatchView mHqView; // private AsyncTask<PatchInfo,Void,PatchInfo> mDrawPatch; private TextWord mText[][]; private AsyncTask<Void,Void,TextWord[][]> mGetText; protected LinkInfo mLinks[]; private AsyncTask<Void,Void,LinkInfo[]> mGetLinkInfo; private View mOverlayView; private SearchResult mSearchResult = null; private RectF mSelectBox; private RectF mItemSelectBox; protected ArrayDeque<ArrayList<ArrayList<PointF>>> mDrawingHistory = new ArrayDeque<ArrayList<ArrayList<PointF>>>(); protected ArrayList<ArrayList<PointF>> mDrawing; private PointF eraser = null; private ProgressBar mBusyIndicator; private final Handler mHandler = new Handler(); //Set in onSharedPreferenceChanged() private static float inkThickness = 10; private static float eraserThickness = 20; private static int inkColor = 0x80AC7225; private static int highlightColor = 0x80AC7225; private static int underlineColor = 0x80AC7225; private static int strikeoutColor = 0x80AC7225; private static boolean useSmartTextSelection = false; //To be overrwritten in MuPDFPageView protected abstract void drawPage(Bitmap bm, int sizeX, int sizeY, int patchX, int patchY, int patchWidth, int patchHeight); protected abstract void updatePage(Bitmap bm, int sizeX, int sizeY, int patchX, int patchY, int patchWidth, int patchHeight); protected abstract LinkInfo[] getLinkInfo(); protected abstract TextWord[][] getText(); protected abstract void addMarkup(PointF[] quadPoints, Annotation.Type type); //The ViewGroup PageView has three child views: mHqView, mEntire, and mOverlayView. //mOverlayView is from an anonymous subclass defined in setPage(), the other two are class PatchInfo { public final Rect viewArea; public final Rect patchArea; public final boolean completeRedraw; public final Bitmap patchBm; public final boolean intersects; public final boolean areaChanged; public PatchInfo(Rect viewArea, Bitmap patchBm, PatchView patch, boolean update) { this.viewArea = viewArea; Rect rect = new Rect(0, 0, patchBm.getWidth(), patchBm.getHeight()); intersects = rect.intersect(viewArea); rect.offset(-viewArea.left, -viewArea.top); patchArea = rect; areaChanged = patch == null ? true : !viewArea.equals(patch.getArea()); completeRedraw = areaChanged || !update; this.patchBm = patchBm; } } class PatchView extends OpaqueImageView { private Rect area; private AsyncTask<PatchInfo,Void,PatchInfo> mDrawPatch; public PatchView(Context context) { super(context); setScaleType(ImageView.ScaleType.MATRIX); } public void setArea(Rect area) { this.area = area; } public Rect getArea() { return area; } public void reset() { cancelRenderInBackground(); setArea(null); setImageBitmap(null); invalidate(); } public void renderInBackground(PatchInfo patchInfo) { // Stop the drawing of previous patch if still going if (mDrawPatch != null) { mDrawPatch.cancel(true); mDrawPatch = null; } mDrawPatch = new AsyncTask<PatchInfo,Void,PatchInfo>() { protected PatchInfo doInBackground(PatchInfo... v) { if (v[0].completeRedraw) { drawPage(v[0].patchBm, v[0].viewArea.width(), v[0].viewArea.height(), v[0].patchArea.left, v[0].patchArea.top, v[0].patchArea.width(), v[0].patchArea.height()); } else { updatePage(v[0].patchBm, v[0].viewArea.width(), v[0].viewArea.height(), v[0].patchArea.left, v[0].patchArea.top, v[0].patchArea.width(), v[0].patchArea.height()); } return v[0]; } protected void onPostExecute(PatchInfo v) { setArea(v.viewArea); setImageBitmap(v.patchBm); invalidate(); layout(v.patchArea.left, v.patchArea.top, v.patchArea.right, v.patchArea.bottom); } }; mDrawPatch.execute(patchInfo); } public void cancelRenderInBackground() { if (mDrawPatch != null) { mDrawPatch.cancel(true); mDrawPatch = null; } } } // class EntireView extends OpaqueImageView { // private AsyncTask<PatchInfo,Void,PatchInfo> mDrawEntire; // private Bitmap mEntireBm; // public EntireView(Context context) { // super(context); // setScaleType(ImageView.ScaleType.MATRIX); // reset(); // public void reset() { // cancelRenderInBackground(); // setImageBitmap(null); // invalidate(); // public void renderInBackground(PatchInfo patchInfo) { // // Stop the drawing of previous patch if still going // if (mDrawEntire != null) { // mDrawEntire.cancel(true); // mDrawEntire = null; // //Create a bitmap of the right size (needs to be adopted!!!) // if(mEntireBm == null || mParent.getWidth() != mEntireBm.getWidth() || mParent.getHeight() != mEntireBm.getHeight()) // mEntireBm = Bitmap.createBitmap(mParent.getWidth(), mParent.getHeight(), Config.ARGB_8888); // mDrawEntire = new AsyncTask<PatchInfo,Void,PatchInfo>() { // protected PatchInfo doInBackground(PatchInfo... v) { // if (v[0].completeRedraw) { // drawPage(v[0].patchBm, v[0].viewArea.width(), v[0].viewArea.height(), // v[0].patchArea.left, v[0].patchArea.top, // v[0].patchArea.width(), v[0].patchArea.height()); // } else { // updatePage(v[0].patchBm, v[0].viewArea.width(), v[0].viewArea.height(), // v[0].patchArea.left, v[0].patchArea.top, // v[0].patchArea.width(), v[0].patchArea.height()); // return v[0]; // protected void onPostExecute(PatchInfo v) { // setImageBitmap(v.patchBm); // invalidate(); // layout(v.patchArea.left, v.patchArea.top, v.patchArea.right, v.patchArea.bottom); // mDrawEntire.execute(patchInfo); // public void cancelRenderInBackground() { // if (mDrawEntire != null) { // mDrawEntire.cancel(true); // mDrawEntire = null; public PageView(Context c, ViewGroup parent) { super(c); mContext = c; mParent = parent; mEntireMat = new Matrix(); } @Override public boolean isOpaque() { return true; } private void reset() { // Cancel pending background tasks // if (mDrawEntire != null) { // mDrawEntire.cancel(true); // mDrawEntire = null; // if (mDrawPatch != null) { // mDrawPatch.cancel(true); // mDrawPatch = null; if (mGetLinkInfo != null) { mGetLinkInfo.cancel(true); mGetLinkInfo = null; } if (mGetText != null) { mGetText.cancel(true); mGetText = null; } mIsBlank = true; mPageNumber = 0; mSize = null; // //Reset the child views // if (mEntireView != null) { // mEntireView.setImageBitmap(null); // mEntireView.invalidate(); if(mEntireView != null) mEntireView.reset(); if(mHqView != null) mHqView.reset(); if(mOverlayView != null) { removeView(mOverlayView); mOverlayView = null; } mSearchResult = null; mLinks = null; mSelectBox = null; mText = null; mItemSelectBox = null; } public void releaseResources() { reset(); if (mBusyIndicator != null) { removeView(mBusyIndicator); mBusyIndicator = null; } mDrawing = null; mDrawingHistory.clear(); //Cancel all other async tasks if (mGetText != null) { mGetText.cancel(true); mGetText = null; } if (mGetLinkInfo != null) { mGetLinkInfo.cancel(true); mGetLinkInfo = null; } } public void releaseBitmaps() { reset(); mEntireBm = null; } public void setPage(int page, PointF size) { reset(); mPageNumber = page; mIsBlank = false; // Calculate scaled size that fits within the parent // This is the size at minimum zoom mSourceScale = Math.min(mParent.getWidth()/size.x, mParent.getHeight()/size.y); mSize = new Point((int)(size.x*mSourceScale), (int)(size.y*mSourceScale)); // Get the link info in the background mGetLinkInfo = new AsyncTask<Void,Void,LinkInfo[]>() { protected LinkInfo[] doInBackground(Void... v) { return getLinkInfo(); } protected void onPostExecute(LinkInfo[] v) { mLinks = v; if (mOverlayView != null) mOverlayView.invalidate(); } }; mGetLinkInfo.execute(); //Set the background to white for now and //prepare and show the busy indicator setBackgroundColor(BACKGROUND_COLOR); if (mBusyIndicator == null) { mBusyIndicator = new ProgressBar(mContext); mBusyIndicator.setIndeterminate(true); addView(mBusyIndicator); mBusyIndicator.setVisibility(INVISIBLE); mHandler.postDelayed(new Runnable() { public void run() { if (mBusyIndicator != null) mBusyIndicator.setVisibility(VISIBLE); } }, PROGRESS_DIALOG_DELAY); } //The following has been moved to addEntire() // //Prepare the mEntire view // if (mEntireView == null) { // mEntireView = new OpaqueImageView(mContext); // mEntireView.setScaleType(ImageView.ScaleType.MATRIX); // addView(mEntireView); // mEntireView.setImageBitmap(null); // mEntireView.invalidate(); // //Create a bitmap of the right size // if(mEntireBm == null || mParent.getWidth() != mEntireBm.getWidth() || mParent.getHeight() != mEntireBm.getHeight()) // mEntireBm = Bitmap.createBitmap(mParent.getWidth(), mParent.getHeight(), Config.ARGB_8888); // // Render the page in the background // mDrawEntire = new AsyncTask<Void,Void,Void>() { // protected Void doInBackground(Void... v) { // drawPage(mEntireBm, mSize.x, mSize.y, 0, 0, mSize.x, mSize.y); // return null; // protected void onPostExecute(Void v) { // if(mBusyIndicator!=null) // mBusyIndicator.setVisibility(INVISIBLE); // removeView(mBusyIndicator); // mBusyIndicator = null; // mEntireView.setImageBitmap(mEntireBm); // mEntireView.invalidate(); // setBackgroundColor(Color.TRANSPARENT); // protected void onCanceled() { // if(mBusyIndicator!=null) // mBusyIndicator.setVisibility(INVISIBLE); // removeView(mBusyIndicator); // mBusyIndicator = null; // mDrawEntire.execute(); addEntire(false); //Create the Overlay view if not present if (mOverlayView == null) { mOverlayView = new View(mContext) { Path mDrawingPath = new Path(); class TextSelectionDrawer implements TextProcessor { RectF rect; float docRelXmaxSelection = Float.NEGATIVE_INFINITY; float docRelXminSelection = Float.POSITIVE_INFINITY; float scale; Canvas canvas; public void reset(Canvas canvas, float scale) { this.canvas = canvas; this.scale = scale; docRelXmaxSelection = Float.NEGATIVE_INFINITY; docRelXminSelection = Float.POSITIVE_INFINITY; } public void onStartLine() { rect = new RectF(); } public void onWord(TextWord word) { rect.union(word); } public void onEndLine() { if (!rect.isEmpty()) { canvas.drawRect(rect.left*scale, rect.top*scale, rect.right*scale, rect.bottom*scale, selectBoxPaint); docRelXmaxSelection = Math.max(docRelXmaxSelection,Math.max(rect.right,docRelXmax)); docRelXminSelection = Math.min(docRelXminSelection,Math.min(rect.left,docRelXmin)); } } public void onEndText() { if (useSmartTextSelection) { canvas.drawRect(0, 0, docRelXminSelection*scale, PageView.this.getHeight(), selectOverlayPaint); canvas.drawRect(docRelXmaxSelection*scale, 0, PageView.this.getWidth(), PageView.this.getHeight(), selectOverlayPaint); } } } private final Paint searchResultPaint = new Paint(); private final Paint highlightedSearchResultPaint = new Paint(); private final Paint linksPaint = new Paint(); private final Paint selectBoxPaint = new Paint(); private final Paint selectOverlayPaint = new Paint(); private final Paint itemSelectBoxPaint = new Paint(); private final Paint drawingPaint = new Paint(); private final Paint eraserInnerPaint = new Paint(); private final Paint eraserOuterPaint = new Paint(); private final TextSelectionDrawer textSelectionDrawer = new TextSelectionDrawer(); { searchResultPaint.setColor(SEARCHRESULTS_COLOR); highlightedSearchResultPaint.setColor(HIGHLIGHTED_SEARCHRESULT_COLOR); highlightedSearchResultPaint.setStyle(Paint.Style.STROKE); highlightedSearchResultPaint.setAntiAlias(true); linksPaint.setColor(LINK_COLOR); linksPaint.setStyle(Paint.Style.STROKE); linksPaint.setStrokeWidth(0); selectBoxPaint.setColor(SELECTION_COLOR); selectBoxPaint.setStyle(Paint.Style.FILL); selectBoxPaint.setStrokeWidth(0); selectOverlayPaint.setColor(GRAYEDOUT_COLOR); selectOverlayPaint.setStyle(Paint.Style.FILL); itemSelectBoxPaint.setColor(BOX_COLOR); itemSelectBoxPaint.setStyle(Paint.Style.STROKE); itemSelectBoxPaint.setStrokeWidth(0); drawingPaint.setAntiAlias(true); drawingPaint.setDither(true); drawingPaint.setStrokeJoin(Paint.Join.ROUND); drawingPaint.setStrokeCap(Paint.Cap.ROUND); drawingPaint.setStyle(Paint.Style.STROKE); eraserInnerPaint.setAntiAlias(true); eraserInnerPaint.setDither(true); eraserInnerPaint.setStyle(Paint.Style.FILL); eraserInnerPaint.setColor(ERASER_INNER_COLOR); eraserOuterPaint.setAntiAlias(true); eraserOuterPaint.setDither(true); eraserOuterPaint.setStyle(Paint.Style.STROKE); eraserOuterPaint.setColor(ERASER_OUTER_COLOR); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int x, y; switch(View.MeasureSpec.getMode(widthMeasureSpec)) { case View.MeasureSpec.UNSPECIFIED: x = PageView.this.getWidth(); break; case View.MeasureSpec.AT_MOST: x = Math.min(PageView.this.getWidth() ,View.MeasureSpec.getSize(widthMeasureSpec)); default: x = View.MeasureSpec.getSize(widthMeasureSpec); } switch(View.MeasureSpec.getMode(heightMeasureSpec)) { case View.MeasureSpec.UNSPECIFIED: y = PageView.this.getHeight(); break; case View.MeasureSpec.AT_MOST: y = Math.min(PageView.this.getHeight(), View.MeasureSpec.getSize(heightMeasureSpec)); default: y = View.MeasureSpec.getSize(heightMeasureSpec); } setMeasuredDimension(x, y); } @Override protected void onDraw(final Canvas canvas) { super.onDraw(canvas); // Log.v("PageView", "onDraw() of page "+mPageNumber+" of OverlayView"+this); //Clip to the canvas size (not sure if this is necessary) canvas.clipRect(0,0, canvas.getWidth(), canvas.getHeight(), Region.Op.INTERSECT); //Move the canvas so that it covers the visible region (not sure why the -2 is necessary) canvas.translate(PageView.this.getLeft(), PageView.this.getTop()); // Work out current total scale factor from source to view final float scale = mSourceScale*(float)PageView.this.getWidth()/(float)mSize.x; // Highlight the search results if (!mIsBlank && mSearchResult != null) { for (RectF rect : mSearchResult.getSearchBoxes()) { canvas.drawRect(rect.left*scale, rect.top*scale, rect.right*scale, rect.bottom*scale, searchResultPaint); } RectF rect = mSearchResult.getFocusedSearchBox(); if(rect != null) { highlightedSearchResultPaint.setStrokeWidth(2 * scale); canvas.drawRect(rect.left*scale, rect.top*scale, rect.right*scale, rect.bottom*scale, highlightedSearchResultPaint); } } // Draw the link boxes if (!mIsBlank && mLinks != null && mHighlightLinks) { for (LinkInfo link : mLinks) { canvas.drawRect(link.rect.left*scale, link.rect.top*scale, link.rect.right*scale, link.rect.bottom*scale, linksPaint); } } // Draw the text selection if (!mIsBlank && mSelectBox != null && mText != null) { textSelectionDrawer.reset(canvas, scale); processSelectedText(textSelectionDrawer); } // Draw the box arround selected notations and thelike if (!mIsBlank && mItemSelectBox != null) { canvas.drawRect(mItemSelectBox.left*scale, mItemSelectBox.top*scale, mItemSelectBox.right*scale, mItemSelectBox.bottom*scale, itemSelectBoxPaint); } // Draw the current hand drawing if (!mIsBlank && mDrawing != null) { PointF p; Iterator<ArrayList<PointF>> it = mDrawing.iterator(); while (it.hasNext()) { ArrayList<PointF> arc = it.next(); if (arc.size() >= 2) { Iterator<PointF> iit = arc.iterator(); if(iit.hasNext()) { p = iit.next(); float mX = p.x * scale; float mY = p.y * scale; mDrawingPath.moveTo(mX, mY); while (iit.hasNext()) { p = iit.next(); float x = p.x * scale; float y = p.y * scale; mDrawingPath.lineTo(x, y); } } if(!canvas.quickReject(mDrawingPath, Canvas.EdgeType.AA)) { drawingPaint.setStrokeWidth(inkThickness * scale); drawingPaint.setColor(inkColor); //Should be done only on settings change canvas.drawPath(mDrawingPath, drawingPaint); } mDrawingPath.reset(); } } } // Draw the eraser if (eraser != null) { canvas.drawCircle(eraser.x * scale, eraser.y * scale, eraserThickness * scale, eraserInnerPaint); canvas.drawCircle(eraser.x * scale, eraser.y * scale, eraserThickness * scale, eraserOuterPaint); } } }; //Fit the overlay view to the PageView mOverlayView.measure(MeasureSpec.makeMeasureSpec(mParent.getWidth(), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(mParent.getHeight(), MeasureSpec.AT_MOST)); addView(mOverlayView); } mOverlayView.invalidate(); requestLayout(); } public void setLinkHighlighting(boolean f) { mHighlightLinks = f; if (mOverlayView != null) mOverlayView.invalidate(); } public void deselectText() { docRelXmax = Float.NEGATIVE_INFINITY; docRelXmin = Float.POSITIVE_INFINITY; mSelectBox = null; mOverlayView.invalidate(); } public boolean hasSelection() { if (mSelectBox == null) return false; else return true; } public void selectText(float x0, float y0, float x1, float y1) { float scale = mSourceScale*(float)getWidth()/(float)mSize.x; float docRelX0 = (x0 - getLeft())/scale; float docRelY0 = (y0 - getTop())/scale; float docRelX1 = (x1 - getLeft())/scale; float docRelY1 = (y1 - getTop())/scale; //Adjust the min/max x values between which text is selected if(Math.max(docRelX0,docRelX1)>docRelXmax) docRelXmax = Math.max(docRelX0,docRelX1); if(Math.min(docRelX0,docRelX1)<docRelXmin) docRelXmin = Math.min(docRelX0,docRelX1); // Order on Y but maintain the point grouping if (docRelY0 <= docRelY1) mSelectBox = new RectF(docRelX0, docRelY0, docRelX1, docRelY1); else mSelectBox = new RectF(docRelX1, docRelY1, docRelX0, docRelY0); mOverlayView.invalidate(); if (mGetText == null) { mGetText = new AsyncTask<Void,Void,TextWord[][]>() { @Override protected TextWord[][] doInBackground(Void... params) { return getText(); } @Override protected void onPostExecute(TextWord[][] result) { mText = result; mOverlayView.invalidate(); } }; mGetText.execute(); } } public void startDraw(final float x, final float y) { savemDrawingToHistory(); final float scale = mSourceScale*(float)getWidth()/(float)mSize.x; final float docRelX = (x - getLeft())/scale; final float docRelY = (y - getTop())/scale; if (mDrawing == null) mDrawing = new ArrayList<ArrayList<PointF>>(); ArrayList<PointF> arc = new ArrayList<PointF>(); arc.add(new PointF(docRelX, docRelY)); mDrawing.add(arc); } public void continueDraw(final float x, final float y) { final float scale = mSourceScale*(float)getWidth()/(float)mSize.x; final float docRelX = (x - getLeft())/scale; final float docRelY = (y - getTop())/scale; PointF point = new PointF(docRelX, docRelY); if (mDrawing != null && mDrawing.size() > 0) { ArrayList<PointF> arc = mDrawing.get(mDrawing.size() - 1); int lastElementIndex = arc.size()-1; // if(lastElementIndex >= 2 && PointFMath.pointToLineDistance(arc.get(lastElementIndex-2),point,arc.get(lastElementIndex-1)) < inkThickness && PointFMath.pointToLineDistance(arc.get(lastElementIndex-2),arc.get(lastElementIndex),arc.get(lastElementIndex-1)) < inkThickness) { // arc.remove(lastElementIndex-1); // if(lastElementIndex >= 2 && PointFMath.distance(arc.get(lastElementIndex-1), point) < inkThickness) // arc.remove(lastElementIndex); arc.add(point); mOverlayView.invalidate(); } } public void finishDraw() { if (mDrawing != null && mDrawing.size() > 0) { ArrayList<PointF> arc = mDrawing.get(mDrawing.size() - 1); //Make points look nice if(arc.size() == 1) { final PointF lastArc = arc.get(0); arc.add(new PointF(lastArc.x+0.5f*inkThickness,lastArc.y)); arc.add(new PointF(lastArc.x+0.5f*inkThickness,lastArc.y+0.5f*inkThickness)); arc.add(new PointF(lastArc.x,lastArc.y+0.5f*inkThickness)); arc.add(lastArc); arc.add(new PointF(lastArc.x+0.5f*inkThickness,lastArc.y)); mOverlayView.invalidate(); } } } public void startErase(final float x, final float y) { savemDrawingToHistory(); continueErase(x,y); } public void continueErase(final float x, final float y) { final float scale = mSourceScale*(float)getWidth()/(float)mSize.x; final float docRelX = (x - getLeft())/scale; final float docRelY = (y - getTop())/scale; eraser = new PointF(docRelX,docRelY); ArrayList<ArrayList<PointF>> newArcs = new ArrayList<ArrayList<PointF>>(); if (mDrawing != null && mDrawing.size() > 0) { for (ArrayList<PointF> arc : mDrawing) { Iterator<PointF> iter = arc.iterator(); PointF pointToAddToArc = null; PointF lastPoint = null; boolean newArcHasBeenCreated = false; if(iter.hasNext()) lastPoint = iter.next(); //Remove the first point if under eraser if(PointFMath.distance(lastPoint,eraser) <= eraserThickness) iter.remove(); while (iter.hasNext()) { PointF point = iter.next(); LineSegmentCircleIntersectionResult result = PointFMath.LineSegmentCircleIntersection(lastPoint , point, eraser, eraserThickness); //Act according to how the segment overlaps with the eraser if(result.intersects) { //...remove the point from the arc... iter.remove(); //If the segment enters... if(result.enter != null) { //...and either add the entry point to the current new arc or save it for later to add it to the end of the current arc if(newArcHasBeenCreated) newArcs.get(newArcs.size()-1).add(newArcs.get(newArcs.size()-1).size(),result.enter); else pointToAddToArc = result.enter; } //If the segment exits start a new arc with the exit point if(result.exit != null) { newArcHasBeenCreated = true; newArcs.add(new ArrayList<PointF>()); newArcs.get(newArcs.size()-1).add(result.exit); newArcs.get(newArcs.size()-1).add(point); } } else if(result.inside) { //Remove the point from the arc iter.remove(); } else if(newArcHasBeenCreated) { //If we have already a new arc transfer the points iter.remove(); newArcs.get(newArcs.size()-1).add(point); } lastPoint = point; } //If arc still contains points add the first entry point at the end if(arc.size() > 0 && pointToAddToArc != null) { arc.add(arc.size(),pointToAddToArc); } } //Finally add all arcs in newArcs mDrawing.addAll(newArcs); //...and remove all arcs with less then two points... Iterator<ArrayList<PointF>> iter = mDrawing.iterator(); while (iter.hasNext()) { if (iter.next().size() < 2) { iter.remove(); } } } mOverlayView.invalidate(); } public void finishErase(final float x, final float y) { continueErase(x,y); eraser = null; } public void undoDraw() { if(mDrawingHistory.size()>0) { mDrawing = mDrawingHistory.pop(); mOverlayView.invalidate(); } } public boolean canUndo() { return mDrawingHistory.size()>0; } public void cancelDraw() { mDrawing = null; mDrawingHistory.clear(); mOverlayView.invalidate(); } public int getDrawingSize() { return mDrawing == null ? 0 : mDrawing.size(); } public void setDraw(PointF[][] arcs) { if(arcs != null) { mDrawing = new ArrayList<ArrayList<PointF>>(); for(int i = 0; i < arcs.length; i++) { mDrawing.add(new ArrayList<PointF>(Arrays.asList(arcs[i]))); } } if (mOverlayView != null) mOverlayView.invalidate(); } protected PointF[][] getDraw() { if (mDrawing == null) return null; PointF[][] arcs = new PointF[mDrawing.size()][]; for (int i = 0; i < mDrawing.size(); i++) { ArrayList<PointF> arc = mDrawing.get(i); arcs[i] = arc.toArray(new PointF[arc.size()]); } return arcs; } protected void processSelectedText(TextProcessor tp) { if (useSmartTextSelection) (new TextSelector(mText, mSelectBox,docRelXmin,docRelXmax)).select(tp); else (new TextSelector(mText, mSelectBox)).select(tp); } public void setItemSelectBox(RectF rect) { mItemSelectBox = rect; if (mOverlayView != null) mOverlayView.invalidate(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int x, y; switch(View.MeasureSpec.getMode(widthMeasureSpec)) { case View.MeasureSpec.UNSPECIFIED: x = mSize.x; break; default: x = View.MeasureSpec.getSize(widthMeasureSpec); } switch(View.MeasureSpec.getMode(heightMeasureSpec)) { case View.MeasureSpec.UNSPECIFIED: y = mSize.y; break; default: y = View.MeasureSpec.getSize(heightMeasureSpec); } setMeasuredDimension(x, y); if (mBusyIndicator != null) { int limit = Math.min(mParent.getWidth(), mParent.getHeight())/2; mBusyIndicator.measure(View.MeasureSpec.AT_MOST | limit, View.MeasureSpec.AT_MOST | limit); } if (mOverlayView != null) { mOverlayView.measure(MeasureSpec.makeMeasureSpec(mParent.getWidth(), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(mParent.getHeight(), MeasureSpec.AT_MOST)); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int w = right-left; int h = bottom-top; //Layout the Hq patch if (mHqView != null && mHqView.getArea() != null) { if(mHqView.getArea().width() != w || mHqView.getArea().height() != h) { // Remove Hq if zoomed since patch was created mHqView.reset(); } else { mHqView.layout(mHqView.getLeft(), mHqView.getTop(), mHqView.getRight(), mHqView.getBottom()); } } //Layout the entire page view if (mEntireView != null) { //Draw mEntireView only if it is not completely covered by a Hq patch if(mHqView != null && mHqView.getDrawable() != null && mHqView.getLeft() == left && mHqView.getTop() == top && mHqView.getRight() == right && mHqView.getBottom() == bottom ) { mEntireView.setVisibility(View.GONE); } else { mEntireView.setVisibility(View.VISIBLE); mEntireMat.setScale(w/(float)mSize.x, h/(float)mSize.y); mEntireView.setImageMatrix(mEntireMat); mEntireView.invalidate(); mEntireView.layout(0, 0, w, h); } } //Layout the overlay view if (mOverlayView != null) { mOverlayView.layout(-left, -top, -left+mOverlayView.getMeasuredWidth(), -top+mOverlayView.getMeasuredHeight()); mOverlayView.invalidate(); } //Layout the busy indicator if (mBusyIndicator != null) { int bw = mBusyIndicator.getMeasuredWidth(); int bh = mBusyIndicator.getMeasuredHeight(); mBusyIndicator.layout((w-bw)/2, (h-bh)/2, (w+bw)/2, (h+bh)/2); } } public void addEntire(boolean update) { Rect viewArea = new Rect(0,0,mParent.getWidth(),mParent.getHeight()); //Create a bitmap of the right size (is this really correct?) if(mEntireBm == null || mParent.getWidth() != mEntireBm.getWidth() || mParent.getHeight() != mEntireBm.getHeight()) { mEntireBm = Bitmap.createBitmap(mParent.getWidth(), mParent.getHeight(), Config.ARGB_8888); } //Construct the PatchInfo PatchInfo patchInfo = new PatchInfo(viewArea, mEntireBm, mEntire, update); //If there is no itersection there is no need to draw anything if(!patchInfo.intersects) return; // If being asked for the same area as last time and not because of an update then nothing to do if (!patchInfo.areaChanged && !update) return; // Create and add the patch view if not already done if (mEntire == null) { mEntire = new PatchView(mContext); addView(mEntire); if(mOverlayView != null) mOverlayView.bringToFront(); } mEntire.renderInBackground(patchInfo); } public void addHq(boolean update) { Rect viewArea = new Rect(getLeft(),getTop(),getRight(),getBottom()); // If the viewArea's size matches the unzoomed size, there is no need for a hq patch if (viewArea.width() == mSize.x && viewArea.height() == mSize.y) return; //Construct the PatchInfo (important: the bitmap is shared between all page views that belong to a given readerview, so we ask the ReadderView to provide it) PatchInfo patchInfo = new PatchInfo(viewArea, ((ReaderView)mParent).getPatchBm(), mHqView, update); //If there is no itersection there is no need to draw anything if(!patchInfo.intersects) return; // If being asked for the same area as last time and not because of an update then nothing to do if (!patchInfo.areaChanged && !update) return; // Create and add the patch view if not already done if (mHqView == null) { mHqView = new PatchView(mContext); addView(mHqView); if(mOverlayView != null) mOverlayView.bringToFront(); } mHqView.renderInBackground(patchInfo); } public void update() { update(false); } public void update(final boolean cancelDrawInOnPostExecute) { // Cancel pending render task if (mDrawEntire != null) { mDrawEntire.cancel(true); mDrawEntire = null; } // if (mDrawPatch != null) { // mDrawPatch.cancel(true); // mDrawPatch = null; if(mHqView != null) mHqView.cancelRenderInBackground(); // // Render the page in the background // mDrawEntire = new AsyncTask<Void,Void,Void>() { // protected Void doInBackground(Void... v) { // updatePage(mEntireBm, mSize.x, mSize.y, 0, 0, mSize.x, mSize.y); // return null; // protected void onPostExecute(Void v) { // if(mBusyIndicator!=null) // mBusyIndicator.setVisibility(INVISIBLE); // removeView(mBusyIndicator); // mBusyIndicator = null; // mEntireView.setImageBitmap(mEntireBm); // mEntireView.invalidate(); // if(cancelDrawInOnPostExecute) cancelDraw(); // protected void onCanceled() { // if(mBusyIndicator!=null) // mBusyIndicator.setVisibility(INVISIBLE); // removeView(mBusyIndicator); // mBusyIndicator = null; // if(cancelDrawInOnPostExecute) cancelDraw(); // mDrawEntire.execute(); addEntire(true); addHq(true); } public void removeHq() { if (mHqView != null) mHqView.reset(); } public float getScale() { return mSourceScale*(float)getWidth()/(float)mSize.x; } public void setSearchResult(SearchResult searchTaskResult) { mSearchResult = searchTaskResult; } public static void onSharedPreferenceChanged(SharedPreferences sharedPref, String key) { //Set ink thickness and colors for PageView inkThickness = Float.parseFloat(sharedPref.getString(SettingsActivity.PREF_INK_THICKNESS, Float.toString(inkThickness))); eraserThickness = Float.parseFloat(sharedPref.getString(SettingsActivity.PREF_ERASER_THICKNESS, Float.toString(eraserThickness))); inkColor = ColorPalette.getHex(Integer.parseInt(sharedPref.getString(SettingsActivity.PREF_INK_COLOR, Integer.toString(inkColor)))); highlightColor = ColorPalette.getHex(Integer.parseInt(sharedPref.getString(SettingsActivity.PREF_HIGHLIGHT_COLOR, Integer.toString(highlightColor)))); underlineColor = ColorPalette.getHex(Integer.parseInt(sharedPref.getString(SettingsActivity.PREF_UNDERLINE_COLOR, Integer.toString(underlineColor)))); strikeoutColor = ColorPalette.getHex(Integer.parseInt(sharedPref.getString(SettingsActivity.PREF_STRIKEOUT_COLOR, Integer.toString(strikeoutColor)))); //Find out whether or not to use smart text selection useSmartTextSelection = sharedPref.getBoolean(SettingsActivity.PREF_SMART_TEXT_SELECTION, true); } private void savemDrawingToHistory() { if(mDrawing != null) { ArrayList<ArrayList<PointF>> mDrawingCopy = new ArrayList<ArrayList<PointF>>(mDrawing.size()); for(int i = 0; i < mDrawing.size(); i++) { mDrawingCopy.add(new ArrayList<PointF>(mDrawing.get(i))); } mDrawingHistory.push(mDrawingCopy); } else { mDrawingHistory.push(new ArrayList<ArrayList<PointF>>(0)); } } @Override public Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); bundle.putParcelable("superInstanceState", super.onSaveInstanceState()); //Save bundle.putSerializable("mDrawing", mDrawing); bundle.putSerializable("mDrawingHistory", mDrawingHistory); return bundle; } @Override public void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { Bundle bundle = (Bundle) state; //Load mDrawing = (ArrayList<ArrayList<PointF>>)bundle.getSerializable("mDrawing"); mDrawingHistory = (ArrayDeque<ArrayList<ArrayList<PointF>>>)bundle.getSerializable("mDrawingHistory"); state = bundle.getParcelable("superInstanceState"); } super.onRestoreInstanceState(state); } }
package com.intellij.openapi.util; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.StringInterner; import com.intellij.util.io.URLUtil; import com.intellij.util.text.CharArrayUtil; import com.intellij.util.text.CharSequenceReader; import org.jdom.*; import org.jdom.filter.Filter; import org.jdom.input.SAXBuilder; import org.jdom.input.sax.SAXHandler; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import javax.xml.XMLConstants; import java.io.*; import java.lang.ref.SoftReference; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * @author mike */ @SuppressWarnings("HardCodedStringLiteral") public class JDOMUtil { private static final ThreadLocal<SoftReference<SAXBuilder>> ourSaxBuilder = new ThreadLocal<SoftReference<SAXBuilder>>(); private static final Condition<Attribute> NOT_EMPTY_VALUE_CONDITION = new Condition<Attribute>() { @Override public boolean value(Attribute attribute) { return !StringUtil.isEmpty(attribute.getValue()); } }; private JDOMUtil() { } @NotNull public static List<Element> getChildren(@Nullable Element parent) { return parent == null ? Collections.<Element>emptyList() : parent.getChildren(); } @NotNull public static List<Element> getChildren(@Nullable Element parent, @NotNull String name) { if (parent != null) { return parent.getChildren(name); } return Collections.emptyList(); } @SuppressWarnings("UtilityClassWithoutPrivateConstructor") private static class LoggerHolder { private static final Logger ourLogger = Logger.getInstance("#com.intellij.openapi.util.JDOMUtil"); } private static Logger getLogger() { return LoggerHolder.ourLogger; } public static boolean areElementsEqual(@Nullable Element e1, @Nullable Element e2) { return areElementsEqual(e1, e2, false); } /** * * @param ignoreEmptyAttrValues defines if elements like <element foo="bar" skip_it=""/> and <element foo="bar"/> are 'equal' * @return {@code true} if two elements are deep-equals by their content and attributes */ public static boolean areElementsEqual(@Nullable Element e1, @Nullable Element e2, boolean ignoreEmptyAttrValues) { if (e1 == null && e2 == null) return true; if (e1 == null || e2 == null) return false; return Comparing.equal(e1.getName(), e2.getName()) && isAttributesEqual(e1.getAttributes(), e2.getAttributes(), ignoreEmptyAttrValues) && contentListsEqual(e1.getContent(CONTENT_FILTER), e2.getContent(CONTENT_FILTER), ignoreEmptyAttrValues); } private static final EmptyTextFilter CONTENT_FILTER = new EmptyTextFilter(); public static int getTreeHash(@NotNull Element root) { return addToHash(0, root, true); } private static int addToHash(int i, @NotNull Element element, boolean skipEmptyText) { i = addToHash(i, element.getName()); for (Attribute attribute : element.getAttributes()) { i = addToHash(i, attribute.getName()); i = addToHash(i, attribute.getValue()); } for (Content child : element.getContent()) { if (child instanceof Element) { i = addToHash(i, (Element)child, skipEmptyText); } else if (child instanceof Text) { String text = ((Text)child).getText(); if (!skipEmptyText || !StringUtil.isEmptyOrSpaces(text)) { i = addToHash(i, text); } } } return i; } private static int addToHash(int i, @NotNull String s) { return i * 31 + s.hashCode(); } /** * @deprecated Use {@link Element#getChildren} instead */ @NotNull @Deprecated public static Element[] getElements(@NotNull Element m) { List<Element> list = m.getChildren(); return list.toArray(new Element[0]); } /** * Replace all strings in JDOM {@code element} with their interned variants with the help of {@code interner} to reduce memory. * It's better to use {@link #internElement(Element)} though because the latter will intern the Element instances too. */ public static void internStringsInElement(@NotNull Element element, @NotNull StringInterner interner) { element.setName(interner.intern(element.getName())); for (Attribute attr : element.getAttributes()) { attr.setName(interner.intern(attr.getName())); attr.setValue(interner.intern(attr.getValue())); } for (Content o : element.getContent()) { if (o instanceof Element) { internStringsInElement((Element)o, interner); } else if (o instanceof Text) { ((Text)o).setText(interner.intern(o.getValue())); } } } @NotNull public static String legalizeText(@NotNull String str) { return legalizeChars(str).toString(); } @NotNull public static CharSequence legalizeChars(@NotNull CharSequence str) { StringBuilder result = new StringBuilder(str.length()); for (int i = 0, len = str.length(); i < len; i ++) { appendLegalized(result, str.charAt(i)); } return result; } private static void appendLegalized(@NotNull StringBuilder sb, char each) { if (each == '<' || each == '>') { sb.append(each == '<' ? "&lt;" : "&gt;"); } else if (!Verifier.isXMLCharacter(each)) { sb.append("0x").append(StringUtil.toUpperCase(Long.toHexString(each))); } else { sb.append(each); } } private static class EmptyTextFilter implements Filter { @Override public boolean matches(Object obj) { return !(obj instanceof Text) || !CharArrayUtil.containsOnlyWhiteSpaces(((Text)obj).getText()); } } private static boolean contentListsEqual(final List c1, final List c2, boolean ignoreEmptyAttrValues) { if (c1 == null && c2 == null) return true; if (c1 == null || c2 == null) return false; Iterator l1 = c1.listIterator(); Iterator l2 = c2.listIterator(); while (l1.hasNext() && l2.hasNext()) { if (!contentsEqual((Content)l1.next(), (Content)l2.next(), ignoreEmptyAttrValues)) { return false; } } return l1.hasNext() == l2.hasNext(); } private static boolean contentsEqual(Content c1, Content c2, boolean ignoreEmptyAttrValues) { if (!(c1 instanceof Element) && !(c2 instanceof Element)) { return c1.getValue().equals(c2.getValue()); } return c1 instanceof Element && c2 instanceof Element && areElementsEqual((Element)c1, (Element)c2, ignoreEmptyAttrValues); } private static boolean isAttributesEqual(@NotNull List<Attribute> l1, @NotNull List<Attribute> l2, boolean ignoreEmptyAttrValues) { if (ignoreEmptyAttrValues) { l1 = ContainerUtil.filter(l1, NOT_EMPTY_VALUE_CONDITION); l2 = ContainerUtil.filter(l2, NOT_EMPTY_VALUE_CONDITION); } if (l1.size() != l2.size()) return false; for (int i = 0; i < l1.size(); i++) { if (!attEqual(l1.get(i), l2.get(i))) return false; } return true; } private static boolean attEqual(@NotNull Attribute a1, @NotNull Attribute a2) { return a1.getName().equals(a2.getName()) && a1.getValue().equals(a2.getValue()); } private static SAXBuilder getSaxBuilder() { SoftReference<SAXBuilder> reference = ourSaxBuilder.get(); SAXBuilder saxBuilder = com.intellij.reference.SoftReference.dereference(reference); if (saxBuilder == null) { saxBuilder = new SAXBuilder() { @Override protected void configureParser(XMLReader parser, SAXHandler contentHandler) throws JDOMException { super.configureParser(parser, contentHandler); try { parser.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (Exception ignore) { } } }; saxBuilder.setEntityResolver(new EntityResolver() { @Override @NotNull public InputSource resolveEntity(String publicId, String systemId) { return new InputSource(new CharArrayReader(ArrayUtil.EMPTY_CHAR_ARRAY)); } }); saxBuilder.setIgnoringBoundaryWhitespace(true); ourSaxBuilder.set(new SoftReference<SAXBuilder>(saxBuilder)); } return saxBuilder; } /** * @deprecated Use {@link #load(CharSequence)} * * Direct usage of element allows to get rid of {@link Document#getRootElement()} because only Element is required in mostly all cases. */ @NotNull @Deprecated public static Document loadDocument(@NotNull CharSequence seq) throws IOException, JDOMException { return loadDocument(new CharSequenceReader(seq)); } public static Element load(@NotNull CharSequence seq) throws IOException, JDOMException { return load(new CharSequenceReader(seq)); } @NotNull private static Document loadDocument(@NotNull Reader reader) throws IOException, JDOMException { try { return getSaxBuilder().build(reader); } finally { reader.close(); } } @NotNull public static Document loadDocument(File file) throws JDOMException, IOException { return loadDocument(new BufferedInputStream(new FileInputStream(file))); } @NotNull public static Element load(@NotNull File file) throws JDOMException, IOException { return load(new BufferedInputStream(new FileInputStream(file))); } @NotNull public static Document loadDocument(@NotNull InputStream stream) throws JDOMException, IOException { return loadDocument(new InputStreamReader(stream, CharsetToolkit.UTF8_CHARSET)); } public static Element load(Reader reader) throws JDOMException, IOException { return reader == null ? null : loadDocument(reader).detachRootElement(); } /** * Consider to use `loadElement` (JdomKt.loadElement from java) due to more efficient whitespace handling (cannot be changed here due to backward compatibility). */ @Contract("null -> null; !null -> !null") public static Element load(InputStream stream) throws JDOMException, IOException { return stream == null ? null : loadDocument(stream).detachRootElement(); } @NotNull public static Document loadDocument(@NotNull Class clazz, String resource) throws JDOMException, IOException { InputStream stream = clazz.getResourceAsStream(resource); if (stream == null) { throw new FileNotFoundException(resource); } return loadDocument(stream); } @NotNull public static Document loadDocument(@NotNull URL url) throws JDOMException, IOException { return loadDocument(URLUtil.openStream(url)); } @NotNull public static Document loadResourceDocument(URL url) throws JDOMException, IOException { return loadDocument(URLUtil.openResourceStream(url)); } public static void writeDocument(@NotNull Document document, @NotNull String filePath, String lineSeparator) throws IOException { OutputStream stream = new BufferedOutputStream(new FileOutputStream(filePath)); try { writeDocument(document, stream, lineSeparator); } finally { stream.close(); } } public static void writeDocument(@NotNull Document document, @NotNull File file, String lineSeparator) throws IOException { write(document, file, lineSeparator); } public static void write(@NotNull Parent element, @NotNull File file) throws IOException { write(element, file, "\n"); } public static void write(@NotNull Parent element, @NotNull File file, @NotNull String lineSeparator) throws IOException { FileUtil.createParentDirs(file); OutputStream stream = new BufferedOutputStream(new FileOutputStream(file)); try { write(element, stream, lineSeparator); } finally { stream.close(); } } public static void writeDocument(@NotNull Document document, @NotNull OutputStream stream, String lineSeparator) throws IOException { write(document, stream, lineSeparator); } public static void write(@NotNull Parent element, @NotNull OutputStream stream, @NotNull String lineSeparator) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(stream, CharsetToolkit.UTF8_CHARSET); try { if (element instanceof Document) { writeDocument((Document)element, writer, lineSeparator); } else { writeElement((Element) element, writer, lineSeparator); } } finally { writer.close(); } } @NotNull public static String writeDocument(@NotNull Document document, String lineSeparator) { try { final StringWriter writer = new StringWriter(); writeDocument(document, writer, lineSeparator); return writer.toString(); } catch (IOException ignored) { // Can't be return ""; } } @NotNull public static String write(Parent element, String lineSeparator) { try { final StringWriter writer = new StringWriter(); write(element, writer, lineSeparator); return writer.toString(); } catch (IOException e) { throw new RuntimeException(e); } } public static void write(Parent element, Writer writer, String lineSeparator) throws IOException { if (element instanceof Element) { writeElement((Element) element, writer, lineSeparator); } else if (element instanceof Document) { writeDocument((Document) element, writer, lineSeparator); } } public static void writeElement(@NotNull Element element, Writer writer, String lineSeparator) throws IOException { writeElement(element, writer, createOutputter(lineSeparator)); } public static void writeElement(@NotNull Element element, @NotNull Writer writer, @NotNull XMLOutputter xmlOutputter) throws IOException { try { xmlOutputter.output(element, writer); } catch (NullPointerException ex) { getLogger().error(ex); printDiagnostics(element, ""); } } @NotNull public static String writeElement(@NotNull Element element) { return writeElement(element, "\n"); } @NotNull public static String writeElement(@NotNull Element element, String lineSeparator) { try { final StringWriter writer = new StringWriter(); writeElement(element, writer, lineSeparator); return writer.toString(); } catch (IOException e) { throw new RuntimeException(e); } } @NotNull public static String writeChildren(@NotNull final Element element, @NotNull final String lineSeparator) throws IOException { final StringWriter writer = new StringWriter(); for (Element child : element.getChildren()) { writeElement(child, writer, lineSeparator); writer.append(lineSeparator); } return writer.toString(); } public static void writeDocument(@NotNull Document document, @NotNull Writer writer, String lineSeparator) throws IOException { XMLOutputter xmlOutputter = createOutputter(lineSeparator); try { xmlOutputter.output(document, writer); } catch (NullPointerException ex) { getLogger().error(ex); printDiagnostics(document.getRootElement(), ""); } } @NotNull public static Format createFormat(@Nullable String lineSeparator) { return Format.getCompactFormat() .setIndent(" ") .setTextMode(Format.TextMode.TRIM) .setEncoding(CharsetToolkit.UTF8) .setOmitEncoding(false) .setOmitDeclaration(false) .setLineSeparator(lineSeparator); } @NotNull public static XMLOutputter createOutputter(String lineSeparator) { return new MyXMLOutputter(createFormat(lineSeparator)); } /** * Returns null if no escapement necessary. */ @Nullable private static String escapeChar(char c, boolean escapeApostrophes, boolean escapeSpaces, boolean escapeLineEnds) { switch (c) { case '\n': return escapeLineEnds ? "&#10;" : null; case '\r': return escapeLineEnds ? "&#13;" : null; case '\t': return escapeLineEnds ? "&#9;" : null; case ' ' : return escapeSpaces ? "&#20" : null; case '<': return "&lt;"; case '>': return "&gt;"; case '\"': return "&quot;"; case '\'': return escapeApostrophes ? "&apos;": null; case '&': return "&amp;"; } return null; } @NotNull public static String escapeText(@NotNull String text) { return escapeText(text, false, false); } @NotNull public static String escapeText(@NotNull String text, boolean escapeSpaces, boolean escapeLineEnds) { return escapeText(text, false, escapeSpaces, escapeLineEnds); } @NotNull public static String escapeText(@NotNull String text, boolean escapeApostrophes, boolean escapeSpaces, boolean escapeLineEnds) { StringBuilder buffer = null; for (int i = 0; i < text.length(); i++) { final char ch = text.charAt(i); final String quotation = escapeChar(ch, escapeApostrophes, escapeSpaces, escapeLineEnds); if (buffer == null) { if (quotation != null) { // An quotation occurred, so we'll have to use StringBuffer // (allocate room for it plus a few more entities). buffer = new StringBuilder(text.length() + 20); // Copy previous skipped characters and fall through // to pickup current character buffer.append(text, 0, i); buffer.append(quotation); } } else if (quotation == null) { buffer.append(ch); } else { buffer.append(quotation); } } // If there were any entities, return the escaped characters // that we put in the StringBuffer. Otherwise, just return // the unmodified input string. return buffer == null ? text : buffer.toString(); } private final static class MyXMLOutputter extends XMLOutputter { public MyXMLOutputter(@NotNull Format format) { super(format); } @Override @NotNull public String escapeAttributeEntities(@NotNull String str) { return escapeText(str, false, true); } @Override @NotNull public String escapeElementEntities(@NotNull String str) { return escapeText(str, false, false); } } public interface ElementOutputFilter { boolean accept(@NotNull Element element, int level); } private static void printDiagnostics(@NotNull Element element, String prefix) { ElementInfo info = getElementInfo(element); prefix += "/" + info.name; if (info.hasNullAttributes) { //noinspection UseOfSystemOutOrSystemErr System.err.println(prefix); } for (final Element child : element.getChildren()) { printDiagnostics(child, prefix); } } @NotNull private static ElementInfo getElementInfo(@NotNull Element element) { boolean hasNullAttributes = false; StringBuilder buf = new StringBuilder(element.getName()); List attributes = element.getAttributes(); if (attributes != null) { int length = attributes.size(); if (length > 0) { buf.append("["); for (int idx = 0; idx < length; idx++) { Attribute attr = (Attribute)attributes.get(idx); if (idx != 0) { buf.append(";"); } buf.append(attr.getName()); buf.append("="); buf.append(attr.getValue()); if (attr.getValue() == null) { hasNullAttributes = true; } } buf.append("]"); } } return new ElementInfo(buf, hasNullAttributes); } public static void updateFileSet(@NotNull File[] oldFiles, @NotNull String[] newFilePaths, @NotNull Document[] newFileDocuments, String lineSeparator) throws IOException { getLogger().assertTrue(newFilePaths.length == newFileDocuments.length); // check if files are writable for (String newFilePath : newFilePaths) { File file = new File(newFilePath); if (file.exists() && !file.canWrite()) { throw new IOException("File \"" + newFilePath + "\" is not writeable"); } } for (File file : oldFiles) { if (file.exists() && !file.canWrite()) { throw new IOException("File \"" + file.getAbsolutePath() + "\" is not writeable"); } } List<String> writtenFilesPaths = new ArrayList<String>(); for (int i = 0; i < newFilePaths.length; i++) { String newFilePath = newFilePaths[i]; writeDocument(newFileDocuments[i], newFilePath, lineSeparator); writtenFilesPaths.add(newFilePath); } // delete files if necessary outer: for (File oldFile : oldFiles) { String oldFilePath = oldFile.getAbsolutePath(); for (final String writtenFilesPath : writtenFilesPaths) { if (oldFilePath.equals(writtenFilesPath)) { continue outer; } } boolean result = oldFile.delete(); if (!result) { throw new IOException("File \"" + oldFilePath + "\" was not deleted"); } } } private static class ElementInfo { @NotNull final CharSequence name; final boolean hasNullAttributes; private ElementInfo(@NotNull CharSequence name, boolean attributes) { this.name = name; hasNullAttributes = attributes; } } public static String getValue(Object node) { if (node instanceof Content) { Content content = (Content)node; return content.getValue(); } else if (node instanceof Attribute) { Attribute attribute = (Attribute)node; return attribute.getValue(); } else { throw new IllegalArgumentException("Wrong node: " + node); } } public static boolean isEmpty(@Nullable Element element) { return element == null || element.getAttributes().isEmpty() && element.getContent().isEmpty(); } public static boolean isEmpty(@Nullable Element element, int attributeCount) { return element == null || element.getAttributes().size() == attributeCount && element.getContent().isEmpty(); } @Nullable public static Element merge(@Nullable Element to, @Nullable Element from) { if (from == null) { return to; } if (to == null) { return from; } for (Iterator<Element> iterator = from.getChildren().iterator(); iterator.hasNext(); ) { Element configuration = iterator.next(); iterator.remove(); to.addContent(configuration); } for (Iterator<Attribute> iterator = from.getAttributes().iterator(); iterator.hasNext(); ) { Attribute attribute = iterator.next(); iterator.remove(); to.setAttribute(attribute); } return to; } @NotNull public static Element deepMerge(@NotNull Element to, @NotNull Element from) { for (Iterator<Element> iterator = from.getChildren().iterator(); iterator.hasNext(); ) { Element child = iterator.next(); iterator.remove(); Element existingChild = to.getChild(child.getName()); if (existingChild != null && isEmpty(existingChild)) { // replace empty tag to.removeChild(child.getName()); existingChild = null; } // if no children (e.g. `<module fileurl="value" />`), it means that element should be added as list item if (existingChild == null || existingChild.getChildren().isEmpty() || !isAttributesEqual(existingChild.getAttributes(), child.getAttributes(), false)) { to.addContent(child); } else { deepMerge(existingChild, child); } } for (Iterator<Attribute> iterator = from.getAttributes().iterator(); iterator.hasNext(); ) { Attribute attribute = iterator.next(); iterator.remove(); to.setAttribute(attribute); } return to; } private static final JDOMInterner ourJDOMInterner = new JDOMInterner(); /** * Interns {@code element} to reduce instance count of many identical Elements created after loading JDOM document to memory. * For example, after interning <pre>{@code * <app> * <component load="true" isDefault="true" name="comp1"/> * <component load="true" isDefault="true" name="comp2"/> * </app>}</pre> * * there will be created just one XmlText("\n ") instead of three for whitespaces between tags, * one Attribute("load=true") instead of two equivalent for each component tag etc. * * <p><h3>Intended usage:</h3> * - When you need to keep some part of JDOM tree in memory, use this method before save the element to some collection, * E.g.: <pre>{@code * public void readExternal(final Element element) { * myStoredElement = JDOMUtil.internElement(element); * } * }</pre> * - When you need to save interned element back to JDOM and/or modify/add it, use {@link ImmutableElement#clone()} * to obtain mutable modifiable Element. * E.g.: <pre>{@code * void writeExternal(Element element) { * for (Attribute a : myStoredElement.getAttributes()) { * element.setAttribute(a.getName(), a.getValue()); // String getters work as before * } * for (Element child : myStoredElement.getChildren()) { * element.addContent(child.clone()); // need to call clone() before modifying/adding * } * } * }</pre> * * @return interned Element, i.e Element which<br/> * - is the same for equivalent parameters. E.g. two calls of internElement() with {@code <xxx/>} and the other {@code <xxx/>} * will return the same element {@code <xxx/>}<br/> * - getParent() method is not implemented (and will throw exception; interning would not make sense otherwise)<br/> * - is immutable (all modifications methods like setName(), setParent() etc will throw)<br/> * - has {@code clone()} method which will return modifiable org.jdom.Element copy.<br/> * * */ @NotNull public static Element internElement(@NotNull Element element) { return ourJDOMInterner.internElement(element); } }
package com.intellij.util; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; /** * Utility wrappers for accessing system properties. * * @see com.intellij.openapi.util.SystemInfo */ public final class SystemProperties { private SystemProperties() { } public static @NotNull String getUserHome() { return System.getProperty("user.home"); } public static @NotNull String getUserName() { return System.getProperty("user.name"); } public static @NotNull String getJavaHome() { return System.getProperty("java.home"); } /** * Returns a value of the given property as an integer, or {@code defaultValue} if the property is not specified or malformed. */ public static int getIntProperty(@NotNull String key, int defaultValue) { String value = System.getProperty(key); if (value != null) { try { return Integer.parseInt(value); } catch (NumberFormatException ignored) { } } return defaultValue; } /** * Returns a value of the given property as a float, or {@code defaultValue} if the property is not specified or malformed. */ public static float getFloatProperty(@NotNull String key, float defaultValue) { String value = System.getProperty(key); if (value != null) { try { return Float.parseFloat(value); } catch (NumberFormatException ignored) { } } return defaultValue; } /** * Returns a value of the given property as a boolean, or {@code defaultValue} if the property is not specified or malformed. */ public static boolean getBooleanProperty(@NotNull String key, boolean defaultValue) { String value = System.getProperty(key); return value != null ? Boolean.parseBoolean(value) : defaultValue; } public static boolean is(String key) { return getBooleanProperty(key, false); } public static boolean has(String key) { return System.getProperty(key) != null; } //<editor-fold desc="Deprecated stuff."> /** @deprecated please use {@link System#lineSeparator()} instead */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2022.1") public static String getLineSeparator() { return System.lineSeparator(); } /** @deprecated moved to {@link com.intellij.openapi.editor.EditorCoreUtil} */ @Deprecated @ApiStatus.ScheduledForRemoval(inVersion = "2022.1") public static boolean isTrueSmoothScrollingEnabled() { return getBooleanProperty("idea.true.smooth.scrolling", false); } //</editor-fold> }
package org.wangzw.plugin.cppstyle; import java.net.URI; import org.eclipse.cdt.codan.core.CodanRuntime; import org.eclipse.cdt.codan.core.cxx.externaltool.ArgsSeparator; import org.eclipse.cdt.codan.core.cxx.externaltool.InvocationFailure; import org.eclipse.cdt.codan.core.model.AbstractCheckerWithProblemPreferences; import org.eclipse.cdt.codan.core.model.CheckerLaunchMode; import org.eclipse.cdt.codan.core.model.IProblem; import org.eclipse.cdt.codan.core.model.IProblemLocation; import org.eclipse.cdt.codan.core.model.IProblemLocationFactory; import org.eclipse.cdt.codan.core.model.IProblemWorkingCopy; import org.eclipse.cdt.codan.core.param.FileScopeProblemPreference; import org.eclipse.cdt.codan.core.param.LaunchModeProblemPreference; import org.eclipse.cdt.codan.core.param.MapProblemPreference; import org.eclipse.cdt.codan.core.param.RootProblemPreference; import org.eclipse.cdt.codan.core.param.SharedRootProblemPreference; import org.eclipse.cdt.core.ErrorParserManager; import org.eclipse.cdt.core.IConsoleParser; import org.eclipse.cdt.core.IMarkerGenerator; import org.eclipse.cdt.core.ProblemMarkerInfo; import org.eclipse.core.filesystem.URIUtil; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.Path; import org.wangzw.plugin.cppstyle.ui.CppStyleConstants; import org.wangzw.plugin.cppstyle.ui.CppStyleMessageConsole; public class CpplintChecker extends AbstractCheckerWithProblemPreferences implements IMarkerGenerator { private final ArgsSeparator argsSeparator; private final CpplintCheckSettings settings; private final CpplintInvoker invoker; private final RootProblemPreference preferences; /** * Constructor. */ public CpplintChecker() { this.argsSeparator = new ArgsSeparator(); this.settings = new CpplintCheckSettings(); this.invoker = new CpplintInvoker(); this.preferences = new SharedRootProblemPreference(); } /** * Returns {@code false} because this checker cannot run "as you type" by * default. * * @return {@code false}. */ @Override public boolean runInEditor() { return false; } @Override public boolean processResource(IResource resource) { if (!shouldProduceProblems(resource)) { return false; } if (!CpplintCheckSettings.checkCpplint(resource)) { return false; } process(resource); return false; } private void process(IResource resource) { try { CppStyleMessageConsole console = CppStyle.buildConsole(); console.getListener().setFile((IFile) resource); String path = resource.getLocation().toOSString(); InvocationParameters parameters = new InvocationParameters(resource, resource, path, null, console); if (parameters != null) { invokeExternalTool(parameters); } } catch (Throwable error) { logResourceProcessingFailure(error, resource); } } private void invokeExternalTool(InvocationParameters parameters) throws Throwable { updateConfigurationSettingsFromPreferences(parameters.getActualFile()); IConsoleParser[] parsers = new IConsoleParser[] { createErrorParserManager(parameters) }; try { invoker.invoke(parameters, settings, argsSeparator, parsers); } catch (InvocationFailure error) { handleInvocationFailure(error, parameters); } } private void updateConfigurationSettingsFromPreferences(IResource fileToProcess) { settings.updateValuesFrom((IFile) fileToProcess); } private ErrorParserManager createErrorParserManager(InvocationParameters parameters) { IProject project = parameters.getActualFile().getProject(); URI workingDirectory = URIUtil.toURI(parameters.getWorkingDirectory()); return new ErrorParserManager(project, workingDirectory, this, getParserIDs()); } /** * @return the IDs of the parsers to use to parse the output of the external * tool. */ protected String[] getParserIDs() { return new String[] { CppStyleConstants.CPPLINT_OUTPUT_PARSER_ID }; } /** * Handles a failure reported when invoking the external tool. This * implementation simply logs the failure. * * @param error * the reported failure. * @param parameters * the parameters passed to the external tool executable. */ protected void handleInvocationFailure(InvocationFailure error, InvocationParameters parameters) { logResourceProcessingFailure(error, parameters.getActualFile()); } private void logResourceProcessingFailure(Throwable error, IResource resource) { String location = resource.getLocation().toOSString(); String msg = String.format("Unable to process resource %s", location); //$NON-NLS-1$ CppStyle.log(msg, error); } /** * Returns the id of the problem used as reference to obtain this checker's * preferences. All preferences in a external-tool-based checker are shared * among its defined problems. * * @return the id of the problem used as reference to obtain this checker's * preferences. */ protected String getReferenceProblemId() { return CppStyleConstants.CPPLINT_ERROR_PROBLEM_ID; } @Override public void initPreferences(IProblemWorkingCopy problem) { getTopLevelPreference(problem); // initialize FileScopeProblemPreference scope = getScopePreference(problem); Path[] value = new Path[5]; value[0] = new Path("*.cc"); value[1] = new Path("*.h"); value[2] = new Path("*.cpp"); value[3] = new Path("*.cu"); value[4] = new Path("*.cuh"); scope.setAttribute(FileScopeProblemPreference.INCLUSION, value); LaunchModeProblemPreference launch = getLaunchModePreference(problem); launch.setRunningMode(CheckerLaunchMode.RUN_ON_FULL_BUILD, false); launch.setRunningMode(CheckerLaunchMode.RUN_ON_INC_BUILD, false); launch.setRunningMode(CheckerLaunchMode.RUN_ON_FILE_OPEN, false); launch.setRunningMode(CheckerLaunchMode.RUN_ON_FILE_SAVE, true); launch.setRunningMode(CheckerLaunchMode.RUN_AS_YOU_TYPE, false); launch.setRunningMode(CheckerLaunchMode.RUN_ON_DEMAND, true); } @Override protected void setDefaultPreferenceValue(IProblemWorkingCopy problem, String key, Object defaultValue) { MapProblemPreference map = getTopLevelPreference(problem); map.setChildValue(key, defaultValue); } @Override public RootProblemPreference getTopLevelPreference(IProblem problem) { RootProblemPreference map = (RootProblemPreference) problem.getPreference(); if (map == null) { map = preferences; if (problem instanceof IProblemWorkingCopy) { ((IProblemWorkingCopy) problem).setPreference(map); } } return map; } @Deprecated @Override public void addMarker(IResource file, int lineNumber, String description, int severity, String variableName) { addMarker(new ProblemMarkerInfo(file, lineNumber, description, severity, variableName)); } @Override public void addMarker(ProblemMarkerInfo info) { String problemId = info.getAttribute(CppStyleConstants.CPPLINT_PROBLEM_ID_KEY); reportProblem(problemId, createProblemLocation(info), info.description); } protected IProblemLocation createProblemLocation(ProblemMarkerInfo info) { IProblemLocationFactory factory = CodanRuntime.getInstance().getProblemLocationFactory(); return factory.createProblemLocation((IFile) info.file, info.startChar, info.endChar, info.lineNumber); } }
package com.intellij.cvsSupport2; import com.intellij.CvsBundle; import com.intellij.cvsSupport2.application.CvsEntriesManager; import com.intellij.cvsSupport2.application.CvsInfo; import com.intellij.cvsSupport2.config.CvsApplicationLevelConfiguration; import com.intellij.cvsSupport2.connections.CvsConnectionSettings; import com.intellij.cvsSupport2.connections.CvsRootParser; import com.intellij.cvsSupport2.cvsstatuses.CvsStatusProvider; import com.intellij.cvsSupport2.util.CvsFileUtil; import com.intellij.cvsSupport2.util.CvsVfsUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.util.text.SyncDateFormat; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.netbeans.lib.cvsclient.admin.Entries; import org.netbeans.lib.cvsclient.admin.EntriesHandler; import org.netbeans.lib.cvsclient.admin.Entry; import javax.swing.*; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.*; public class CvsUtil { private final static SyncDateFormat DATE_FORMATTER = new SyncDateFormat(new SimpleDateFormat(Entry.getLastModifiedDateFormatter().toPattern(), Locale.US)); static { //noinspection HardCodedStringLiteral DATE_FORMATTER.setTimeZone(TimeZone.getTimeZone("GMT+0000")); } @NonNls public static final String CVS_IGNORE_FILE = ".cvsignore"; @NonNls public static final String CVS_ROOT_FILE = "Root"; private static final Logger LOG = Logger.getInstance("#com.intellij.cvsSupport2.CvsUtil"); @NonNls private static final String REPOSITORY = "Repository"; @NonNls private static final String TAG = "Tag"; @NonNls public static final String CVS = "CVS"; @NonNls public static final String ENTRIES = "Entries"; @NonNls private static final String CONFLICTS = "Conflicts"; @NonNls public static final String STICKY_DATE_PREFIX = "D"; @NonNls private static final String TEMPLATE = "Template"; @NonNls public static final String STICKY_BRANCH_TAG_PREFIX = "T"; @NonNls public static final String STICKY_NON_BRANCH_TAG_PREFIX = "N"; @NonNls public static final String HEAD = "HEAD"; @NonNls public static final String BASE = "Base"; public static void skip(InputStream inputStream, int length) throws IOException { int skipped = 0; while (skipped < length) { skipped += inputStream.skip(length - skipped); } } public static String getModuleName(VirtualFile file) { if (file.isDirectory()) { return CvsEntriesManager.getInstance().getRepositoryFor(file); } else { return CvsEntriesManager.getInstance().getRepositoryFor(file.getParent()) + "/" + file.getName(); } } public static boolean fileIsUnderCvs(VirtualFile vFile) { return fileIsUnderCvs(CvsVfsUtil.getFileFor(vFile)); } public static boolean fileIsUnderCvs(File ioFile) { try { if (ioFile.isDirectory()) { return directoryIsUnderCVS(ioFile); } return fileIsUnderCvs(getEntryFor(ioFile)); } catch (Exception e1) { return false; } } private static boolean directoryIsUnderCVS(File directory) { if (!getAdminDir(directory).isDirectory()) return false; if (!getFileInTheAdminDir(directory, ENTRIES).isFile()) return false; if (!getFileInTheAdminDir(directory, CVS_ROOT_FILE).isFile()) return false; if (!getFileInTheAdminDir(directory, REPOSITORY).isFile()) return false; return true; } public static Entry getEntryFor(VirtualFile file) { return CvsEntriesManager.getInstance().getEntryFor(CvsVfsUtil.getParentFor(file), file.getName()); } public static Entry getEntryFor(File ioFile) { File parentFile = ioFile.getParentFile(); if (parentFile == null) return null; return CvsEntriesManager.getInstance().getEntryFor(CvsVfsUtil.findFileByIoFile(parentFile), ioFile.getName()); } private static boolean fileIsUnderCvs(Entry entry) { return entry != null; } public static boolean filesAreUnderCvs(File[] selectedFiles) { return allSatisfy(selectedFiles, fileIsUnderCvsCondition()); } public static boolean filesArentUnderCvs(File[] selectedFiles) { return !anySatisfy(selectedFiles, fileIsUnderCvsCondition()); } private static FileCondition fileIsUnderCvsCondition() { return new FileCondition() { public boolean verify(File file) { return fileIsUnderCvs(file); } }; } private static boolean allSatisfy(File[] files, FileCondition condition) { for (File file : files) { if (!condition.verify(file)) return false; } return true; } private static boolean anySatisfy(File[] files, FileCondition condition) { return !allSatisfy(files, new ReverseFileCondition(condition)); } public static boolean filesHaveParentUnderCvs(File[] files) { return allSatisfy(files, new FileCondition() { public boolean verify(File file) { return fileHasParentUnderCvs(file); } }); } private static boolean fileHasParentUnderCvs(File file) { return fileIsUnderCvs(file.getParentFile()); } public static boolean fileIsLocallyAdded(File file) { Entry entry = getEntryFor(file); return entry == null ? false : entry.isAddedFile(); } public static boolean fileIsLocallyDeleted(File file) { Entry entry = getEntryFor(file); return entry == null ? false : entry.isRemoved(); } public static boolean fileIsLocallyAdded(VirtualFile file) { return fileIsLocallyAdded(CvsVfsUtil.getFileFor(file)); } public static Entries getEntriesIn(File dir) { return getEntriesHandlerIn(dir).getEntries(); } private static EntriesHandler getEntriesHandlerIn(final File dir) { EntriesHandler entriesHandler = new EntriesHandler(dir); try { entriesHandler.read(CvsApplicationLevelConfiguration.getCharset()); return entriesHandler; } catch (Exception ex) { final String entries = loadFrom(dir, ENTRIES, true); if (entries != null) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { final String entriesFileRelativePath = CVS + File.separatorChar + ENTRIES; Messages.showErrorDialog(CvsBundle.message("message.error.invalid.entries", entriesFileRelativePath, dir.getAbsolutePath(), entries), CvsBundle.message("message.error.invalid.entries.title")); } }); } return entriesHandler; } } public static void removeEntryFor(File file) { File entriesFile = file.getParentFile(); EntriesHandler handler = new EntriesHandler(entriesFile); String charset = CvsApplicationLevelConfiguration.getCharset(); try { handler.read(charset); } catch (IOException e) { return; } Entries entries = handler.getEntries(); entries.removeEntry(file.getName()); try { handler.write(getLineSeparator(), charset); } catch (IOException e) { LOG.error(e); } CvsEntriesManager.getInstance().removeEntryForFile(file.getParentFile(), file.getName()); } private static String getLineSeparator() { return CodeStyleSettingsManager.getInstance().getCurrentSettings().getLineSeparator(); } public static boolean fileIsLocallyRemoved(File file) { Entry entry = getEntryFor(file); if (entry == null) return false; return entry.isRemoved(); } public static boolean fileIsLocallyRemoved(VirtualFile file) { return fileIsLocallyRemoved(CvsVfsUtil.getFileFor(file)); } public static String formatDate(Date date) { return DATE_FORMATTER.format(date); } public static void saveEntryForFile(File file, Entry entry) throws IOException { EntriesHandler entriesHandler = new EntriesHandler(file.getParentFile()); entriesHandler.read(CvsApplicationLevelConfiguration.getCharset()); entriesHandler.getEntries().addEntry(entry); entriesHandler.write(getLineSeparator(), CvsApplicationLevelConfiguration.getCharset()); } public static String loadRepositoryFrom(File file) { return loadFrom(file, REPOSITORY, true); } public static String loadRootFrom(File file) { return loadFrom(file, CVS_ROOT_FILE, true); } @Nullable private static String loadFrom(File directory, String fileName, boolean trimContent) { if (directory == null) return null; File file = getFileInTheAdminDir(directory, fileName); if (!file.isFile()) return null; try { String result = new String(FileUtil.loadFileText(file)); if (trimContent) { return result.trim(); } else { return result; } } catch (IOException e) { return null; } } private static File getFileInTheAdminDir(File file, String fileName) { return new File(getAdminDir(file), fileName); } private static File getAdminDir(File file) { return new File(file, CVS); } public static String getStickyDateForDirectory(VirtualFile parentFile) { File file = CvsVfsUtil.getFileFor(parentFile); String tag = loadStickyTagFrom(file); if (tag == null) return null; if (tag.startsWith(STICKY_DATE_PREFIX)) { return tag.substring(STICKY_DATE_PREFIX.length()); } if (tag.startsWith(STICKY_BRANCH_TAG_PREFIX)) { return tag.substring(STICKY_BRANCH_TAG_PREFIX.length()); } return tag; } public static String loadStickyTagFrom(File file) { return loadFrom(file, TAG, true); } public static String getStickyTagForDirectory(VirtualFile parentFile) { String tag = loadFrom(CvsVfsUtil.getFileFor(parentFile), TAG, true); if (tag == null) return null; if (tag.length() == 0) return null; if (tag.startsWith(STICKY_DATE_PREFIX)) return null; if (tag.startsWith(STICKY_BRANCH_TAG_PREFIX)) return tag.substring(1); if (tag.startsWith(STICKY_NON_BRANCH_TAG_PREFIX)) return tag.substring(1); return null; } public static void ignoreFile(final VirtualFile file) throws IOException { VirtualFile directory = CvsVfsUtil.getParentFor(file); File cvsignoreFile = cvsignoreFileFor(CvsVfsUtil.getPathFor(directory)); CvsFileUtil.appendLineToFile(file.getName(), cvsignoreFile); CvsEntriesManager.getInstance().clearCachedFiltersFor(directory); } public static File cvsignoreFileFor(String path) { return new File(new File(path), CVS_IGNORE_FILE); } public static File cvsignoreFileFor(File file) { return new File(file, CVS_IGNORE_FILE); } public static void addConflict(File file) { File conflictsFile = getConflictsFile(file); try { Conflicts conflicts = Conflicts.readFrom(conflictsFile); conflicts.addConflictForFile(file.getName()); conflicts.saveTo(conflictsFile); } catch (IOException e) { LOG.error(e); } } private static File getConflictsFile(File file) { return getFileInTheAdminDir(file.getParentFile(), CONFLICTS); } public static void removeConflict(File file) { File conflictsFile = getConflictsFile(file); if (!conflictsFile.exists()) return; try { Conflicts conflicts = Conflicts.readFrom(conflictsFile); conflicts.removeConflictForFile(file.getName()); conflicts.saveTo(conflictsFile); } catch (IOException e) { LOG.error(e); } } public static boolean isLocallyRemoved(File file) { Entry entry = getEntryFor(file); if (entry == null) return false; return entry.isRemoved(); } public static String getRevisionFor(File file) { final Entry entry = getEntryFor(file); if (entry == null) return null; return entry.getRevision(); } public static boolean filesExistInCvs(File[] files) { return allSatisfy(files, new FileCondition() { public boolean verify(File file) { return fileIsUnderCvs(file) && !fileIsLocallyAdded(file); } }); } public static boolean filesAreNotDeleted(File[] files) { return allSatisfy(files, new FileCondition() { public boolean verify(File file) { return fileIsUnderCvs(file) && !fileIsLocallyAdded(file) && !fileIsLocallyDeleted(file); } }); } public static void saveRevisionForMergedFile(@NotNull VirtualFile parent, @NotNull final Entry previousEntry, List<String> revisions) { File conflictsFile = getConflictsFile(new File(CvsVfsUtil.getFileFor(parent), previousEntry.getFileName())); try { Conflicts conflicts = Conflicts.readFrom(conflictsFile); Date lastModified = previousEntry.getLastModified(); conflicts.setRevisionAndDateForFile(previousEntry.getFileName(), previousEntry.getRevision(), revisions, lastModified == null ? new Date().getTime() : lastModified.getTime()); conflicts.saveTo(conflictsFile); } catch (IOException e) { LOG.error(e); } } public static byte[] getStoredContentForFile(VirtualFile file, final String originalRevision) { File ioFile = CvsVfsUtil.getFileFor(file); try { File storedRevisionFile = new File(ioFile.getParentFile(), ".#" + ioFile.getName() + "." + originalRevision); if (!storedRevisionFile.isFile()) return null; return FileUtil.loadFileBytes(storedRevisionFile); } catch (IOException e) { LOG.error(e); return null; } } public static byte[] getStoredContentForFile(VirtualFile file) { File ioFile = CvsVfsUtil.getFileFor(file); try { File storedRevisionFile = new File(ioFile.getParentFile(), ".#" + ioFile.getName() + "." + getAllRevisionsForFile(file).get(0)); if (!storedRevisionFile.isFile()) return null; return FileUtil.loadFileBytes(storedRevisionFile); } catch (IOException e) { LOG.error(e); return null; } } public static long getUpToDateDateForFile(VirtualFile file) { try { return Conflicts.readFrom(getConflictsFile(CvsVfsUtil.getFileFor(file))).getPreviousEntryTime(file.getName()); } catch (IOException e) { LOG.error(e); return -1; } } public static void resolveConflict(VirtualFile vFile) { File file = CvsVfsUtil.getFileFor(vFile); removeConflict(file); EntriesHandler handler = getEntriesHandlerIn(file.getParentFile()); Entries entries = handler.getEntries(); Entry entry = entries.getEntry(file.getName()); if (entry == null) return; long timeStamp = vFile.getTimeStamp(); final Date date = CvsStatusProvider.createDateDiffersTo(timeStamp); entry.parseConflictString(Entry.getLastModifiedDateFormatter().format(date)); entries.addEntry(entry); try { handler.write(getLineSeparator(), CvsApplicationLevelConfiguration.getCharset()); } catch (IOException e) { LOG.error(e); } } @Nullable public static String getTemplateFor(FilePath file) { return loadFrom(file.isDirectory() ? file.getIOFile().getParentFile() : file.getIOFile(), TEMPLATE, false); } public static String getRepositoryFor(File file) { String result = loadRepositoryFrom(file); if (result == null) return null; String root = loadRootFrom(file); if (root != null) { final CvsRootParser cvsRootParser = CvsRootParser.valueOf(root, false); String serverRoot = cvsRootParser.REPOSITORY; if (serverRoot != null) { result = getRelativeRepositoryPath(result, serverRoot); } } return result; } public static String getRelativeRepositoryPath(String repository, String serverRoot) { repository = repository.replace(File.separatorChar, '/'); serverRoot = serverRoot.replace(File.separatorChar, '/'); if (repository.startsWith(serverRoot)) { repository = repository.substring(serverRoot.length()); if (repository.startsWith("/")) { repository = repository.substring(1); } } if (repository.startsWith("./")) { repository = repository.substring(2); } return repository; } public static File getCvsLightweightFileForFile(File file) { return new File(getRepositoryFor(file.getParentFile()), file.getName()); } public static List<String> getAllRevisionsForFile(VirtualFile file) { try { return Conflicts.readFrom(getConflictsFile(CvsVfsUtil.getFileFor(file))).getRevisionsFor(file.getName()); } catch (IOException e) { LOG.error(e); return null; } } public static void restoreFile(final VirtualFile file) { CvsEntriesManager cvsEntriesManager = CvsEntriesManager.getInstance(); VirtualFile directory = CvsVfsUtil.getParentFor(file); LOG.assertTrue(directory != null); CvsInfo cvsInfo = cvsEntriesManager.getCvsInfoFor(directory); Entry entry = cvsInfo.getEntryNamed(file.getName()); LOG.assertTrue(entry != null); String revision = entry.getRevision(); LOG.assertTrue(StringUtil.startsWithChar(revision, '-')); String originalRevision = revision.substring(1); String date = Entry.formatLastModifiedDate(CvsStatusProvider.createDateDiffersTo(file.getTimeStamp())); String kwdSubstitution = entry.getOptions() == null ? "" : entry.getOptions(); String stickyDataString = entry.getStickyData(); Entry newEntry = Entry.createEntryForLine("/" + file.getName() + "/" + originalRevision + "/" + date + "/" + kwdSubstitution + "/" + stickyDataString); try { saveEntryForFile(CvsVfsUtil.getFileFor(file), newEntry); cvsEntriesManager.clearCachedEntriesFor(directory); } catch (final IOException e) { SwingUtilities.invokeLater(new Runnable() { public void run() { Messages.showErrorDialog(CvsBundle.message("message.error.restore.entry", file.getPresentableUrl(), e.getLocalizedMessage()), CvsBundle.message("message.error.restore.entry.title")); } }); } } public static boolean fileExistsInCvs(VirtualFile file) { if (file.isDirectory()) { final VirtualFile child = file.findChild(CVS); if (child != null && child.isDirectory()) return true; } Entry entry = CvsEntriesManager.getInstance().getEntryFor(file); if (entry == null) return false; return !entry.isAddedFile(); } public static boolean fileExistsInCvs(FilePath file) { if (file.isDirectory() && new File(file.getIOFile(), CVS).isDirectory()) return true; Entry entry = CvsEntriesManager.getInstance().getEntryFor(file.getVirtualFileParent(), file.getName()); if (entry == null) return false; return !entry.isAddedFile(); } public static boolean storedVersionExists(final String original, final VirtualFile file) { File ioFile = CvsVfsUtil.getFileFor(file); File storedRevisionFile = new File(ioFile.getParentFile(), ".#" + ioFile.getName() + "." + original); return storedRevisionFile.isFile(); } private static interface FileCondition { boolean verify(File file); } private static class ReverseFileCondition implements FileCondition { private final FileCondition myCondition; public ReverseFileCondition(FileCondition condition) { myCondition = condition; } public boolean verify(File file) { return !myCondition.verify(file); } } private static class Conflict { private String myName; private List<String> myRevisions; private long myPreviousTime; private static final String DELIM = ";"; private Conflict(String name, String originalRevision, List<String> revisions, long time) { myName = name; myRevisions = new ArrayList<String>(); myRevisions.add(originalRevision); myRevisions.addAll(revisions); myPreviousTime = time; } private Conflict(String name, List<String> revisions, long time) { myName = name; myRevisions = new ArrayList<String>(); myRevisions.addAll(revisions); myPreviousTime = time; } public String toString() { StringBuffer result = new StringBuffer(); result.append(myName); result.append(DELIM); result.append(String.valueOf(myPreviousTime)); result.append(DELIM); for (int i = 0; i < myRevisions.size(); i++) { if (i > 0) { result.append(DELIM); } result.append(myRevisions.get(i)); } return result.toString(); } public static Conflict readFrom(String line) { try { String[] strings = line.split(DELIM); if (strings.length == 0) return null; String name = strings[0]; long time = strings.length > 1 ? Long.parseLong(strings[1]) : -1; int revisionsSize = strings.length > 2 ? strings.length - 2 : 0; String[] revisions = new String[revisionsSize]; if (revisions.length > 0) { System.arraycopy(strings, 2, revisions, 0, revisions.length); } return new Conflict(name, Arrays.asList(revisions), time); } catch (NumberFormatException e) { return null; } } public String getFileName() { return myName; } public long getPreviousEntryTime() { return myPreviousTime; } public List<String> getRevisions() { return new ArrayList<String>(myRevisions); } public void setOriginalRevision(final String originalRevision) { if (!myRevisions.isEmpty()) myRevisions.remove(0); myRevisions.add(0, originalRevision); } public void setRevisions(final List<String> revisions) { if (myRevisions.isEmpty()) { } else { final String originalRevision = myRevisions.remove(0); myRevisions.clear(); myRevisions.add(originalRevision); myRevisions.addAll(revisions); } } } private static class Conflicts { private final Map<String, Conflict> myNameToConflict = new com.intellij.util.containers.HashMap<String, Conflict>(); @NotNull public static Conflicts readFrom(File file) throws IOException { Conflicts result = new Conflicts(); if (!file.exists()) return result; List<String> lines = CvsFileUtil.readLinesFrom(file); for (final String line : lines) { Conflict conflict = Conflict.readFrom(line); if (conflict != null) { result.addConflict(conflict); } } return result; } public void saveTo(File file) throws IOException { CvsFileUtil.storeLines(getConflictLines(), file); } private List<String> getConflictLines() { ArrayList<String> result = new ArrayList<String>(); for (final Conflict conflict : myNameToConflict.values()) { result.add((conflict).toString()); } return result; } private void addConflict(Conflict conflict) { myNameToConflict.put(conflict.getFileName(), conflict); } public void setRevisionAndDateForFile(String fileName, String originalRevision, List<String> revisions, long time) { if (!myNameToConflict.containsKey(fileName)) { myNameToConflict.put(fileName, new Conflict(fileName, originalRevision, revisions, time)); } myNameToConflict.get(fileName).setOriginalRevision(originalRevision); myNameToConflict.get(fileName).setRevisions(revisions); } public void addConflictForFile(String name) { if (!myNameToConflict.containsKey(name)) { myNameToConflict.put(name, new Conflict(name, "", new ArrayList<String>(), -1)); } } public void removeConflictForFile(String name) { myNameToConflict.remove(name); } public List<String> getRevisionsFor(String name) { if (!myNameToConflict.containsKey(name)) return new ArrayList<String>(); return (myNameToConflict.get(name)).getRevisions(); } public long getPreviousEntryTime(String fileName) { if (!myNameToConflict.containsKey(fileName)) return -1; return (myNameToConflict.get(fileName)).getPreviousEntryTime(); } public String getOriginalRevisionFor(final String name) { if (!myNameToConflict.containsKey(name)) return ""; final List<String> revisions = (myNameToConflict.get(name)).getRevisions(); return revisions.isEmpty() ? "" : revisions.get(0); } } public static CvsConnectionSettings getCvsConnectionSettings(FilePath path){ VirtualFile virtualFile = path.getVirtualFile(); if (virtualFile == null || !path.isDirectory()){ return CvsEntriesManager.getInstance().getCvsConnectionSettingsFor(path.getVirtualFileParent()); } else { return CvsEntriesManager.getInstance().getCvsConnectionSettingsFor(virtualFile); } } }
package arez.spy; import arez.Arez; import arez.Component; import arez.ComputableValue; import arez.ObservableValue; import arez.Observer; import java.util.Collection; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Interface for interacting with spy system. */ public interface Spy { /** * Add a spy handler to the list of handlers. * The handler should not already be in the list. * * @param handler the spy handler. */ void addSpyEventHandler( @Nonnull SpyEventHandler handler ); /** * Remove spy handler from list of existing handlers. * The handler should already be in the list. * * @param handler the spy handler. */ void removeSpyEventHandler( @Nonnull SpyEventHandler handler ); /** * Return true if spy events will be propagated. * This means spies are enabled and there is at least one spy event handler present. * * @return true if spy events will be propagated, false otherwise. */ boolean willPropagateSpyEvents(); /** * Report an event in the Arez system. * * @param event the event that occurred. */ void reportSpyEvent( @Nonnull Object event ); /** * Return true if there is a transaction active. * * @return true if there is a transaction active. */ boolean isTransactionActive(); /** * Return the current transaction. * This method should not be invoked unless {@link #isTransactionActive()} returns true. * * @return the current transaction. */ @Nonnull TransactionInfo getTransaction(); /** * Find the component identified by the specified type and id. * * @param type the component type. * @param id the component id. Should be null if the component is a singleton. * @return the component descriptor matching the specified type and id. */ @Nullable ComponentInfo findComponent( @Nonnull String type, @Nonnull Object id ); /** * Find all the components identified by the specified type. * This collection returned is unmodifiable. * * @param type the component type. * @return the collection of component descriptors of specified type. */ @Nonnull Collection<ComponentInfo> findAllComponentsByType( @Nonnull String type ); /** * Find all the component types in the system. * This is essentially all the types that have at least 1 instance. * This collection returned is unmodifiable. * * @return the collection of component types. */ @Nonnull Collection<String> findAllComponentTypes(); /** * Find all the observables not contained by a native component. * This method should not be invoked unless {@link Arez#areRegistriesEnabled()} returns true. * This collection returned is unmodifiable. * * @return the collection of observables not contained by a native component. */ @Nonnull Collection<ObservableValueInfo> findAllTopLevelObservableValues(); /** * Find all the observers not contained by a native component. * This method should not be invoked unless {@link Arez#areRegistriesEnabled()} returns true. * This collection returned is unmodifiable. * * @return the collection of observers not contained by a native component. */ @Nonnull Collection<ObserverInfo> findAllTopLevelObservers(); /** * Find all the computable values not contained by a native component. * This method should not be invoked unless {@link Arez#areRegistriesEnabled()} returns true. * This collection returned is unmodifiable. * * @return the collection of computable values not contained by a native component. */ @Nonnull Collection<ComputableValueInfo> findAllTopLevelComputableValues(); /** * Convert the specified component into an ComponentInfo. * * @param component the Component. * @return the ComponentInfo. */ @Nonnull ComponentInfo asComponentInfo( @Nonnull Component component ); /** * Convert the specified observer into an ObserverInfo. * * @param observer the Observer. * @return the ObserverInfo. */ @Nonnull ObserverInfo asObserverInfo( @Nonnull Observer observer ); /** * Convert the specified observableValue into an ObservableValueInfo. * * @param <T> The type of the value that is observableValue. * @param observableValue the ObservableValue. * @return the ObservableValueInfo wrapping observableValue. */ @Nonnull <T> ObservableValueInfo asObservableValueInfo( @Nonnull ObservableValue<T> observableValue ); /** * Convert the specified ComputableValue into an ComputableValueInfo. * * @param <T> The type of the value that is computable. * @param computableValue the ComputableValue. * @return the ComputableValueInfo wrapping the ComputableValue. */ @Nonnull <T> ComputableValueInfo asComputableValueInfo( @Nonnull ComputableValue<T> computableValue ); }
package xidecsc; import com.badlogic.gdx.math.Vector2; import entities.PlayerEntity; import player.ActualPlayerClass; /** * Contains and modifies the state of game logic objects, such as if an object * even exists at all or its position. A {@link XIDECSCComponent}. * * @author sorcerer * */ public class StateContainer { public void movePlayer(ActualPlayerClass player, PlayerEntity entity, double angle, String direction, Vector2 displacement) { player.radians_Direction = angle; entity.direction = direction; /* * Check for collision elsewhere, by the way, not here in this method. */ player.x += displacement.x * player.speed; player.y += displacement.y * player.speed; entity.position.x += displacement.x * player.speed; entity.position.y += displacement.y * player.speed; entity.playerRectangle.x = entity.position.x; entity.playerRectangle.y = entity.position.y; entity.isAnimating = true; } }
package org.pm4j.core.pm.impl; import java.io.Serializable; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.validation.Validation; import javax.validation.ValidationException; import javax.validation.ValidatorFactory; import javax.validation.constraints.NotNull; import javax.validation.metadata.BeanDescriptor; import javax.validation.metadata.ConstraintDescriptor; import javax.validation.metadata.PropertyDescriptor; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pm4j.common.util.CompareUtil; import org.pm4j.common.util.collection.MapUtil; import org.pm4j.core.exception.PmConverterException; import org.pm4j.core.exception.PmResourceData; import org.pm4j.core.exception.PmRuntimeException; import org.pm4j.core.exception.PmValidationException; import org.pm4j.core.pm.PmAspect; import org.pm4j.core.pm.PmAttr; import org.pm4j.core.pm.PmBean; import org.pm4j.core.pm.PmConstants; import org.pm4j.core.pm.PmElement; import org.pm4j.core.pm.PmEvent; import org.pm4j.core.pm.PmMessage; import org.pm4j.core.pm.PmMessage.Severity; import org.pm4j.core.pm.PmObject; import org.pm4j.core.pm.PmOptionSet; import org.pm4j.core.pm.PmVisitor; import org.pm4j.core.pm.annotation.PmAttrCfg; import org.pm4j.core.pm.annotation.PmAttrCfg.AttrAccessKind; import org.pm4j.core.pm.annotation.PmAttrStringCfg; import org.pm4j.core.pm.annotation.PmCacheCfg; import org.pm4j.core.pm.annotation.PmCacheCfg.CacheMode; import org.pm4j.core.pm.annotation.PmOptionCfg; import org.pm4j.core.pm.annotation.PmOptionCfg.NullOption; import org.pm4j.core.pm.api.PmCacheApi; import org.pm4j.core.pm.api.PmEventApi; import org.pm4j.core.pm.api.PmExpressionApi; import org.pm4j.core.pm.api.PmMessageUtil; import org.pm4j.core.pm.impl.cache.PmCacheStrategy; import org.pm4j.core.pm.impl.cache.PmCacheStrategyBase; import org.pm4j.core.pm.impl.cache.PmCacheStrategyNoCache; import org.pm4j.core.pm.impl.cache.PmCacheStrategyRequest; import org.pm4j.core.pm.impl.commands.PmValueChangeCommand; import org.pm4j.core.pm.impl.converter.PmConverterOptionBased; import org.pm4j.core.pm.impl.options.GenericOptionSetDef; import org.pm4j.core.pm.impl.options.OptionSetDefNoOption; import org.pm4j.core.pm.impl.options.PmOptionSetDef; import org.pm4j.core.pm.impl.pathresolver.PathResolver; import org.pm4j.core.pm.impl.pathresolver.PmExpressionPathResolver; import org.pm4j.core.util.reflection.BeanAttrAccessor; import org.pm4j.core.util.reflection.BeanAttrAccessorImpl; /** * <p> Basic implementation for PM attributes. </p> * * <p> Note: If you are looking for a generic PmAttr implementation * for use in client code, use PmAttrImpl, not this base class. </p> * * TODOC: * * @param <T_PM_VALUE> * The external PM api type.<br> * Examples:<br> * For a string field: the type {@link String};<br> * For a bean reference: the PM class for the referenced bean. * @param <T_BEAN_VALUE> * The bean field type. <br> * Examples:<br> * For a string field: the type {@link String};<br> * For a reference: The referenced class. * * @author olaf boede */ public abstract class PmAttrBase<T_PM_VALUE, T_BEAN_VALUE> extends PmObjectBase implements PmAttr<T_PM_VALUE> { private static final Log LOG = LogFactory.getLog(PmAttrBase.class); /** * Indicates if the value was explicitly set. This information is especially * important for the default value logic. Default values may have only effect * on values that are not explicitly set. */ private boolean valueWasSet = false; /** * Contains optional attribute data that in most cases doesn't exist for usual * bean attributes. */ private PmAttrDataContainer<T_PM_VALUE, T_BEAN_VALUE> dataContainer; /** * Keeps a reference to the entered value in case of buffered data entry. */ private Object bufferedValue = UNKNOWN_VALUE_INDICATOR; /** Shortcut to the next parent element. */ private PmElement pmParentElement; public PmAttrBase(PmObject pmParent) { super(pmParent); pmParentElement = (pmParent instanceof PmElement) ? (PmElement)pmParent : PmUtil.getPmParentOfType(pmParent, PmElement.class); } /** * @return The next parent of type {@link PmElement}. */ protected PmElement getPmParentElement() { return pmParentElement; } @Override public final PmOptionSet getOptionSet() { MetaData md = getOwnMetaData(); Object ov = md.cacheStrategyForOptions.getCachedValue(this); if (ov != PmCacheStrategy.NO_CACHE_VALUE) { // just return the cache hit (if there was one) return (PmOptionSet) ov; } else { try { PmOptionSet os = getOptionSetImpl(); md.cacheStrategyForOptions.setAndReturnCachedValue(this, os); return os; } catch (RuntimeException e) { PmRuntimeException forwardedEx = PmRuntimeException.asPmRuntimeException(this, e); // TODO olaf: Logging is required here for JSF. Make it configurable for other // UI frameworks with better exception handling. LOG.error("getOptionSet failed", forwardedEx); throw forwardedEx; } } } /** * @return An option set. In case of no options an empty option set. */ protected PmOptionSet getOptionSetImpl() { PmOptionSet os = getOwnMetaData().optionSetDef.makeOptions(this); return os; } /** * A combination of {@link PmOptionCfg} and the implementation of this method * may be used to define the options for the attribute value. * <p> * The id, title and value attributes of the annotation will be applied to * the items of the provided object set to create the option set. * * @return The object to generate the options from.<br> * May return <code>null</code> in case of no option values. */ // XXX olaf: is currently public because of the package location of OptionSetDefBase. public Iterable<?> getOptionValues() { throw new PmRuntimeException(this, "Please don't forget to implement getOptionValues() if you don't specifiy the options in the @PmOptions annotation."); } // XXX olaf: is currently public because of the package location of OptionSetDefBase. /** * Provides the attribute type specific default definition, if an option set * should contain a <code>null</code> option definition or not. * <p> * Usualy non-list attributes provide the default * {@link PmOptionCfg.NullOption#FOR_OPTIONAL_ATTR} and list attributes * {@link PmOptionCfg.NullOption#NO}. * * @return The attribute type specific null-option generation default value. */ public NullOption getNullOptionDefault() { return NullOption.FOR_OPTIONAL_ATTR; } @Override public boolean isRequired() { return getOwnMetaData().required && isPmEnabled(); } @Override public boolean isPmReadonly() { return super.isPmReadonly() || getPmParentElement().isPmReadonly(); } @Override protected boolean isPmEnabledImpl() { return super.isPmEnabledImpl() && !isPmReadonly(); } @Override protected boolean isPmVisibleImpl() { boolean visible = super.isPmVisibleImpl(); if (visible && getOwnMetaData().hideWhenEmpty) { visible = !isEmptyValue(getValue()); } return visible; } @Override protected void getPmStyleClassesImpl(Set<String> styleClassSet) { super.getPmStyleClassesImpl(styleClassSet); if (isRequired()) { styleClassSet.add(STYLE_CLASS_REQUIRED); } } @Override public void accept(PmVisitor visitor) { visitor.visit(this); } @Override public void clearPmInvalidValues() { boolean wasValid = isPmValid(); if (dataContainer != null) { if (dataContainer.invalidValue != null) { dataContainer.invalidValue = null; } } if (!wasValid) { for (PmMessage m : PmMessageUtil.getPmErrors(this)) { this.getPmConversationImpl().clearPmMessage(m); } PmEventApi.firePmEvent(this, getOwnMetaData().validationChangeEventMask); } } /** * The default implementation compares the results of {@link #getValueLocalized()} * according to the collation sequence of the current {@link Locale}. */ @Override public int compareTo(PmObject otherPm) { return PmUtil.getAbsoluteName(this).equals(PmUtil.getAbsoluteName(otherPm)) ? CompareUtil.compare(getValueLocalized(), ((PmAttr<?>)otherPm).getValueLocalized(), getPmConversation().getPmLocale()) : super.compareTo(otherPm); } /** * Checks if two instances represent the same value. * <p> * Sub classes may override this method to provide their specific equals-conditions. * <p> * This correct implementation of this method is important for the changed state handling. * * @see #isPmValueChanged() * @see #onPmValueChange(PmEvent) * @see PmEvent#VALUE_CHANGE * * @param v1 A value. May be <code>null</code>. * @param v2 Another value. May be <code>null</code>. * @return <code>true</code> if both parameters represent the same value. */ protected boolean equalValues(T_PM_VALUE v1, T_PM_VALUE v2) { return ObjectUtils.equals(v1, v2); } // Bei erfolgreicher Typkonvertierung sollte auch diese Methode @SuppressWarnings("unchecked") @Override public T_PM_VALUE getValue() { MetaData md = getOwnMetaData(); Object ov = md.cacheStrategyForValue.getCachedValue(this); if (ov != PmCacheStrategy.NO_CACHE_VALUE) { // just return the cache hit (if there was one) return (T_PM_VALUE) ov; } else { try { T_PM_VALUE v = null; if (isInvalidValue()) { if (!dataContainer.invalidValue.isPmValueSet()) { throw new PmRuntimeException(this, "Unable to get a value that was not convertible to the presentation model type.\n" + "Hint: Use getValueAsString when the value was set by getValueAsString."); } v = dataContainer.invalidValue.getPmValue(); } else { v = getValueImpl(); } return (T_PM_VALUE) md.cacheStrategyForValue.setAndReturnCachedValue(this, v); } catch (RuntimeException e) { PmRuntimeException forwardedEx = PmRuntimeException.asPmRuntimeException(this, e); // TODO olaf: Logging is required here for JSF. Make it configurable for other // UI frameworks with better exception handling. LOG.error("getValue failed", forwardedEx); throw forwardedEx; } } } @Override public final void setValue(T_PM_VALUE value) { if (!isPmReadonly()) { SetValueContainer<T_PM_VALUE> vc = SetValueContainer.makeWithPmValue(this, value); PmValueChangeCommand cmd = new PmValueChangeCommand(null, this, vc.getPmValue()); if (setValueImpl(vc)) { getPmConversation().getPmCommandHistory().commandDone(cmd); } } else { // XXX olaf: is only a workaround for the standard jsf-form behavior... // Approach: add a configuration parameter if (LOG.isInfoEnabled()) { LOG.info("Ignored setValue() call for read-only attribute: " + PmUtil.getPmLogString(this)); } } } @Override public final String getValueAsString() { try { T_PM_VALUE value; if (isInvalidValue()) { if (dataContainer.invalidValue.isStringValueSet()) { return dataContainer.invalidValue.getStringValue(); } else { value = dataContainer.invalidValue.getPmValue(); } } else { value = getValue(); } return value != null ? getConverter().valueToString(this, value) : null; } catch (PmRuntimeException pmrex) { throw pmrex; } catch (RuntimeException e) { PmRuntimeException forwardedEx = PmRuntimeException.asPmRuntimeException(this, e); LOG.error("getValueAsString failed", forwardedEx); throw forwardedEx; } } /** * The default implementation returns the result of {@link #getValueAsString()}. */ @Override public String getValueLocalized() { return getValueAsString(); } /** * The default implementation returns 0. */ @Override public int getMinLen() { return 0; } @Override public int getMaxLen() { return PmAttrStringCfg.DEFAULT_MAXLEN; } @Override public final void setValueAsString(String text) { SetValueContainer<T_PM_VALUE> vc = new SetValueContainer<T_PM_VALUE>(this, text); PmValueChangeCommand cmd = new PmValueChangeCommand(null, this, vc.getPmValue()); if (zz_validateAndSetValueAsString(vc)) { getPmConversation().getPmCommandHistory().commandDone(cmd); } } @Override public void resetPmValues() { boolean isWritable = !isPmReadonly(); if (isWritable) { PmCacheApi.clearCachedPmValues(this); this.valueWasSet = false; } clearPmInvalidValues(); if (isWritable) { setValue(getDefaultValue()); } } @Override protected void clearCachedPmValues(Set<PmCacheApi.CacheKind> cacheSet) { super.clearCachedPmValues(cacheSet); MetaData sd = getOwnMetaData(); if (cacheSet.contains(PmCacheApi.CacheKind.VALUE)) sd.cacheStrategyForValue.clear(this); if (cacheSet.contains(PmCacheApi.CacheKind.OPTIONS)) sd.cacheStrategyForOptions.clear(this); } /** * Gets attribute value directly from the bound data source. Does not use the * cache and does not consider any temporarily set invalid values. * * @return The current attribute value. */ public final T_PM_VALUE getUncachedValidValue() { return getValueImpl(); } protected T_PM_VALUE getValueImpl() { try { T_BEAN_VALUE beanAttrValue = getBackingValue(); if (beanAttrValue != null) { return convertBackingValueToPmValue(beanAttrValue); } else { // Default values may have only effect if the value was not set // by the user: if (valueWasSet) { return null; } else { T_PM_VALUE defaultValue = getDefaultValue(); if (defaultValue != null) { beanAttrValue = convertPmValueToBackingValue(defaultValue); // XXX olaf: The backing value gets changed within the 'get' functionality. // Check if that can be postponed... setBackingValue(beanAttrValue); } return defaultValue; } } } catch (Exception e) { throw PmRuntimeException.asPmRuntimeException(this, e); } } /** * Performs a smart set operation. * Validates the value before applying it. * * @param value The new value. * @return <code>true</code> when the attribute value was really changed. */ protected boolean setValueImpl(SetValueContainer<T_PM_VALUE> value) { PmEventApi.ensureThreadEventSource(this); try { assert value.isPmValueSet(); // New game. Forget all the old invalid stuff. clearPmInvalidValues(); T_PM_VALUE newPmValue = value.getPmValue(); T_PM_VALUE currentValue = getUncachedValidValue(); boolean pmValueChanged = ! equalValues(currentValue, newPmValue); // Ensure that primitive types will not be set to null. if ((newPmValue == null) && getOwnMetaData().primitiveType) { zz_setAndPropagateInvalidValue(value, PmConstants.MSGKEY_VALIDATION_MISSING_REQUIRED_VALUE); return false; } if (pmValueChanged && isPmReadonly()) { PmMessageUtil.makeMsg(this, Severity.ERROR, PmConstants.MSGKEY_VALIDATION_READONLY); return false; } if (isValidatingOnSetPmValue()) { // Validate even if nothing was changed. The currentValue may be invalid too. // Example: New object with empty attributes values. try { validate(newPmValue); } catch (PmValidationException e) { PmResourceData resData = e.getResourceData(); zz_setAndPropagateInvalidValue(value, resData.msgKey, resData.msgArgs); return false; } } // Check both values for null-value because they might be different but // may both represent a null-value. if (pmValueChanged && (!(isEmptyValue(newPmValue) && isEmptyValue(currentValue))) ) { try { // TODO olaf: a quick hack to hide password data. Should be done more general for other field names too. if (LOG.isDebugEnabled() && !ObjectUtils.equals(getPmName(), "password")) { LOG.debug("Changing PM value of '" + PmUtil.getPmLogString(this) + "' from '" + currentValue + "' to '" + newPmValue + "'."); } T_BEAN_VALUE beanAttrValue = (newPmValue != null) ? convertPmValueToBackingValue(newPmValue) : null; setBackingValue(beanAttrValue); getOwnMetaData().cacheStrategyForValue.setAndReturnCachedValue(this, newPmValue); } catch (Exception e) { throw PmRuntimeException.asPmRuntimeException(this, e); } // From now on the value should be handled as intentionally modified. // That means that the default value shouldn't be returned, even if the // value was set to <code>null</code>. valueWasSet = true; setValueChanged(currentValue, newPmValue); PmEventApi.firePmEvent(this, PmEvent.VALUE_CHANGE); return true; } else { return false; } } catch (RuntimeException e) { PmRuntimeException pmex = new PmRuntimeException(this, "Unable to set value: " + value, e); LOG.error("setValue failed", pmex); throw pmex; } } @Override public boolean isPmValueChanged() { return dataContainer != null && dataContainer.originalValue != UNCHANGED_VALUE_INDICATOR; } @Override public void setPmValueChanged(boolean newChangedState) { PmEventApi.ensureThreadEventSource(this); setValueChanged(UNKNOWN_VALUE_INDICATOR, newChangedState ? CHANGED_VALUE_INDICATOR : UNCHANGED_VALUE_INDICATOR); } static final String UNCHANGED_VALUE_INDICATOR = " static final String CHANGED_VALUE_INDICATOR = " static final String UNKNOWN_VALUE_INDICATOR = " /** * Detects a change by checking the <code>oldValue</code> and <code>newValue</code> * parameters. * <p> * Passing {@link #UNCHANGED_VALUE_INDICATOR} as <code>newValue</code> causes * a change of the internal managed <code>originalValue</code> to 'unchanged'.<br> * This way the current attribute value gets accepted as the 'original unchange' * value. * * @param oldValue The old value. * @param newValue The new value. */ private void setValueChanged(Object oldValue, Object newValue) { boolean fireStateChange = false; // Reset to an unchanged value state. Accepts the current value as the original one. if (newValue == UNCHANGED_VALUE_INDICATOR) { // prevent creation of a data container only to store the default value... if (dataContainer != null) { fireStateChange = (dataContainer.originalValue != UNCHANGED_VALUE_INDICATOR); dataContainer.originalValue = UNCHANGED_VALUE_INDICATOR; } } // Set the value: else { // Setting the attribute to the original value leads to an 'unchanged' state. if (ObjectUtils.equals(zz_getDataContainer().originalValue, newValue)) { fireStateChange = (dataContainer.originalValue != UNCHANGED_VALUE_INDICATOR); dataContainer.originalValue = UNCHANGED_VALUE_INDICATOR; } // Setting a value which is not the original one: else { // Remember the current value as the original one if the attribute was in an unchanged // state: if (dataContainer.originalValue == UNCHANGED_VALUE_INDICATOR) { fireStateChange = true; dataContainer.originalValue = oldValue; } else { // If the attribute gets changed back to its original value: Mark it as unchanged. if (ObjectUtils.equals(dataContainer.originalValue, newValue)) { fireStateChange = true; dataContainer.originalValue = UNCHANGED_VALUE_INDICATOR; } } } } if (fireStateChange) { PmEventApi.firePmEvent(this, PmEvent.VALUE_CHANGED_STATE_CHANGE); } } /** * The default implementation provides the default value provided by the * annotation {@link PmAttrCfg#defaultValue()}. * <p> * Subclasses may override the method {@link #getDefaultValueImpl()} to provide * some special implementation.<br> * For example an internationalized value... * * @return The default value for this attribute. */ protected final T_PM_VALUE getDefaultValue() { return getDefaultValueImpl(); } /** * Reads a PM request attribute with the name of the attribute. * * @return The read request attribute, converted to the attribute specific * type. <code>null</code> if there is no default value attribute * within the given request. */ private T_PM_VALUE getDefaultValueFromRequest() { String reqValue = getPmConversationImpl().getViewConnector().readRequestValue(getPmName()); try { return (reqValue != null) ? getConverter().stringToValue(this, reqValue) : null; } catch (PmConverterException e) { throw new PmRuntimeException(this, e); } } /** * The default implementation provides the default value provided by the * annotation {@link PmAttrCfg#defaultPath()} and (if that was * <code>null</code>) the value provided by {@link PmAttrCfg#defaultValue()}. * <p> * Subclasses may override this method to provide some special implementation. * <br> * For example an internationalized value... * <p> * The default implemenation internally handles the injection of request values to the * attributes. * * @return The default value for this attribute. */ // FIXME olaf: shouldn't that method return T_BEAN_VALUE ? // not yet changed because of the effort to change the meta data handling code... // alternatively: add a second method getDefaultBackingValue()... @SuppressWarnings("unchecked") protected T_PM_VALUE getDefaultValueImpl() { MetaData md = getOwnMetaData(); if (md.defaultPath != null) { // TODO: store a precompiled path // TODO: add local navigation within the element (like @valuePath} T_BEAN_VALUE bv = (T_BEAN_VALUE) PmExpressionApi.findByExpression(this, md.defaultPath); if (bv != null) { return convertBackingValueToPmValue(bv); } } // Lazy static default value initialization. // Reason: The converter does not yet work a PM initialization time. if (md.defaultValue == MetaData.NOT_INITIALIZED) { try { md.defaultValue = StringUtils.isNotBlank(md.defaultValueString) ? getConverter().stringToValue(this, md.defaultValueString) : null; } catch (PmConverterException e) { throw new PmRuntimeException(this, e); } } return (T_PM_VALUE) (md.defaultValue != null ? md.defaultValue : getDefaultValueFromRequest()); } /** * Sets the invalid value and propagates a {@link PmValidationMessage} to the * session. * * @param invValue * The invalid value. * @param msgKey * Key for the user message. * @param msgArgs * Values for the user message. */ private void zz_setAndPropagateInvalidValue(SetValueContainer<T_PM_VALUE> invValue, String msgKey, Object... msgArgs) { zz_getDataContainer().invalidValue = invValue; this.getPmConversationImpl().addPmMessage(new PmValidationMessage(this, invValue, msgKey, msgArgs)); PmEventApi.firePmEvent(this, getOwnMetaData().validationChangeEventMask); } /** * @return <code>true</code> when there is an invalid user data entry. */ private final boolean isInvalidValue() { return (dataContainer != null) && (dataContainer.invalidValue != null); } /** * Checks the attribute type specific <code>null</code> or empty value * condition. * * @return <code>true</code> when the value is a <code>null</code> or empty * value equivalent. */ protected boolean isEmptyValue(T_PM_VALUE value) { return (value == null); } /** * If this method returns <code>true</code>, each {@link #setValue(Object)} will cause an * immediate call to {@link #pmValidate()}. * <p> * Alternatively validation is usually triggered by a command. */ protected boolean isValidatingOnSetPmValue() { return ((PmElementBase) getPmParentElement()).isValidatingOnSetPmValue(); } /** * The default validation checks just the required condition. * More specific attribute classes have to add their specific validation * by overriding this method. * * @param value The value to validate. */ protected void validate(T_PM_VALUE value) throws PmValidationException { if (isRequired() && isEmptyValue(value)) { throw new PmValidationException(PmMessageUtil.makeRequiredWarning(this)); } } @Override public void pmValidate() { if (isPmVisible() && !isPmReadonly()) { boolean wasValid = isPmValid(); try { validate(getValue()); } catch (PmValidationException e) { PmResourceData exResData = e.getResourceData(); PmValidationMessage msg = new PmValidationMessage(this, exResData.msgKey, exResData.msgArgs); getPmConversationImpl().addPmMessage(msg); } boolean isValid = isPmValid(); if (isValid != wasValid) { PmEventApi.firePmEvent(this, getOwnMetaData().validationChangeEventMask); } } } private final boolean zz_validateAndSetValueAsString(SetValueContainer<T_PM_VALUE> vc) { zz_ensurePmInitialization(); try { if (isPmReadonly() && getFormatString() != null) { // Some UI controls (e.g. SWT Text) send an immediate value change event when they get initialized. // To prevent unnecessary (and problematic) set value loops, nothing happens if the actual // value gets set to a read-only attribute. // In case of formatted string representations the value change detection mechanism on value level // may detect a change if the format does not represent all details of the actual value. // To prevent such effects, this code checks if the formatted string output is still the same... // TODO: What about changing a if (! StringUtils.equals(getValueAsString(), vc.getStringValue())) { throw new PmRuntimeException(this, "Illegal attempt to set a new value to a read only attribute."); } return true; } clearPmInvalidValues(); String stringValue = vc.getStringValue(); try { vc.setPmValue(StringUtils.isNotBlank(stringValue) ? getConverter().stringToValue(this, stringValue) : null); } catch (PmRuntimeException e) { PmResourceData resData = e.getResourceData(); if (resData == null) { // XXX olaf: That happens in case of program bugs. // Should we re-throw the exception here? zz_setAndPropagateInvalidValue(vc, PmConstants.MSGKEY_VALIDATION_CONVERSION_FROM_STRING_FAILED, getPmShortTitle()); LOG.error(e.getMessage(), e); } else { zz_setAndPropagateInvalidValue(vc, resData.msgKey, resData.msgArgs); if (LOG.isDebugEnabled()) { LOG.debug("String to value conversion failed in attribute '" + PmUtil.getPmLogString(this) + "'. String value: " + stringValue); } } return false; } catch (PmConverterException e) { PmResourceData resData = e.getResourceData(); // TODO olaf: processing of converter message is not yet implemented. zz_setAndPropagateInvalidValue(vc, resData.msgKey, getPmShortTitle()); if (LOG.isDebugEnabled()) { LOG.debug("String to value conversion failed in attribute '" + PmUtil.getPmLogString(this) + "'. String value: '" + stringValue + "'. Caused by: " + e.getMessage()); } return false; } catch (RuntimeException e) { zz_setAndPropagateInvalidValue(vc, PmConstants.MSGKEY_VALIDATION_CONVERSION_FROM_STRING_FAILED, getPmShortTitle()); if (LOG.isDebugEnabled()) { LOG.debug("String to value conversion failed in attribute '" + PmUtil.getPmLogString(this) + "'. String value: " + stringValue, e); } return false; } return setValueImpl(vc); } catch (RuntimeException e) { PmRuntimeException pme = PmRuntimeException.asPmRuntimeException(this, e); LOG.error("setValueAsString failed to set value '" + vc.getStringValue() + "'", pme); throw pme; } } /** * Defaults to <code>true</code>. * <p> * Subclasses that don't implement the 'toString' methods should return <code>false</code>. * * @return <code>true</code> when the 'asString' operations are supported. */ // * FIXME olaf: A workaround for missing converter instances. // * Only remaining usages: // * s:selectManyPicklist and // * m:selectManyCheckbox // * Both should be refactored to use setValueAsStringList! After that this // * method signature should be removed. public boolean isSupportingAsStringValues() { return true; } /** * @return The converter that translates from and to the corresponding string representation. */ @SuppressWarnings("unchecked") protected Converter<T_PM_VALUE> getConverter() { Converter<T_PM_VALUE> c = (Converter<T_PM_VALUE>) getOwnMetaData().converter; if (c == null) { throw new PmRuntimeException(this, "Missing value converter."); } return c; } public boolean isBufferedPmValueMode() { return getPmParentElement().isBufferedPmValueMode(); } @SuppressWarnings("unchecked") public void commitBufferedPmChanges() { if (isBufferedPmValueMode() && bufferedValue != UNKNOWN_VALUE_INDICATOR) { setBackingValueImpl((T_BEAN_VALUE)bufferedValue); bufferedValue = UNKNOWN_VALUE_INDICATOR; } } public void rollbackBufferedPmChanges() { bufferedValue = UNKNOWN_VALUE_INDICATOR; } @SuppressWarnings("unchecked") public T_PM_VALUE convertBackingValueToPmValue(T_BEAN_VALUE backingValue) { return (T_PM_VALUE) backingValue; } @SuppressWarnings("unchecked") public T_BEAN_VALUE convertPmValueToBackingValue(T_PM_VALUE pmAttrValue) { return (T_BEAN_VALUE) pmAttrValue; } @SuppressWarnings("unchecked") public T_BEAN_VALUE getBackingValue() { return (bufferedValue != UNKNOWN_VALUE_INDICATOR) ? (T_BEAN_VALUE)bufferedValue : getBackingValueImpl(); } public void setBackingValue(T_BEAN_VALUE value) { if (isBufferedPmValueMode()) { bufferedValue = value; } else { setBackingValueImpl(value); } } /** * Provides the internal (non PM) data type representation of the attribute value. * <p> * Attributes may override this method to provide a specific implementation. * * @return The value (internal data type representation). */ @SuppressWarnings("unchecked") protected T_BEAN_VALUE getBackingValueImpl() { return (T_BEAN_VALUE) getOwnMetaData().valueAccessStrategy.getValue(this); } /** * Sets the internal (non PM) data type representation of the attribute value. * <p> * Attributes may override this method to provide a specific implementation. * * @param value The value to assign (internal data type representation). */ protected void setBackingValueImpl(T_BEAN_VALUE value) { getOwnMetaData().valueAccessStrategy.setValue(this, value); } @Override public String getFormatString() { String key = getOwnMetaData().formatResKey; String format = null; // 1. fix resource key definition if (key != null) { format = localize(key); } // 2. no fix key: try to find a postfix based definition else { key = getPmResKey() + PmConstants.RESKEY_POSTFIX_FORMAT; format = findLocalization(key); // 3. Try a default key (if defined for this attribute) if (format == null) { key = getFormatDefaultResKey(); if (key != null) { format = findLocalization(key); } } } return format; } /** * Concrete attribute classes may specify here a default format resource key * as a fallback for unspecified format localizations. * * @return The fallback resource key or <code>null</code> if there is none. */ protected String getFormatDefaultResKey() { return null; } @Override Serializable getPmContentAspect(PmAspect aspect) { switch (aspect) { case VALUE: T_PM_VALUE v = getValue(); return getConverter().valueToSerializable(this, v); default: return super.getPmContentAspect(aspect); } } @Override void setPmContentAspect(PmAspect aspect, Serializable value) throws PmConverterException { PmEventApi.ensureThreadEventSource(this); switch (aspect) { case VALUE: setValue(getConverter().serializeableToValue(this, value)); break; default: super.setPmContentAspect(aspect, value); } } /** * Provides a data container. Creates it on the fly when it does not already * exist. * * @return The container for optional data parts. */ private final PmAttrDataContainer<T_PM_VALUE, T_BEAN_VALUE> zz_getDataContainer() { if (dataContainer == null) { dataContainer = new PmAttrDataContainer<T_PM_VALUE, T_BEAN_VALUE>(); } return dataContainer; } /** The optional JSR-303 bean validator to be considered. */ private static ValidatorFactory zz_validatorFactory; { try { zz_validatorFactory = Validation.buildDefaultValidatorFactory(); } catch (ValidationException e) { LOG.info("No JSR-303 bean validation configuration found:" + e.getMessage()); } } /** * Gets called when the meta data instance for this presentation model * is not yet available (first call within the VM live time). * <p> * Subclasses that provide more specific meta data should override this method * to provide their meta data information container. * * @param attrName The name of the attribute. Unique within the parent element scope. * @return A meta data container for this presentation model. */ @Override protected PmObjectBase.MetaData makeMetaData() { return new MetaData(); } // XXX olaf: really required? May be solved by overriding initMetaData too. protected PmOptionSetDef<?> makeOptionSetDef(PmOptionCfg cfg, Method getOptionValuesMethod) { return cfg != null ? new GenericOptionSetDef(cfg, getOptionValuesMethod) : OptionSetDefNoOption.INSTANCE; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override protected void initMetaData(PmObjectBase.MetaData metaData) { super.initMetaData(metaData); MetaData myMetaData = (MetaData) metaData; Class<?> beanClass = (getPmParent() instanceof PmBean) ? ((PmBean)getPmParent()).getPmBeanClass() : null; PmAttrCfg fieldAnnotation = findAnnotation(PmAttrCfg.class); zz_readBeanValidationRestrictions(beanClass, fieldAnnotation, myMetaData); // read the option configuration first from the getOptionValues() // method. If not found there: From the attribute- and class declaration. Method getOptionValuesMethod = null; PmOptionCfg optionCfg = null; try { getOptionValuesMethod = getClass().getMethod("getOptionValues"); if (getOptionValuesMethod.getDeclaringClass() != PmAttrBase.class) { optionCfg = getOptionValuesMethod.getAnnotation(PmOptionCfg.class); // XXX: not really fine for security contexts. getOptionValuesMethod.setAccessible(true); } else { getOptionValuesMethod = null; } } catch (Exception e) { throw new PmRuntimeException(this, "Unable to access method 'getOptionValues'.", e); } if (optionCfg == null) { optionCfg = findAnnotation(PmOptionCfg.class); } myMetaData.optionSetDef = (PmOptionSetDef) makeOptionSetDef(optionCfg, getOptionValuesMethod); if (myMetaData.optionSetDef != OptionSetDefNoOption.INSTANCE) { myMetaData.setItemConverter( new PmConverterOptionBased(optionCfg != null ? optionCfg.id() : "")); } boolean useReflection = true; if (fieldAnnotation != null) { myMetaData.hideWhenEmpty = fieldAnnotation.hideWhenEmpty(); myMetaData.setReadOnly(fieldAnnotation.readOnly()); // The pm can force more constraints. It should not define less constraints as // the bean validation definition: if (fieldAnnotation.required()) { myMetaData.required = true; } myMetaData.accessKind = fieldAnnotation.accessKind(); myMetaData.formatResKey = StringUtils.defaultIfEmpty(fieldAnnotation.formatResKey(), null); if (StringUtils.isNotEmpty(fieldAnnotation.defaultValue())) { myMetaData.defaultValueString = fieldAnnotation.defaultValue(); } myMetaData.defaultPath = StringUtils.defaultIfEmpty(fieldAnnotation.defaultPath(), null); switch (myMetaData.accessKind) { case DEFAULT: if (StringUtils.isNotBlank(fieldAnnotation.valuePath())) { myMetaData.valuePathResolver = PmExpressionPathResolver.parse(fieldAnnotation.valuePath(), true); useReflection = false; myMetaData.valueAccessStrategy = ValueAccessByExpression.INSTANCE; } break; case OVERRIDE: useReflection = false; myMetaData.valueAccessStrategy = ValueAccessOverride.INSTANCE; break; case SESSIONPROPERTY: useReflection = false; myMetaData.valueAccessStrategy = ValueAccessSessionProperty.INSTANCE; break; case LOCALVALUE: useReflection = false; myMetaData.valueAccessStrategy = ValueAccessLocal.INSTANCE; break; default: throw new PmRuntimeException(this, "Unknown annotation kind: " + fieldAnnotation.accessKind()); } } if (myMetaData.accessKind == AttrAccessKind.DEFAULT) { try { // FIXME: shouldn't be required. overriding should make internal strategies obsolete. Method m = getClass().getDeclaredMethod("getBackingValueImpl"); if (!m.getDeclaringClass().equals(PmAttrBase.class)) { myMetaData.accessKind = AttrAccessKind.OVERRIDE; myMetaData.valueAccessStrategy = ValueAccessOverride.INSTANCE; useReflection = false; } } catch (SecurityException e) { throw new PmRuntimeException(this, "Reflection base class analysis failed for PM class '" + getClass() + "'.", e); } catch (NoSuchMethodException e) { // ok. the method is not overridden locally. } } if (useReflection) { if (beanClass != null) { try { myMetaData.beanAttrAccessor = new BeanAttrAccessorImpl(beanClass, getPmName()); } catch (RuntimeException e) { PmObjectUtil.throwAsPmRuntimeException(this, e); } if (myMetaData.beanAttrAccessor.getFieldClass().isPrimitive()) { myMetaData.primitiveType = true; if (fieldAnnotation == null) { myMetaData.required = true; } } myMetaData.valueAccessStrategy = ValueAccessReflection.INSTANCE; } } // Use default attribute title provider if no specific provider was configured. if (metaData.getPmTitleProvider() == getPmConversation().getPmDefaults().getPmTitleProvider()) { metaData.setPmTitleProvider(getPmConversation().getPmDefaults().getPmAttrTitleProvider()); } // -- Cache configuration -- List<PmCacheCfg> cacheAnnotations = new ArrayList<PmCacheCfg>(); findAnnotationsInPmHierarchy(PmCacheCfg.class, cacheAnnotations); myMetaData.cacheStrategyForOptions = readCacheStrategy(PmCacheCfg.ATTR_OPTIONS, cacheAnnotations, CACHE_STRATEGIES_FOR_OPTIONS); myMetaData.cacheStrategyForValue = readCacheStrategy(PmCacheCfg.ATTR_VALUE, cacheAnnotations, CACHE_STRATEGIES_FOR_VALUE); } private void zz_readBeanValidationRestrictions(Class<?> beanClass, PmAttrCfg fieldAnnotation, MetaData myMetaData) { if (zz_validatorFactory == null) return; Class<?> srcClass = ((fieldAnnotation != null) && (fieldAnnotation.beanInfoClass() != Void.class)) ? fieldAnnotation.beanInfoClass() : beanClass; if (srcClass != null) { BeanDescriptor beanDescriptor = zz_validatorFactory.getValidator().getConstraintsForClass(srcClass); if (beanDescriptor != null) { String propName = ((fieldAnnotation != null) && (StringUtils.isNotBlank(fieldAnnotation.beanInfoField()))) ? fieldAnnotation.beanInfoField() : myMetaData.getName(); PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty(propName); if (propertyDescriptor != null) { for (ConstraintDescriptor<?> cd : propertyDescriptor.getConstraintDescriptors()) { initMetaDataBeanConstraint(cd); } } } } } /** * Gets called for each found {@link ConstraintDescriptor}.<br> * The default implementation just checks the {@link NotNull} restrictions.<br/> * Sub classes override this method to consider other restrictions. * * @param cd The {@link ConstraintDescriptor} to consider for this attribute. */ protected void initMetaDataBeanConstraint(ConstraintDescriptor<?> cd) { if (cd.getAnnotation() instanceof NotNull) { getOwnMetaData().required = true; } } /** * Shared meta data for all attributes of the same kind. * E.g. for all 'myapp.User.name' attributes. */ protected static class MetaData extends PmObjectBase.MetaData { static final Object NOT_INITIALIZED = "NOT_INITIALIZED"; private BeanAttrAccessor beanAttrAccessor; private PmOptionSetDef<PmAttr<?>> optionSetDef = OptionSetDefNoOption.INSTANCE; private boolean hideWhenEmpty; private boolean required; private boolean primitiveType; // private PmValueStrategy pmValueStrategy; private PathResolver valuePathResolver; private PmAttrCfg.AttrAccessKind accessKind = PmAttrCfg.AttrAccessKind.DEFAULT; private String formatResKey; private String defaultValueString; /** The default provided by the annotation, converted to T_PM_VALUE. */ private Object defaultValue = NOT_INITIALIZED; private String defaultPath; private PmCacheStrategy cacheStrategyForOptions = PmCacheStrategyNoCache.INSTANCE; private PmCacheStrategy cacheStrategyForValue = PmCacheStrategyNoCache.INSTANCE; private Converter<?> converter; private BackingValueAccessStrategy valueAccessStrategy = ValueAccessLocal.INSTANCE; /** @return The statically defined option set algorithm. */ public PmOptionSetDef<PmAttr<?>> getOptionSetDef() { return optionSetDef; } public String getFormatResKey() { return formatResKey; } public void setFormatResKey(String formatResKey) { this.formatResKey = formatResKey; } public PmCacheStrategy getCacheStrategyForOptions() { return cacheStrategyForOptions; } public PmCacheStrategy getCacheStrategyForValue() { return cacheStrategyForValue; } public Converter<?> getConverter() { return converter; } public void setConverter(Converter<?> converter) { this.converter = converter; } /** * Multi value attributes (like lists) have specific item converters. * <p> * For single value attributes there is no difference between * {@link #converter} and the <code>itemConverter</code>. * * @param converter The converter for attribute items. */ public void setItemConverter(Converter<?> converter) { setConverter(converter); } /** @see #setItemConverter(org.pm4j.core.pm.PmAttr.Converter) */ public Converter<?> getItemConverter() { return getConverter(); } /** * If the converter was not explicitly defined by a user annotation, this * method will be used to define a attribute type specific converter. */ public void setConverterDefault(Converter<?> converter) { assert converter != null; if (this.converter == null) this.converter = converter; } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } } private final MetaData getOwnMetaData() { return (MetaData) getPmMetaData(); } private static final PmCacheStrategy CACHE_VALUE_LOCAL = new PmCacheStrategyBase<PmAttrBase<?,?>>("CACHE_VALUE_LOCAL") { @Override protected Object readRawValue(PmAttrBase<?, ?> pm) { return (pm.dataContainer != null) ? pm.dataContainer.cachedValue : null; } @Override protected void writeRawValue(PmAttrBase<?, ?> pm, Object value) { pm.zz_getDataContainer().cachedValue = value; } @Override protected void clearImpl(PmAttrBase<?, ?> pm) { if (pm.dataContainer != null) { pm.dataContainer.cachedValue = null; } } }; private static final PmCacheStrategy CACHE_OPTIONS_LOCAL = new PmCacheStrategyBase<PmAttrBase<?,?>>("CACHE_OPTIONS_LOCAL") { @Override protected Object readRawValue(PmAttrBase<?, ?> pm) { return (pm.dataContainer != null) ? pm.dataContainer.cachedOptionSet : null; } @Override protected void writeRawValue(PmAttrBase<?, ?> pm, Object value) { pm.zz_getDataContainer().cachedOptionSet = value; } @Override protected void clearImpl(PmAttrBase<?, ?> pm) { if (pm.dataContainer != null) { pm.dataContainer.cachedOptionSet = null; } } }; private static final Map<CacheMode, PmCacheStrategy> CACHE_STRATEGIES_FOR_VALUE = MapUtil.makeFixHashMap( CacheMode.OFF, PmCacheStrategyNoCache.INSTANCE, CacheMode.ON, CACHE_VALUE_LOCAL, CacheMode.REQUEST, new PmCacheStrategyRequest("CACHE_VALUE_IN_REQUEST", "v") ); private static final Map<CacheMode, PmCacheStrategy> CACHE_STRATEGIES_FOR_OPTIONS = MapUtil.makeFixHashMap( CacheMode.OFF, PmCacheStrategyNoCache.INSTANCE, CacheMode.ON, CACHE_OPTIONS_LOCAL, CacheMode.REQUEST, new PmCacheStrategyRequest("CACHE_OPTIONS_IN_REQUEST", "os") ); interface BackingValueAccessStrategy { Object getValue(PmAttrBase<?, ?> attr); void setValue(PmAttrBase<?, ?> attr, Object value); } static class ValueAccessLocal implements BackingValueAccessStrategy { static final BackingValueAccessStrategy INSTANCE = new ValueAccessLocal(); @Override public Object getValue(PmAttrBase<?, ?> attr) { return attr.dataContainer != null ? attr.dataContainer.localValue : null; } @Override public void setValue(PmAttrBase<?, ?> attr, Object value) { attr.zz_getDataContainer().localValue = value; } } static class ValueAccessSessionProperty implements BackingValueAccessStrategy { static final BackingValueAccessStrategy INSTANCE = new ValueAccessSessionProperty(); @Override public Object getValue(PmAttrBase<?, ?> attr) { return attr.getPmConversation().getPmNamedObject(PmUtil.getAbsoluteName(attr)); } @Override public void setValue(PmAttrBase<?, ?> attr, Object value) { attr.getPmConversation().setPmNamedObject(PmUtil.getAbsoluteName(attr), value); } } // TODO: should disappear as soon as the value strategy configuration is complete. static class ValueAccessOverride implements BackingValueAccessStrategy { static final BackingValueAccessStrategy INSTANCE = new ValueAccessOverride(); @Override public Object getValue(PmAttrBase<?, ?> attr) { throw new PmRuntimeException(attr, "getBackingValueImpl() method is not implemented."); } @Override public void setValue(PmAttrBase<?, ?> attr, Object value) { throw new PmRuntimeException(attr, "setBackingValueImpl() method is not implemented."); } } static class ValueAccessByExpression implements BackingValueAccessStrategy { static final BackingValueAccessStrategy INSTANCE = new ValueAccessByExpression(); @Override public Object getValue(PmAttrBase<?, ?> attr) { return attr.getOwnMetaData().valuePathResolver.getValue(attr.getPmParent()); } @Override public void setValue(PmAttrBase<?, ?> attr, Object value) { attr.getOwnMetaData().valuePathResolver.setValue(attr.getPmParent(), value); } } static class ValueAccessReflection implements BackingValueAccessStrategy { static final BackingValueAccessStrategy INSTANCE = new ValueAccessReflection(); @Override public Object getValue(PmAttrBase<?, ?> attr) { return attr.getOwnMetaData().beanAttrAccessor.<Object>getBeanAttrValue(getPmParentElementBean(attr)); } @Override public void setValue(PmAttrBase<?, ?> attr, Object value) { attr.getOwnMetaData().beanAttrAccessor.setBeanAttrValue(getPmParentElementBean(attr), value); } @SuppressWarnings("unchecked") private final Object getPmParentElementBean(PmAttrBase<?, ?> attr) { Object bean = ((PmBean<Object>)attr.getPmParentElement()).getPmBean(); if (bean == null) { throw new PmRuntimeException(attr, "Unable to access an attribute value for a backing pmBean that is 'null'."); } return bean; } } }
package opendap.io; import opendap.ppt.PPTSessionProtocol; import org.slf4j.Logger; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Chunk { public static final int HEADER_SIZE_ENCODING_BYTES = 7; public static final int HEADER_TYPE_ENCODING_BYTES = 1; public static final int HEADER_SIZE = HEADER_SIZE_ENCODING_BYTES + HEADER_TYPE_ENCODING_BYTES; /** * The CHUNK_SIZE_BIT_MASK is calculated based on the number of bytes * specified by the HEADER_SIZE_ENCODING_BYTES. */ private static int BIT_MASK; static { BIT_MASK = 0; for(int i=0; i< HEADER_SIZE_ENCODING_BYTES;i++){ BIT_MASK = (BIT_MASK<<4) + 0x000f; //System.out.println("BIT_MASK: 0x"+ Integer.toHexString(BIT_MASK)); } } public static final int SIZE_BIT_MASK = BIT_MASK; public static final int MAX_SIZE = BIT_MASK; public static final int DATA = 'd'; public static final int EXTENSION = 'x'; public static final int DEFAULT_SIZE = 65535; public static final byte[] closingChunk = new byte[HEADER_SIZE]; static { int i; for(i=0; i<HEADER_SIZE_ENCODING_BYTES; i++){ closingChunk[i] = '0'; } closingChunk[i] = DATA; } public static final String STATUS_EXTENSION = "status="; public static final String ERROR_STATUS = "error"; public static final String EMERGENCY_EXIT_STATUS = "exit"; public static final String EXIT_STATUS = PPTSessionProtocol.PPT_EXIT_NOW; public static final String COUNT_EXTENSION = "count="; private static final Logger log = org.slf4j.LoggerFactory.getLogger(Chunk.class); /** * * @param chunkHeader * @return The size, in bytes, of the data section of this chunk. If the * passed header is the closing chunk (Size is all zeros) this is taken to * indicate that the transmission is at an end and a -1 is returned. * @throws IOException */ public static int getDataSize(byte[] chunkHeader) throws IOException{ StringBuilder sizestr = new StringBuilder(); for(int i=0; i<HEADER_SIZE_ENCODING_BYTES; i++){ sizestr.append((char) chunkHeader[i]); } //log.error("ChunkSizeString: "+sizestr); int chunkSize; try { chunkSize = Integer.valueOf(sizestr.toString(),16); } catch(NumberFormatException e){ throw new IOException("Failed to parse Chunk header data size field. " + "Caught " + e.getClass().getName() + " msg: "+e.getMessage()); } //log.error("ChunkSize: "+chunkSize); if(chunkSize==0){ return -1; } return chunkSize; } public static boolean isLastChunk(byte[] chunkHeader){ StringBuilder sizestr = new StringBuilder(); for(int i=0; i<HEADER_SIZE_ENCODING_BYTES; i++){ sizestr.append((char) chunkHeader[i]); } //System.out.println("ChunkSizeString: "+sizestr); int chunkSize = Integer.valueOf(sizestr.toString(),16); //System.out.println("ChunkSize: "+chunkSize); return chunkSize == 0; } public static int getType(byte[] chunkHeader) throws IOException { byte[] type = new byte[HEADER_TYPE_ENCODING_BYTES]; int j=0; for(int i=HEADER_SIZE_ENCODING_BYTES; i<HEADER_SIZE; i++){ type[j++] = chunkHeader[i]; } if(type.length == 1){ return type[0]; } else { throw new IOException("Size of Chunk Type Encoding has changed." + "The implmentation of opendap.io.Chunk is not compatible" + "with this change. Reimplment Chunk!"); } } static int readFully(InputStream is, byte[] buf, int off, int len) throws IOException { if( buf!=null && // Make sure the buffer is not null len>=0 && // Make sure they want a positive number of bytes off>=0 && // Make sure the offset is positive // Guard against buffer overflow buf.length>=(off+len) ){ boolean done = false; int bytesToRead = len; int totalBytesRead =0; int bytesRead; while (!done) { bytesRead = is.read(buf, off, len); if (bytesRead == -1) { if (totalBytesRead == 0) totalBytesRead = -1; done = true; } else { totalBytesRead += bytesRead; if(totalBytesRead == bytesToRead){ done = true; } else { len = bytesToRead - totalBytesRead; off += bytesRead; } } } return totalBytesRead; } else { String msg = "Attempted to read "+len+" bytes starting " + "at "+off; if(buf==null) msg += " into a null reference. "; else msg += " into a buffer of length "+buf.length+" "; msg += "I'm afraid I can't allow that..."; log.error(msg); throw new IOException(msg); } } /** * * Send closing chunk. This is a chunk header where the size is zero and * the chunk type is always "DATA". <p> * Example: {'0','0','0','0','d'} * * @param os The stream to which to write the closing chunk header. * @throws IOException When the wrapped OutputStream encounters a problem. */ public static void writeClosingChunkHeader(OutputStream os) throws IOException { if(os==null) throw new IOException("Chunk.writeClosingChunkHeader() - Passed " + "OutputStream reference is null."); log.debug("writeClosingChunkHeader(): "+new String(closingChunk,HyraxStringEncoding.getCharset())); os.write(closingChunk); os.flush(); } /** * * Writes a chunk header to the underlying stream. The passed <code> * dataSize<code> parameter specifies the size of the data about to be sent, * not including the size of the chunk header. The chunk header size is * added by this method prior writing the size to the stream. * * @param os The stream to which to write the chunk header. * @param dataSize The size of the data portion of the chunk. * @param type The type of the chunk * @throws IOException When things go wrong. */ public static void writeChunkHeader(OutputStream os, int dataSize, int type) throws IOException { if(os==null) throw new IOException("Chunk.writeChunkHeader() - Passed " + "OutputStream reference is null."); if( dataSize > Chunk.MAX_SIZE) throw new IOException("Chunk size of "+dataSize+ " bytes is to " + "large to be encoded."); byte[] header = new byte[Chunk.HEADER_SIZE]; String size = Integer.toHexString(Chunk.SIZE_BIT_MASK & dataSize); while(size.length() < Chunk.HEADER_SIZE_ENCODING_BYTES){ size = "0" + size; } log.debug("writeChunkHeader() - size: "+size+" size.length: "+size.length()+" type: "+(char)type); System.arraycopy(size.getBytes(HyraxStringEncoding.getCharset()),0,header,0,Chunk.HEADER_SIZE-1); header[Chunk.HEADER_SIZE-1] = (byte) type; os.write(header); } public String toString(){ String msg ="Chunk: \n"; msg += " DEFAULT_SIZE: "+ DEFAULT_SIZE +"\n"; msg += " HEADER_SIZE_ENCODING_BYTES: "+ HEADER_SIZE_ENCODING_BYTES +"\n"; msg += " HEADER_TYPE_ENCODING_BYTES: "+ HEADER_TYPE_ENCODING_BYTES +"\n"; msg += " CHUNK_HEADER_SIZE: "+ HEADER_SIZE +"\n"; msg += " CHUNK_SIZE_BIT_MASK: 0x"+ Integer.toHexString(SIZE_BIT_MASK) +"\n"; msg += " MAX_CHUNK_SIZE: "+ MAX_SIZE +"\n"; return msg; } /** * Reads a chunk header into the passed byte buffer begining at location * off. The number of bytes is determined by the value of the <code> * HEADER_SIZE<code> constant * * @param is The InputStream from which to read the header. * @param header The array into which to read the chunk header. * @param off The offset within the array header at which to start placing * the bytes of header. * @return The number of bytes in the chunk, or -1 if the underlying stream * has no more bytes to read. * @throws java.io.IOException When the underlying stream does. * @see #HEADER_SIZE * */ public static int readChunkHeader(InputStream is, byte[] header, int off) throws IOException { if(header.length-off<HEADER_SIZE) throw new IOException("Header will exceed bounds of passed array."); try { int ret; // Read the header ret = readFully(is, header,off, HEADER_SIZE); if(ret==-1) return ret; int size = getDataSize(header); return size; } catch(IOException e) { log.error(" - Caught {} Msg: {}",e.getClass().getName(),e.getMessage()); StringBuilder sb = new StringBuilder(); sb.append(" - InputStream Dump: \n"); try { boolean done = false; while (!done) { byte b[] = new byte[4096]; int c = is.read(b); if (c < 4096) { done = true; } for (int i = 0; i < c; i++) { sb.append((char) b[i]); } } } catch (Exception m){ sb.append("OUCH! FAILED TO DRAIN STREAM! Caught ").append(m.getClass().getName()); sb.append(" Message: ").append(m.getMessage()); } finally { sb.append("\nDUMP END\n"); } sb.append("RETHROWING ").append(e.getClass().getName()).append("\n"); log.error(sb.toString()); throw e; } } }
package opendap.io; import opendap.ppt.PPTSessionProtocol; import org.slf4j.Logger; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Chunk { public static final int HEADER_SIZE_ENCODING_BYTES = 7; public static final int HEADER_TYPE_ENCODING_BYTES = 1; public static final int HEADER_SIZE = HEADER_SIZE_ENCODING_BYTES + HEADER_TYPE_ENCODING_BYTES; /** * The CHUNK_SIZE_BIT_MASK is calculated based on the number of bytes * specified by the HEADER_SIZE_ENCODING_BYTES. */ private static int BIT_MASK; static { BIT_MASK = 0; for(int i=0; i< HEADER_SIZE_ENCODING_BYTES;i++){ BIT_MASK = (BIT_MASK<<4) + 0x000f; //System.out.println("BIT_MASK: 0x"+ Integer.toHexString(BIT_MASK)); } } public static final int SIZE_BIT_MASK = BIT_MASK; public static final int MAX_SIZE = BIT_MASK; public static final int DATA = 'd'; public static final int EXTENSION = 'x'; public static final int DEFAULT_SIZE = 65535; public static final byte[] closingChunk = new byte[HEADER_SIZE]; static { int i; for(i=0; i<HEADER_SIZE_ENCODING_BYTES; i++){ closingChunk[i] = '0'; } closingChunk[i] = DATA; } public static final String STATUS_EXTENSION = "status="; public static final String ERROR_STATUS = "error"; public static final String EMERGENCY_EXIT_STATUS = "exit"; public static final String EXIT_STATUS = PPTSessionProtocol.PPT_EXIT_NOW; public static final String COUNT_EXTENSION = "count="; private static final Logger log = org.slf4j.LoggerFactory.getLogger(Chunk.class); /** * * @param chunkHeader * @return The size, in bytes, of the data section of this chunk. If the * passed header is the closing chunk (Size is all zeros) this is taken to * indicate that the transmission is at an end and a -1 is returned. * @throws IOException */ public static int getDataSize(byte[] chunkHeader) throws IOException{ StringBuilder sizestr = new StringBuilder(); for(int i=0; i<HEADER_SIZE_ENCODING_BYTES; i++){ sizestr.append((char) chunkHeader[i]); } log.error("ChunkSizeString: "+sizestr); int chunkSize = 0; try { Integer.valueOf(sizestr.toString(),16); } catch(NumberFormatException e){ throw new IOException("Failed to parse Chunk header datasize field. msg:"+e.getMessage()); } log.error("ChunkSize: "+chunkSize); if(chunkSize==0){ return -1; } return chunkSize; } public static boolean isLastChunk(byte[] chunkHeader){ StringBuilder sizestr = new StringBuilder(); for(int i=0; i<HEADER_SIZE_ENCODING_BYTES; i++){ sizestr.append((char) chunkHeader[i]); } //System.out.println("ChunkSizeString: "+sizestr); int chunkSize = Integer.valueOf(sizestr.toString(),16); //System.out.println("ChunkSize: "+chunkSize); return chunkSize == 0; } public static int getType(byte[] chunkHeader) throws IOException { byte[] type = new byte[HEADER_TYPE_ENCODING_BYTES]; int j=0; for(int i=HEADER_SIZE_ENCODING_BYTES; i<HEADER_SIZE; i++){ type[j++] = chunkHeader[i]; } if(type.length == 1){ return type[0]; } else { throw new IOException("Size of Chunk Type Encoding has changed." + "The implmentation of opendap.io.Chunk is not compatible" + "with this change. Reimplment Chunk!"); } } static int readFully(InputStream is, byte[] buf, int off, int len) throws IOException{ if( buf!=null && // Make sure the buffer is not null len>=0 && // Make sure they want a positive number of bytes off>=0 && // Make sure the offset is positive // Guard against buffer overflow buf.length>=(off+len) ){ boolean done = false; int bytesToRead = len; int totalBytesRead =0; int bytesRead; while(!done){ bytesRead = is.read(buf,off,len); if(bytesRead == -1){ if(totalBytesRead==0) totalBytesRead=-1; done = true; } else { totalBytesRead += bytesRead; if(totalBytesRead == bytesToRead){ done = true; } else { len = bytesToRead - totalBytesRead; off += bytesRead; } } } return totalBytesRead; } else { String msg = "Attempted to read "+len+" bytes starting " + "at "+off; if(buf==null) msg += " into a null reference. "; else msg += " into a buffer of length "+buf.length+" "; msg += "I'm afraid I can't allow that..."; log.error(msg); throw new IOException(msg); } } /** * * Send closing chunk. This is a chunk header where the size is zero and * the chunk type is always "DATA". <p> * Example: {'0','0','0','0','d'} * * @param os The stream to which to write the closing chunk header. * @throws IOException When the wrapped OutputStream encounters a problem. */ public static void writeClosingChunkHeader(OutputStream os) throws IOException { if(os==null) throw new IOException("Chunk.writeClosingChunkHeader() - Passed " + "OutputStream reference is null."); log.debug("writeClosingChunkHeader(): "+new String(closingChunk,HyraxStringEncoding.getCharset())); os.write(closingChunk); os.flush(); } /** * * Writes a chunk header to the underlying stream. The passed <code> * dataSize<code> parameter specifies the size of the data about to be sent, * not including the size of the chunk header. The chunk header size is * added by this method prior writing the size to the stream. * * @param os The stream to which to write the chunk header. * @param dataSize The size of the data portion of the chunk. * @param type The type of the chunk * @throws IOException When things go wrong. */ public static void writeChunkHeader(OutputStream os, int dataSize, int type) throws IOException { if(os==null) throw new IOException("Chunk.writeChunkHeader() - Passed " + "OutputStream reference is null."); if( dataSize > Chunk.MAX_SIZE) throw new IOException("Chunk size of "+dataSize+ " bytes is to " + "large to be encoded."); byte[] header = new byte[Chunk.HEADER_SIZE]; String size = Integer.toHexString(Chunk.SIZE_BIT_MASK & dataSize); while(size.length() < Chunk.HEADER_SIZE_ENCODING_BYTES){ size = "0" + size; } log.debug("writeChunkHeader() - size: "+size+" size.length: "+size.length()+" type: "+(char)type); System.arraycopy(size.getBytes(HyraxStringEncoding.getCharset()),0,header,0,Chunk.HEADER_SIZE-1); header[Chunk.HEADER_SIZE-1] = (byte) type; os.write(header); } public String toString(){ String msg ="Chunk: \n"; msg += " DEFAULT_SIZE: "+ DEFAULT_SIZE +"\n"; msg += " HEADER_SIZE_ENCODING_BYTES: "+ HEADER_SIZE_ENCODING_BYTES +"\n"; msg += " HEADER_TYPE_ENCODING_BYTES: "+ HEADER_TYPE_ENCODING_BYTES +"\n"; msg += " CHUNK_HEADER_SIZE: "+ HEADER_SIZE +"\n"; msg += " CHUNK_SIZE_BIT_MASK: 0x"+ Integer.toHexString(SIZE_BIT_MASK) +"\n"; msg += " MAX_CHUNK_SIZE: "+ MAX_SIZE +"\n"; return msg; } /** * Reads a chunk header into the passed byte buffer begining at location * off. The number of bytes is determined by the value of the <code> * HEADER_SIZE<code> constant * * @param is The InputStream from which to read the header. * @param header The array into which to read the chunk header. * @param off The offset within the array header at which to start placing * the bytes of header. * @return The number of bytes in the chunk, or -1 if the underlying stream * has no more bytes to read. * @throws java.io.IOException When the underlying stream does. * @see #HEADER_SIZE * */ public static int readChunkHeader(InputStream is, byte[] header, int off) throws IOException { if(header.length-off<HEADER_SIZE) throw new IOException("Header will exceed bounds of passed array."); int ret; // Read the header ret = Chunk.readFully(is, header,off, HEADER_SIZE); if(ret==-1) return ret; return getDataSize(header); } }
package arez.processor; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; final class ProcessorUtil { private ProcessorUtil() { } @SuppressWarnings( "unchecked" ) static boolean isWarningSuppressed( @Nonnull final Element element, @Nonnull final String warning, @Nullable final String alternativeSuppressWarnings ) { if ( null != alternativeSuppressWarnings ) { final AnnotationMirror suppress = AnnotationsUtil.findAnnotationByType( element, alternativeSuppressWarnings ); if ( null != suppress ) { final AnnotationValue value = AnnotationsUtil.findAnnotationValueNoDefaults( suppress, "value" ); if ( null != value ) { final List<AnnotationValue> warnings = (List<AnnotationValue>) value.getValue(); for ( final AnnotationValue suppression : warnings ) { if ( warning.equals( suppression.getValue() ) ) { return true; } } } } } final SuppressWarnings annotation = element.getAnnotation( SuppressWarnings.class ); if ( null != annotation ) { for ( final String suppression : annotation.value() ) { if ( warning.equals( suppression ) ) { return true; } } } final Element enclosingElement = element.getEnclosingElement(); return null != enclosingElement && isWarningSuppressed( enclosingElement, warning, alternativeSuppressWarnings ); } @Nonnull static List<TypeElement> getSuperTypes( @Nonnull final TypeElement element ) { final List<TypeElement> superTypes = new ArrayList<>(); enumerateSuperTypes( element, superTypes ); return superTypes; } private static void enumerateSuperTypes( @Nonnull final TypeElement element, @Nonnull final List<TypeElement> superTypes ) { final TypeMirror superclass = element.getSuperclass(); if ( TypeKind.NONE != superclass.getKind() ) { final TypeElement superclassElement = (TypeElement) ( (DeclaredType) superclass ).asElement(); superTypes.add( superclassElement ); enumerateSuperTypes( superclassElement, superTypes ); } for ( final TypeMirror interfaceType : element.getInterfaces() ) { final TypeElement interfaceElement = (TypeElement) ( (DeclaredType) interfaceType ).asElement(); enumerateSuperTypes( interfaceElement, superTypes ); } } @Nonnull static List<TypeElement> getInterfaces( @Nonnull final TypeElement element ) { final List<TypeElement> superTypes = new ArrayList<>(); enumerateInterfaces( element, superTypes ); return superTypes; } private static void enumerateInterfaces( @Nonnull final TypeElement element, @Nonnull final List<TypeElement> superTypes ) { final TypeMirror superclass = element.getSuperclass(); if ( TypeKind.NONE != superclass.getKind() ) { final TypeElement superclassElement = (TypeElement) ( (DeclaredType) superclass ).asElement(); enumerateInterfaces( superclassElement, superTypes ); } for ( final TypeMirror interfaceType : element.getInterfaces() ) { final TypeElement interfaceElement = (TypeElement) ( (DeclaredType) interfaceType ).asElement(); superTypes.add( interfaceElement ); enumerateInterfaces( interfaceElement, superTypes ); } } @Nonnull static List<VariableElement> getFieldElements( @Nonnull final TypeElement element ) { final Map<String, VariableElement> methodMap = new LinkedHashMap<>(); enumerateFieldElements( element, methodMap ); return new ArrayList<>( methodMap.values() ); } private static void enumerateFieldElements( @Nonnull final TypeElement element, @Nonnull final Map<String, VariableElement> fields ) { final TypeMirror superclass = element.getSuperclass(); if ( TypeKind.NONE != superclass.getKind() ) { enumerateFieldElements( (TypeElement) ( (DeclaredType) superclass ).asElement(), fields ); } for ( final Element member : element.getEnclosedElements() ) { if ( member.getKind() == ElementKind.FIELD ) { fields.put( member.getSimpleName().toString(), (VariableElement) member ); } } } @Nonnull static List<ExecutableElement> getMethods( @Nonnull final TypeElement element, @Nonnull final Elements elementUtils, @Nonnull final Types typeUtils ) { final Map<String, ArrayList<ExecutableElement>> methodMap = new LinkedHashMap<>(); enumerateMethods( element, elementUtils, typeUtils, element, methodMap ); return methodMap.values().stream().flatMap( Collection::stream ).collect( Collectors.toList() ); } private static void enumerateMethods( @Nonnull final TypeElement scope, @Nonnull final Elements elementUtils, @Nonnull final Types typeUtils, @Nonnull final TypeElement element, @Nonnull final Map<String, ArrayList<ExecutableElement>> methods ) { final TypeMirror superclass = element.getSuperclass(); if ( TypeKind.NONE != superclass.getKind() ) { final TypeElement superclassElement = (TypeElement) ( (DeclaredType) superclass ).asElement(); enumerateMethods( scope, elementUtils, typeUtils, superclassElement, methods ); } for ( final TypeMirror interfaceType : element.getInterfaces() ) { final TypeElement interfaceElement = (TypeElement) ( (DeclaredType) interfaceType ).asElement(); enumerateMethods( scope, elementUtils, typeUtils, interfaceElement, methods ); } for ( final Element member : element.getEnclosedElements() ) { if ( member.getKind() == ElementKind.METHOD ) { final ExecutableElement method = (ExecutableElement) member; processMethod( elementUtils, typeUtils, scope, methods, method ); } } } private static void processMethod( @Nonnull final Elements elementUtils, @Nonnull final Types typeUtils, @Nonnull final TypeElement typeElement, @Nonnull final Map<String, ArrayList<ExecutableElement>> methods, @Nonnull final ExecutableElement method ) { final ExecutableType methodType = (ExecutableType) typeUtils.asMemberOf( (DeclaredType) typeElement.asType(), method ); final String key = method.getSimpleName().toString(); final ArrayList<ExecutableElement> elements = methods.computeIfAbsent( key, k -> new ArrayList<>() ); boolean found = false; final int size = elements.size(); for ( int i = 0; i < size; i++ ) { final ExecutableElement executableElement = elements.get( i ); if ( method.equals( executableElement ) ) { found = true; break; } else if ( isSubsignature( typeUtils, typeElement, methodType, executableElement ) ) { if ( !isAbstractInterfaceMethod( method ) ) { elements.set( i, method ); } found = true; break; } else if ( elementUtils.overrides( method, executableElement, typeElement ) ) { elements.set( i, method ); found = true; break; } } if ( !found ) { elements.add( method ); } } private static boolean isAbstractInterfaceMethod( final @Nonnull ExecutableElement method ) { return method.getModifiers().contains( Modifier.ABSTRACT ) && ElementKind.INTERFACE == method.getEnclosingElement().getKind(); } private static boolean isSubsignature( @Nonnull final Types typeUtils, @Nonnull final TypeElement typeElement, @Nonnull final ExecutableType methodType, @Nonnull final ExecutableElement candidate ) { final ExecutableType candidateType = (ExecutableType) typeUtils.asMemberOf( (DeclaredType) typeElement.asType(), candidate ); final boolean isEqual = methodType.equals( candidateType ); final boolean isSubsignature = typeUtils.isSubsignature( methodType, candidateType ); return isSubsignature || isEqual; } @Nonnull static List<ExecutableElement> getConstructors( @Nonnull final TypeElement element ) { return element.getEnclosedElements().stream(). filter( m -> m.getKind() == ElementKind.CONSTRUCTOR ). map( m -> (ExecutableElement) m ). collect( Collectors.toList() ); } @Nullable static String deriveName( @Nonnull final ExecutableElement method, @Nonnull final Pattern pattern, @Nonnull final String name ) throws ProcessorException { if ( Constants.SENTINEL.equals( name ) ) { final String methodName = method.getSimpleName().toString(); final Matcher matcher = pattern.matcher( methodName ); if ( matcher.find() ) { final String candidate = matcher.group( 1 ); return firstCharacterToLowerCase( candidate ); } else { return null; } } else { return name; } } @Nonnull static String firstCharacterToLowerCase( @Nonnull final String name ) { return Character.toLowerCase( name.charAt( 0 ) ) + name.substring( 1 ); } static boolean hasNonnullAnnotation( @Nonnull final Element element ) { return AnnotationsUtil.hasAnnotationOfType( element, Constants.NONNULL_ANNOTATION_CLASSNAME ); } static boolean isDisposableTrackableRequired( @Nonnull final Element element ) { final VariableElement variableElement = (VariableElement) AnnotationsUtil.getAnnotationValue( element, Constants.COMPONENT_ANNOTATION_CLASSNAME, "disposeNotifier" ).getValue(); switch ( variableElement.getSimpleName().toString() ) { case "ENABLE": return true; case "DISABLE": return false; default: return !AnnotationsUtil.hasAnnotationOfType( element, Constants.SINGLETON_ANNOTATION_CLASSNAME ); } } }
package com.sometrik.framework; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import android.content.Context; import android.text.Editable; import android.text.TextWatcher; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; public class FWEditText extends EditText implements NativeCommandHandler { private FrameWork frame; private Date lastTypeTime; public FWEditText(FrameWork frameWork) { super(frameWork); this.frame = frameWork; LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); setLayoutParams(params); } public void addDelayedChangeListener(final int viewId){ addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable editable) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { lastTypeTime = new Date(); } @Override public void onTextChanged(final CharSequence text, int arg1, int arg2, int arg3) { System.out.println("BigEditText TextChanged"); // dispatch after done typing (1 sec after) Timer t = new Timer(); TimerTask tt = new TimerTask() { @Override public void run() { Date myRunTime = new Date(); System.out.println("BigEditText TextChanged run!"); if ((lastTypeTime.getTime() + 2000) <= myRunTime.getTime()) { post(new Runnable() { @Override public void run() { System.out.println("typing finished. Sending update"); System.out.println("update: " + text.toString()); // frame.textChangedEvent(System.currentTimeMillis() / 1000.0, viewId, text); } }); } else { System.out.println("Canceled"); } } }; t.schedule(tt, 2000); } }); } @Override public void addChild(View view) { System.out.println("FWEditText couldn't handle command"); } @Override public void addOption(int optionId, String text) { System.out.println("FWEditText couldn't handle command"); } @Override public void setValue(String v) { setText(v); } @Override public void setValue(int v) { System.out.println("FWEditText couldn't handle command"); } @Override public void setViewEnabled(Boolean enabled) { setEnabled(enabled); } @Override public void setStyle(String key, String value) { if (key.equals("weight")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); params.weight = Integer.parseInt(value); setLayoutParams(params); } else if (key.equals("width")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); if (value.equals("wrap-content")) { params.width = LinearLayout.LayoutParams.WRAP_CONTENT; } else if (value.equals("match-parent")) { params.width = LinearLayout.LayoutParams.MATCH_PARENT; } setLayoutParams(params); } else if (key.equals("height")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); if (value.equals("wrap-content")) { params.height = LinearLayout.LayoutParams.WRAP_CONTENT; } else if (value.equals("match-parent")) { params.height = LinearLayout.LayoutParams.MATCH_PARENT; } setLayoutParams(params); } else if (key.equals("gravity")) { LinearLayout.LayoutParams params = (LayoutParams) getLayoutParams(); params.weight = 1; if (value.equals("bottom")) { params.gravity = Gravity.BOTTOM; } else if (value.equals("top")) { params.gravity = Gravity.TOP; } else if (value.equals("left")) { params.gravity = Gravity.LEFT; } else if (value.equals("right")) { params.gravity = Gravity.RIGHT; } } else if (key.equals("minimun-width")) { setMinimumWidth(Integer.parseInt(value)); } } @Override public void setError(boolean hasError, String errorText) { setError(hasError ? errorText : null); } @Override public int getElementId() { return getId(); } @Override public void onScreenOrientationChange(boolean isLandscape) { // TODO Auto-generated method stub } @Override public void addData(String text, int row, int column, int sheet) { System.out.println("FWEditText couldn't handle command"); } @Override public void setViewVisibility(boolean visibility) { if (visibility){ this.setVisibility(VISIBLE); } else { this.setVisibility(INVISIBLE); } } @Override public void clear() { System.out.println("Clear on EditText"); this.setText(""); } @Override public void flush() { // TODO Auto-generated method stub } @Override public void addColumn(String text, int columnType) { // TODO Auto-generated method stub } @Override public void reshape(int value, int size) { // TODO Auto-generated method stub } @Override public void setImage(byte[] bytes) { // TODO Auto-generated method stub } @Override public void reshape(int size) { // TODO Auto-generated method stub } }
package me.vanpan.rctqqsdk; import android.app.Activity; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.webkit.URLUtil; import com.facebook.react.bridge.ActivityEventListener; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.BaseActivityEventListener; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.WritableMap; import com.facebook.react.views.imagehelper.ResourceDrawableIdHelper; import com.tencent.connect.common.Constants; import com.tencent.connect.share.QQShare; import com.tencent.connect.share.QzonePublish; import com.tencent.connect.share.QzoneShare; import com.tencent.open.GameAppOperation; import com.tencent.tauth.IUiListener; import com.tencent.tauth.Tencent; import com.tencent.tauth.UiError; import org.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; import static android.content.ContentValues.TAG; class ShareScene { public static final int QQ = 0; public static final int QQZone = 1; public static final int Favorite = 2; } public class QQSDK extends ReactContextBaseJavaModule { private static Tencent mTencent; private String appId; private String appName; private Promise mPromise; private static final String ACTIVITY_DOES_NOT_EXIST = "activity not found"; private static final String QQ_Client_NOT_INSYALLED_ERROR = "QQ client is not installed"; private static final String QQ_RESPONSE_ERROR = "QQ response is error"; private static final String QQ_CANCEL_BY_USER = "cancelled by user"; private static final String QZONE_SHARE_CANCEL = "QZone share is cancelled"; private static final String QQFAVORITES_CANCEL = "QQ Favorites is cancelled"; private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() { @Override public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent intent) { if (requestCode == Constants.REQUEST_API) { if (resultCode == Constants.REQUEST_LOGIN) { mTencent.onActivityResultData(requestCode, resultCode, intent, loginListener); } } if (requestCode == Constants.REQUEST_QQ_SHARE) { if (resultCode == Constants.ACTIVITY_OK) { mTencent.onActivityResultData(requestCode, resultCode, intent, qqShareListener); } } if (requestCode == Constants.REQUEST_QZONE_SHARE) { if (resultCode == Constants.ACTIVITY_OK) { mTencent.onActivityResultData(requestCode, resultCode, intent, qZoneShareListener); } } } }; public QQSDK(ReactApplicationContext reactContext) { super(reactContext); reactContext.addActivityEventListener(mActivityEventListener); appId = this.getAppID(reactContext); appName = this.getAppName(reactContext); if (null == mTencent) { mTencent = Tencent.createInstance(appId, reactContext); } } @Override public void initialize() { super.initialize(); } @Override public String getName() { return "QQSDK"; } @Override public void onCatalystInstanceDestroy() { super.onCatalystInstanceDestroy(); if (mTencent != null) { mTencent.releaseResource(); mTencent = null; } appId = null; appName = null; mPromise = null; } @ReactMethod public void checkClientInstalled(Promise promise) { Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } Boolean installed = mTencent.isSupportSSOLogin(currentActivity); if (installed) { promise.resolve(true); } else { promise.reject("404", QQ_Client_NOT_INSYALLED_ERROR); } } @ReactMethod public void logout(Promise promise) { Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } mTencent.logout(currentActivity); promise.resolve(true); } @ReactMethod public void ssoLogin(final Promise promise) { if (mTencent.isSessionValid()) { WritableMap map = Arguments.createMap(); map.putString("userid", mTencent.getOpenId()); map.putString("access_token", mTencent.getAccessToken()); map.putDouble("expires_time", mTencent.getExpiresIn()); promise.resolve(map); } else { final Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } Runnable runnable = new Runnable() { @Override public void run() { mPromise = promise; mTencent.login(currentActivity, "all", loginListener); } }; UiThreadUtil.runOnUiThread(runnable); } } @ReactMethod public void shareText(String text,int shareScene, final Promise promise) { final Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } mPromise = promise; final Bundle params = new Bundle(); switch (shareScene) { case ShareScene.QQ: promise.reject("500","AndroidQQ"); break; case ShareScene.Favorite: params.putInt(GameAppOperation.QQFAV_DATALINE_REQTYPE, GameAppOperation.QQFAV_DATALINE_TYPE_TEXT); params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, appName); params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION, text); params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName); Runnable favoritesRunnable = new Runnable() { @Override public void run() { mTencent.addToQQFavorites(currentActivity, params, addToQQFavoritesListener); } }; UiThreadUtil.runOnUiThread(favoritesRunnable); break; case ShareScene.QQZone: params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzonePublish.PUBLISH_TO_QZONE_TYPE_PUBLISHMOOD); params.putString(QzoneShare.SHARE_TO_QQ_TITLE, text); Runnable zoneRunnable = new Runnable() { @Override public void run() { mTencent.publishToQzone(currentActivity,params,qZoneShareListener); } }; UiThreadUtil.runOnUiThread(zoneRunnable); break; default: break; } } @ReactMethod public void shareImage(String image,String title, String description,int shareScene, final Promise promise) { final Activity currentActivity = getCurrentActivity(); Log.d("",image); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } mPromise = promise; image = processImage(image); final Bundle params = new Bundle(); switch (shareScene) { case ShareScene.QQ: params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE); params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,image); params.putString(QQShare.SHARE_TO_QQ_TITLE, title); params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description); Runnable qqRunnable = new Runnable() { @Override public void run() { mTencent.shareToQQ(currentActivity,params,qqShareListener); } }; UiThreadUtil.runOnUiThread(qqRunnable); break; case ShareScene.Favorite: ArrayList<String> imageUrls = new ArrayList<String>(); imageUrls.add(image); params.putInt(GameAppOperation.QQFAV_DATALINE_REQTYPE, GameAppOperation.QQFAV_DATALINE_TYPE_IMAGE_TEXT); params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, title); params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION, description); params.putString(GameAppOperation.QQFAV_DATALINE_IMAGEURL,image); params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName); params.putStringArrayList(GameAppOperation.QQFAV_DATALINE_FILEDATA,imageUrls); Runnable favoritesRunnable = new Runnable() { @Override public void run() { mTencent.addToQQFavorites(currentActivity, params, addToQQFavoritesListener); } }; UiThreadUtil.runOnUiThread(favoritesRunnable); break; case ShareScene.QQZone: params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE); params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,image); params.putString(QQShare.SHARE_TO_QQ_TITLE, title); params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description); params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN); Runnable zoneRunnable = new Runnable() { @Override public void run() { mTencent.shareToQQ(currentActivity,params,qqShareListener); } }; UiThreadUtil.runOnUiThread(zoneRunnable); break; default: break; } } @ReactMethod public void shareNews(String url,String image,String title, String description,int shareScene, final Promise promise) { final Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } mPromise = promise; final Bundle params = new Bundle(); switch (shareScene) { case ShareScene.QQ: params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT); if(image.startsWith("http: params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,image); } else { params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,processImage(image)); } params.putString(QQShare.SHARE_TO_QQ_TITLE, title); params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url); params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description); Runnable qqRunnable = new Runnable() { @Override public void run() { mTencent.shareToQQ(currentActivity,params,qqShareListener); } }; UiThreadUtil.runOnUiThread(qqRunnable); break; case ShareScene.Favorite: image = processImage(image); params.putInt(GameAppOperation.QQFAV_DATALINE_REQTYPE, GameAppOperation.QQFAV_DATALINE_TYPE_DEFAULT); params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, title); params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION,description); params.putString(GameAppOperation.QQFAV_DATALINE_IMAGEURL,image); params.putString(GameAppOperation.QQFAV_DATALINE_URL,url); params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName); Runnable favoritesRunnable = new Runnable() { @Override public void run() { mTencent.addToQQFavorites(currentActivity, params, addToQQFavoritesListener); } }; UiThreadUtil.runOnUiThread(favoritesRunnable); break; case ShareScene.QQZone: image = processImage(image); ArrayList<String> imageUrls = new ArrayList<String>(); imageUrls.add(image); params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT); params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title); params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY,description); params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,url); params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imageUrls); Runnable zoneRunnable = new Runnable() { @Override public void run() { mTencent.shareToQzone(currentActivity,params,qZoneShareListener); } }; UiThreadUtil.runOnUiThread(zoneRunnable); break; default: break; } } @ReactMethod public void shareAudio(String url,String flashUrl,String image,String title, String description,int shareScene, final Promise promise) { final Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } mPromise = promise; final Bundle params = new Bundle(); switch (shareScene) { case ShareScene.QQ: params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT); if(image.startsWith("http: params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,image); } else { params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL,processImage(image)); } params.putString(QQShare.SHARE_TO_QQ_AUDIO_URL, flashUrl); params.putString(QQShare.SHARE_TO_QQ_TITLE, title); params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url); params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description); Runnable qqRunnable = new Runnable() { @Override public void run() { mTencent.shareToQQ(currentActivity,params,qqShareListener); } }; UiThreadUtil.runOnUiThread(qqRunnable); break; case ShareScene.Favorite: image = processImage(image); params.putInt(GameAppOperation.QQFAV_DATALINE_REQTYPE, GameAppOperation.QQFAV_DATALINE_TYPE_DEFAULT); params.putString(GameAppOperation.QQFAV_DATALINE_TITLE, title); params.putString(GameAppOperation.QQFAV_DATALINE_DESCRIPTION,description); params.putString(GameAppOperation.QQFAV_DATALINE_IMAGEURL,image); params.putString(GameAppOperation.QQFAV_DATALINE_URL,url); params.putString(GameAppOperation.QQFAV_DATALINE_APPNAME, appName); params.putString(GameAppOperation.QQFAV_DATALINE_AUDIOURL,flashUrl); Runnable favoritesRunnable = new Runnable() { @Override public void run() { mTencent.addToQQFavorites(currentActivity, params, addToQQFavoritesListener); } }; UiThreadUtil.runOnUiThread(favoritesRunnable); break; case ShareScene.QQZone: image = processImage(image); ArrayList<String> imageUrls = new ArrayList<String>(); imageUrls.add(image); params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT); params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title); params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY,description); params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,url); params.putString(QzoneShare.SHARE_TO_QQ_AUDIO_URL,flashUrl); params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL,imageUrls); Runnable zoneRunnable = new Runnable() { @Override public void run() { mTencent.shareToQzone(currentActivity,params,qZoneShareListener); } }; UiThreadUtil.runOnUiThread(zoneRunnable); break; default: break; } } @ReactMethod public void shareVideo(String url,String flashUrl,String image,String title, String description,int shareScene, final Promise promise) { final Activity currentActivity = getCurrentActivity(); if (null == currentActivity) { promise.reject("405",ACTIVITY_DOES_NOT_EXIST); return; } mPromise = promise; final Bundle params = new Bundle(); switch (shareScene) { case ShareScene.QQ: promise.reject("500","AndroidQQ"); break; case ShareScene.Favorite: promise.reject("500","AndroidQQ"); break; case ShareScene.QQZone: ArrayList<String> imageUrls = new ArrayList<String>(); imageUrls.add(image); params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzonePublish.PUBLISH_TO_QZONE_TYPE_PUBLISHVIDEO); params.putString(QzonePublish.PUBLISH_TO_QZONE_IMAGE_URL, image); params.putString(QzonePublish.PUBLISH_TO_QZONE_SUMMARY,description); params.putString(QzonePublish.PUBLISH_TO_QZONE_VIDEO_PATH,flashUrl); Runnable zoneRunnable = new Runnable() { @Override public void run() { mTencent.shareToQzone(currentActivity,params,qZoneShareListener); } }; UiThreadUtil.runOnUiThread(zoneRunnable); break; default: break; } } @Nullable @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); constants.put("QQ", ShareScene.QQ); constants.put("QQZone", ShareScene.QQZone); constants.put("Favorite", ShareScene.Favorite); return constants; } /** * Tencent SDK App ID * @param reactContext * @return */ private String getAppID(ReactApplicationContext reactContext) { try { ApplicationInfo appInfo = reactContext.getPackageManager() .getApplicationInfo(reactContext.getPackageName(), PackageManager.GET_META_DATA); String key = appInfo.metaData.get("QQ_APP_ID").toString(); return key; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; } /** * * @param reactContext * @return */ private String getAppName(ReactApplicationContext reactContext) { PackageManager packageManager = reactContext.getPackageManager(); ApplicationInfo applicationInfo = null; try { applicationInfo = packageManager.getApplicationInfo(reactContext.getPackageName(), 0); } catch (final PackageManager.NameNotFoundException e) {} final String AppName = (String)((applicationInfo != null) ? packageManager.getApplicationLabel(applicationInfo) : "AppName"); return AppName; } private String processImage(String image) { if(URLUtil.isHttpUrl(image) || URLUtil.isHttpsUrl(image)) { return saveBitmapToFile(getBitmapFromURL(image)); } else if (isBase64(image)) { return saveBitmapToFile(decodeBase64ToBitmap(image)); } else if (URLUtil.isFileUrl(image) || image.startsWith("/") ){ File file = new File(image); return file.getAbsolutePath(); } else { return saveBitmapToFile(BitmapFactory.decodeResource(getReactApplicationContext().getResources(),getDrawableFileID(image))); } } /** * Base64 * @param image * @return */ private boolean isBase64(String image) { try { byte[] decodedString = Base64.decode(image, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); if (bitmap == null) { return false; } return true; } catch (Exception e) { return false; } } /** * DrawbleID * @param imageName * @return */ private int getDrawableFileID(String imageName) { ResourceDrawableIdHelper sResourceDrawableIdHelper = ResourceDrawableIdHelper.getInstance(); int id = sResourceDrawableIdHelper.getResourceDrawableId(getReactApplicationContext(),imageName); return id; } /** * URLBitmap * @param src * @return */ private static Bitmap getBitmapFromURL(String src) { try { URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(input); return bitmap; } catch (IOException e) { return null; } } /** * Base64Bitmap * @param Base64String * @return */ private Bitmap decodeBase64ToBitmap(String Base64String) { byte[] decode = Base64.decode(Base64String,Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length); return bitmap; } /** * bitmap * @param bitmap * @return */ private String saveBitmapToFile(Bitmap bitmap) { File pictureFile = getOutputMediaFile(); if (pictureFile == null) { return null; } try { FileOutputStream fos = new FileOutputStream(pictureFile); bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.close(); } catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); } return pictureFile.getAbsolutePath(); } /** * * @return */ private File getOutputMediaFile(){ File mediaStorageDir = getCurrentActivity().getExternalCacheDir(); if (! mediaStorageDir.exists()){ if (! mediaStorageDir.mkdirs()){ return null; } } String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date()); File mediaFile; String mImageName="RN_"+ timeStamp +".jpg"; mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName); return mediaFile; } /** * token openid * * @param jsonObject */ public static void initOpenidAndToken(JSONObject jsonObject) { try { String token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN); String expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN); String openId = jsonObject.getString(Constants.PARAM_OPEN_ID); if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) { mTencent.setAccessToken(token, expires); mTencent.setOpenId(openId); } } catch (Exception e) { } } IUiListener loginListener = new IUiListener() { @Override public void onComplete(Object response) { if (null == response) { mPromise.reject("600",QQ_RESPONSE_ERROR); return; } JSONObject jsonResponse = (JSONObject) response; if (null != jsonResponse && jsonResponse.length() == 0) { mPromise.reject("600",QQ_RESPONSE_ERROR); return; } initOpenidAndToken(jsonResponse); WritableMap map = Arguments.createMap(); map.putString("userid", mTencent.getOpenId()); map.putString("access_token", mTencent.getAccessToken()); map.putDouble("expires_time", mTencent.getExpiresIn()); mPromise.resolve(map); } @Override public void onError(UiError e) { mPromise.reject("600",e.errorMessage); } @Override public void onCancel() { mPromise.reject("603",QQ_CANCEL_BY_USER); } }; IUiListener qqShareListener = new IUiListener() { @Override public void onCancel() { mPromise.reject("503",QQ_CANCEL_BY_USER); } @Override public void onComplete(Object response) { mPromise.resolve(true); } @Override public void onError(UiError e) { mPromise.reject("500",e.errorMessage); } }; /** * QQZONE */ IUiListener qZoneShareListener = new IUiListener() { @Override public void onCancel() { mPromise.reject("503",QZONE_SHARE_CANCEL); } @Override public void onError(UiError e) { mPromise.reject("500",e.errorMessage); } @Override public void onComplete(Object response) { mPromise.resolve(true); } }; IUiListener addToQQFavoritesListener = new IUiListener() { @Override public void onCancel() { mPromise.reject("503",QQFAVORITES_CANCEL); } @Override public void onComplete(Object response) { mPromise.resolve(true); } @Override public void onError(UiError e) { mPromise.reject("500",e.errorMessage); } }; }
package com.mapzen.tangram; import com.mapzen.tangram.geometry.Geometry; import com.mapzen.tangram.geometry.Point; import com.mapzen.tangram.geometry.Polygon; import com.mapzen.tangram.geometry.Polyline; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * {@code MapData} is a named collection of drawable map features. */ public class MapData { String name; long pointer = 0; MapController map; List<String> geojson = new ArrayList<>(); List<Geometry> features = new ArrayList<>(); /** * Construct a collection of drawable map features. * @param name The name of the data collection. Once added to a map, features from this * {@code MapData} will be available from a data source with this name, just like a data source * specified in a scene file. */ public MapData(String name) { this.name = name; } /** * Get the name of this {@code MapData}. * @return The name. */ public String name() { return name; } /** * Add the features from this {@code MapData} to a map. * <p> * This {@code MapData} will be associated with the given map until {@link #removeFromMap()} * is called or until this method is called again. * @param map The {@code MapController} managing the destination map. */ public void addToMap(MapController map) { if (map == null) { throw new RuntimeException("MapData cannot be added to a null MapController"); } if (this.map != null) { removeFromMap(); } this.map = map; this.pointer = map.nativeAddDataSource(name); syncWithMap(); } /** * Remove this {@code MapData} from the map it is currently associated with. This must not be * called when this {@code MapData} is not associated with a map. */ public void removeFromMap() { if (map == null) { throw new RuntimeException("There is no associated map for this MapData"); } map.nativeRemoveDataSource(pointer); pointer = 0; map = null; } /** * Synchronize the features in this {@code MapData} with the map. * <p> * This method must be called after features are added or removed to update their * appearance in the map. This method must not be called when this {@code MapData} is not * associated with a map. */ public void syncWithMap() { if (map == null) { throw new RuntimeException("There is no associated map for this MapData"); } map.nativeClearDataSource(pointer); for (String data : geojson) { map.nativeAddGeoJson(pointer, data); } for (Geometry geometry : features) { map.nativeAddFeature(pointer, geometry.getCoordinateArray(), geometry.getRingArray(), geometry.getPropertyArray()); } } /** * Add a point feature to this collection. * @param point The coordinates of the feature. * @param properties The properties of the feature, used for filtering and styling according to * the scene file used by the map; may be null. * @return This object, for chaining. */ public MapData addPoint(LngLat point, Map<String, String> properties) { features.add(new Point(point, properties)); return this; } /** * Add a polyline feature to this collection. * @param polyline A list of coordinates that define the line segments of the feature. * @param properties The properties of the feature, used for filtering and styling according to * the scene file used by the map; may be null. * @return This object, for chaining. */ public MapData addPolyline(List<LngLat> polyline, Map<String, String> properties) { features.add(new Polyline(polyline, properties)); return this; } /** * Add a polygon feature to this collection. * @param polygon A list of rings describing the shape of the feature. Each * ring is a list of coordinates. The first ring is taken as the "exterior" of the polygon and * rings with opposite winding are considered "holes". * @param properties The properties of the feature, used for filtering and styling according to * the scene file used by the map; may be null. * @return This object, for chaining. */ public MapData addPolygon(List<List<LngLat>> polygon, Map<String, String> properties) { features.add(new Polygon(polygon, properties)); return this; } public MapData addGeoJson(String data) { geojson.add(data); return this; } /** * Remove all features from this collection. * @return This object, for chaining. */ public MapData clear() { geojson.clear(); features.clear(); return this; } }
/** * @author Mike Heath <heathma@ldschurch.org> */ public class Hybrid implements HttpRequestHandler { private FreeMarkerConfig freeMarkerConfig; private Map<String, SimpleJdbcTemplate> templates; private ExecutorService executorService; private final AtomicLong queueTime = new AtomicLong(); private final AtomicInteger queueCount = new AtomicInteger(); private final AtomicLong queryTime = new AtomicLong(); private final AtomicInteger queryCount = new AtomicInteger(); private final AtomicLong totalTime = new AtomicLong(); private final AtomicInteger timeCount = new AtomicInteger(); @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Configuration configuration = freeMarkerConfig.getConfiguration(); configuration.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER); final Template template = configuration.getTemplate("page.ftl"); final Writer writer = response.getWriter(); final Random random = new Random(); final Map<String, Object> root = new HashMap<String, Object>(); final int maxTime = 1247052675; int time = random.nextInt(maxTime); final String query = "select count(*) from access_log where time > " + time + " and time < " + (time + 10000) + ";"; final long start = System.currentTimeMillis(); Future<Integer> count1Future = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { long queryStart = System.currentTimeMillis(); queueTime.getAndAdd(queryStart - start); queueCount.incrementAndGet(); int count = templates.get("mysql_logs").queryForInt(query); queryTime.getAndAdd(System.currentTimeMillis() - queryStart); queryCount.incrementAndGet(); return count; } }); Future<Integer> count2Future = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { long queryStart = System.currentTimeMillis(); queueTime.getAndAdd(queryStart - start); queueCount.incrementAndGet(); int count = templates.get("pg_logs").queryForInt(query); queryTime.getAndAdd(System.currentTimeMillis() - queryStart); queryCount.incrementAndGet(); return count; } }); int[] numbers = {random.nextInt(40000), random.nextInt(40000), random.nextInt(40000), random.nextInt(40000), random.nextInt(40000)}; Future<List<List<Map<String, Object>>>> contacts1Future = executorService.submit(new Select5Callable(templates.get("mysql_contacts"), numbers)); Future<List<List<Map<String, Object>>>> contacts2Future = executorService.submit(new Select5Callable(templates.get("pg_contacts"), numbers)); try { root.put("count1", count1Future.get()); root.put("count2", count2Future.get()); root.put("contacts1", contacts1Future.get()); root.put("contacts2", contacts2Future.get()); totalTime.getAndAdd(System.currentTimeMillis() - start); timeCount.incrementAndGet(); response.setContentType("text/html"); template.process(root, writer); } catch (Throwable e) { e.printStackTrace(); throw new ServletException(e); } } public void setFreeMarkerConfig(FreeMarkerConfig freeMarkerConfig) { this.freeMarkerConfig = freeMarkerConfig; } public void setTemplates(Map<String, SimpleJdbcTemplate> templates) { this.templates = templates; } public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } private class Select5Callable implements Callable<List<List<Map<String, Object>>>> { private final SimpleJdbcTemplate jdbcTemplate; private final int[] numbers; private Select5Callable(SimpleJdbcTemplate jdbcTemplate, int[] numbers) { this.jdbcTemplate = jdbcTemplate; this.numbers = numbers; } @Override public List<List<Map<String, Object>>> call() throws Exception { List<List<Map<String, Object>>> contacts = new ArrayList<List<Map<String, Object>>>(); for (int i : numbers) { String query = "select name, phone from contacts where id = " + i + ";"; contacts.add(jdbcTemplate.queryForList(query)); } return contacts; } } public void dump() { System.out.println("Average queue time: " + ((double)queueTime.get() / queueCount.get())); System.out.println("Average query time: " + ((double)queryTime.get() / queryCount.get())); System.out.println("Average total time: " + ((double)totalTime.get() / timeCount.get())); queueTime.set(0); queryCount.set(0); queryTime.set(0); queryCount.set(0); totalTime.set(0); timeCount.set(0); } }
package net.fortuna.ical4j.util; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import net.fortuna.ical4j.model.property.Uid; public class UidGeneratorTest extends TestCase { private UidGenerator generator; /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { generator = new UidGenerator("1"); } /** * Test method for {@link net.fortuna.ical4j.util.UidGenerator#generateUid()}. */ public void testGenerateUid() throws InterruptedException { final List uids = new ArrayList(); Thread[] threads = new Thread[10]; for (int i = 0; i < 10; i++) { threads[i] = new Thread(new Runnable() { public void run() { for (int i = 0; i < 10; i++) { synchronized(uids) { uids.add(generator.generateUid()); } } } }); } for (int i = 0; i < 10; i++) { threads[i].start(); } for (int i = 0; i < 10; i++) { threads[i].join(); } for (int i = 0; i < uids.size(); i++) { Uid uid = (Uid) uids.get(i); for (int j = 0; j < uids.size(); j++) { if (j != i) { assertFalse(uid.equals(uids.get(j))); } } } } }
package aho.uozu.yakbox; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.SearchView; 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.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class LoadActivity extends AppCompatActivity { /** All recordings at the time this activity was created */ private List<String> mAllRecordings; /** Recordings to give to the ListView */ private List<String> mViewRecordings; private ArrayAdapter<String> mAdapter; private Storage mStorage; private static final String TAG = "Yakbox-Load"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_load); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setLogo(R.drawable.ic_launcher_sml); ActionBar ab = getSupportActionBar(); if (ab != null) { ab.setDisplayHomeAsUpEnabled(true); } mStorage = Storage.getInstance(this); try { mAllRecordings = mStorage.getSavedRecordingNames(); } catch (Storage.StorageUnavailableException e) { String msg = "Error: Can't access storage"; Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show(); mAllRecordings = new ArrayList<>(); } Collections.sort(mAllRecordings); mViewRecordings = new ArrayList<>(mAllRecordings); // Configure list view ListView mListView = (ListView) findViewById(R.id.list); mAdapter = new ArrayAdapter<>(this, R.layout.load_list_item, mViewRecordings); mListView.setAdapter(mAdapter); // short taps mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String recordingName = ((TextView) view).getText().toString(); Intent i = new Intent(); i.putExtra("name", recordingName); setResult(RESULT_OK, i); finish(); } }); // long taps mListView.setLongClickable(true); mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { showDeleteDialog(position); return true; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_load, menu); // configure search final MenuItem item = menu.findItem(R.id.action_search); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { filterViewList(newText); mAdapter.notifyDataSetChanged(); return true; } }); searchView.setOnCloseListener(new SearchView.OnCloseListener() { @Override public boolean onClose() { filterViewList(""); return false; } }); return true; } /** * Filter the view list for items containing the given pattern */ private void filterViewList(String pattern) { if (pattern.isEmpty()) { mViewRecordings.clear(); mViewRecordings.addAll(mAllRecordings); } else { mViewRecordings.clear(); for (String item : mAllRecordings) { if (item.contains(pattern)) { mViewRecordings.add(item); } } } } private void showDeleteDialog(final int itemIdx) { AlertDialog.Builder builder = new AlertDialog.Builder(this); String name = mAllRecordings.get(itemIdx); builder .setMessage(getString(R.string.delete_dialog_msg) + " " + name + "?") .setPositiveButton(R.string.delete_dialog_positive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { deleteRecording(itemIdx); } }) .setNegativeButton(R.string.delete_dialog_negative, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); builder.show(); } private void deleteRecording(int itemIdx) { String name = mAllRecordings.get(itemIdx); mAllRecordings.remove(itemIdx); mAdapter.notifyDataSetChanged(); try { mStorage.deleteRecording(name); } catch (IOException e) { Log.e(TAG, "Error deleting " + name, e); } } }
package akechi.projectl; import android.accounts.Account; import android.accounts.AccountManager; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.IBinder; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.ActionProvider; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.api.client.repackaged.com.google.common.base.Strings; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.List; import java.util.Map; import jp.michikusa.chitose.lingr.Events; public class HomeActivity extends AppCompatActivity implements CometService.OnCometEventListener, ViewPager.OnPageChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_home); final AccountManager manager= AccountManager.get(this); Account[] accounts= manager.getAccountsByType("com.lingr"); if(accounts.length <= 0) { manager.addAccount("com.lingr", "", null, null, this, null, null); this.finish(); return; } final AppContext appContext= (AppContext)this.getApplicationContext(); // restore state { final SharedPreferences prefs= this.getSharedPreferences("prefs", Context.MODE_PRIVATE); final String name= prefs.getString("account.name", ""); final String type= prefs.getString("account.type", ""); if(!Strings.isNullOrEmpty(name) && !Strings.isNullOrEmpty(type)) { final Account account= new Account(name, type); appContext.setAccount(account); } } if(savedInstanceState != null) { final Account account = savedInstanceState.getParcelable("account"); if(account != null) { appContext.setAccount(account); } } final Account account= appContext.getAccount(); final ViewPager pager= (ViewPager)this.findViewById(R.id.pager); pager.addOnPageChangeListener(this); pager.setAdapter(new SwipeSwitcher(this.getSupportFragmentManager())); if(account != null && !Strings.isNullOrEmpty(appContext.getRoomId(account))) { pager.setCurrentItem(SwipeSwitcher.POS_ROOM); } else { pager.setCurrentItem(SwipeSwitcher.POS_ROOM_LIST); } this.onPageSelected(pager.getCurrentItem()); final ActionBar bar= this.getSupportActionBar(); bar.setDisplayShowHomeEnabled(true); bar.setDisplayShowCustomEnabled(true); bar.setDisplayUseLogoEnabled(true); bar.setLogo(R.drawable.icon_logo); final LocalBroadcastManager lbMan= LocalBroadcastManager.getInstance(this.getApplicationContext()); { final IntentFilter ifilter= new IntentFilter(CometService.class.getCanonicalName()); final BroadcastReceiver receiver= new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { final Events events= (Events)intent.getSerializableExtra("events"); HomeActivity.this.onCometEvent(events); } }; lbMan.registerReceiver(receiver, ifilter); this.receivers.add(receiver); } { final IntentFilter ifilter= new IntentFilter(Event.RoomChange.ACTION); final BroadcastReceiver receiver= new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { final String roomId= intent.getStringExtra(Event.RoomChange.KEY_ROOM_ID); HomeActivity.this.onRoomSelected(roomId); } }; lbMan.registerReceiver(receiver, ifilter); this.receivers.add(receiver); } final Intent service= new Intent(this, CometService.class); this.startService(service); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageScrollStateChanged(int state) { } @Override public void onPageSelected(int position) { final TextView whenceView= (TextView)this.findViewById(R.id.whenceView); final AppContext appContext= (AppContext)this.getApplicationContext(); switch(position) { case SwipeSwitcher.POS_ROOM:{ final Account account= appContext.getAccount(); final String roomId= appContext.getRoomId(account); if(Iterables.size(appContext.getAccounts()) <= 1) { whenceView.setText(Strings.isNullOrEmpty(roomId) ? "You're not in the room" : "You're in " + roomId ); } else { whenceView.setText(Strings.isNullOrEmpty(roomId) ? String.format("You're %s, not in the room", account.name) : String.format("You're %s, in %s", account.name, roomId) ); } break; } case SwipeSwitcher.POS_ROOM_LIST:{ final Account account= appContext.getAccount(); whenceView.setText(String.format("Hi %s, choose a room", account.name)); break; } case SwipeSwitcher.POS_PREFERENCE:{ final Account account= appContext.getAccount(); whenceView.setText("Settings for " + account.name); break; } default: throw new AssertionError("Unknown page position: " + position); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch(keyCode) { // swipe to room list when back button press in the room case KeyEvent.KEYCODE_BACK:{ final ViewPager pager= (ViewPager)this.findViewById(R.id.pager); if(pager.getCurrentItem() == SwipeSwitcher.POS_ROOM) { pager.setCurrentItem(SwipeSwitcher.POS_ROOM_LIST, true); return true; } // fallthrough } default: return super.onKeyDown(keyCode, event); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Log.i("HomeActivity", "onSaveInstanceState()"); final AppContext appContext= (AppContext)this.getApplicationContext(); outState.putParcelable("account", appContext.getAccount()); } @Override protected void onPause() { super.onPause(); final AppContext appContext= (AppContext)this.getApplicationContext(); final SharedPreferences prefs= this.getSharedPreferences("prefs", Context.MODE_PRIVATE); final SharedPreferences.Editor editor= prefs.edit(); final Account account= appContext.getAccount(); if(account != null) { editor.putString("account.name", account.name); editor.putString("account.type", account.type); } editor.commit(); // this.unbindService(this.serviceConnection); // this.serviceConnection= null; } @Override protected void onDestroy() { super.onDestroy(); final LocalBroadcastManager lbMan= LocalBroadcastManager.getInstance(this.getApplicationContext()); for(final BroadcastReceiver receiver : this.receivers) { lbMan.unregisterReceiver(receiver); } this.receivers.clear(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // menu.add(Menu.NONE, MENU_ITEM_PREFERENCE, Menu.NONE, "Preference"); // Switch account final AppContext appContext= (AppContext)this.getApplicationContext(); final Iterable<Account> accounts= appContext.getAccounts(); if(Iterables.size(accounts) >= 1) { final SubMenu subMenu= menu.addSubMenu(Menu.NONE, Menu.NONE, Menu.NONE, "Switch account"); for(final Account account : accounts) { subMenu.add(Menu.NONE, MENU_ITEM_ACCOUNT, Menu.NONE, account.name); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case MENU_ITEM_PREFERENCE:{ return true; } case MENU_ITEM_ACCOUNT:{ final AppContext appContext= (AppContext)this.getApplicationContext(); final String accountName= item.getTitle().toString(); final Optional<Account> account= Iterables.tryFind(appContext.getAccounts(), new Predicate<Account>(){ @Override public boolean apply(Account input) { return input.name.equals(accountName); } }); if(!account.isPresent()) { Toast.makeText(this, "Did you remove an account? Try again", Toast.LENGTH_SHORT).show(); return true; } appContext.setAccount(account.get()); // choose current page { final ViewPager pager= (ViewPager)this.findViewById(R.id.pager); if(Strings.isNullOrEmpty(appContext.getRoomId(account.get()))) { pager.setCurrentItem(SwipeSwitcher.POS_ROOM_LIST); } else { pager.setCurrentItem(SwipeSwitcher.POS_ROOM); } this.onPageSelected(pager.getCurrentItem()); } // trigger event { final Intent intent= new Intent(Event.AccountChange.ACTION); intent.putExtra(Event.AccountChange.KEY_ACCOUNT, account.get()); final LocalBroadcastManager lbMan= LocalBroadcastManager.getInstance(this.getApplicationContext()); lbMan.sendBroadcast(intent); } return true; } } return false; } private void onRoomSelected(CharSequence roomId) { final AppContext appContext= (AppContext)this.getApplicationContext(); appContext.setRoomId(appContext.getAccount(), roomId); final ViewPager pager= (ViewPager)this.findViewById(R.id.pager); pager.setCurrentItem(SwipeSwitcher.POS_ROOM, true); } @Override public void onCometEvent(Events events) { Log.i("HomeActivity", "events = " + events); final ViewPager pager= (ViewPager)this.findViewById(R.id.pager); final SwipeSwitcher adapter= (SwipeSwitcher)pager.getAdapter(); final Fragment[] fragments= new Fragment[]{ adapter.getFragment(SwipeSwitcher.POS_ROOM_LIST), adapter.getFragment(SwipeSwitcher.POS_ROOM), }; for(final Fragment fragment : fragments) { if(fragment instanceof CometService.OnCometEventListener) { ((CometService.OnCometEventListener)fragment).onCometEvent(events); } } } public static final class SwipeSwitcher extends FragmentStatePagerAdapter { public static final int POS_ROOM_LIST= 0; public static final int POS_ROOM= 1; public static final int POS_PREFERENCE= 2; public static final int NPAGES= 3; public SwipeSwitcher(FragmentManager fm) { super(fm); } public Fragment getFragment(int position) { return this.getItem(position); } @Override public Fragment getItem(int position) { if(this.fragments.containsKey(position)) { return this.fragments.get(position); } switch(position) { case POS_ROOM_LIST:{ final Fragment fragment= new RoomListFragment(); this.fragments.put(position, fragment); return fragment; } case POS_ROOM:{ final Fragment fragment= new RoomFragment(); this.fragments.put(position, fragment); return fragment; } case POS_PREFERENCE:{ final Fragment fragment= new SettingsFragment(); this.fragments.put(position, fragment); return fragment; } default: throw new AssertionError(); } } @Override public int getCount() { return NPAGES; } private final Map<Integer, Fragment> fragments= Maps.newHashMap(); } private static final int MENU_ITEM_PREFERENCE= 1; private static final int MENU_ITEM_ACCOUNT= 2; private List<BroadcastReceiver> receivers= Lists.newLinkedList(); }
package br.com.lfdb.zup; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.HashSet; import java.util.List; import java.util.Set; import br.com.lfdb.zup.domain.CategoriaRelato; import br.com.lfdb.zup.service.CategoriaRelatoService; import br.com.lfdb.zup.util.ImageUtils; import butterknife.ButterKnife; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; public class TestActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); final Adapter adapter = new Adapter(); recyclerView.setAdapter(adapter); adapter.addAll(); findViewById(R.id.toggleAll).setOnClickListener(v -> { TextView text = (TextView) v.findViewById(R.id.textoTodos); ImageView icon = (ImageView) v.findViewById(R.id.iconeTodos); if (v.getTag() != null) { v.setTag(null); text.setText("Ativar todas as categorias"); icon.setImageResource(R.drawable.filtros_check_todascategorias_ativar); adapter.addAll(); } else { v.setTag(new Object()); text.setText("Desativar todas as categorias"); icon.setImageResource(R.drawable.filtros_check_todascategorias_desativar); adapter.removeAll(); } }); } public Activity getContext() { return this; } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> { private final List<CategoriaRelato> categories; private final Set<Long> expanded = new HashSet<>(); private final Set<CategoriaRelato> selecionadas = new HashSet<>(); public Adapter() { categories = new CategoriaRelatoService().getCategorias(getContext()); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int type) { return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_expandable_category, parent, false)); } public void addAll() { for (int i = 0; i < categories.size(); i++) { selecionadas.add(categories.get(i)); selecionadas.addAll(categories.get(i).getSubcategorias()); } notifyDataSetChanged(); } public void removeAll() { selecionadas.clear(); notifyDataSetChanged(); } @Override public void onBindViewHolder(ViewHolder holder, int position) { final CategoriaRelato categoria = categories.get(position); holder.imagem.setImageBitmap(ImageUtils.getScaledCustom(getContext(), "reports", selecionadas.contains(categoria) ? categoria.getIconeAtivo() : categoria.getIconeInativo(), 0.75f)); holder.nomeCategoria.setText(categoria.getNome()); holder.nomeCategoria.setCompoundDrawablesWithIntrinsicBounds(0, 0, selecionadas.contains(categoria) ? R.drawable.filtros_check_categoria : 0, 0); holder.expander.setOnClickListener(v -> { switchState(categoria.getId()); checkExpanded(categoria, holder); }); holder.nomeCategoria.setOnClickListener(v -> { if (selecionadas.contains(categoria)) { selecionadas.remove(categoria); selecionadas.removeAll(categoria.getSubcategorias()); } else { selecionadas.add(categoria); selecionadas.addAll(categoria.getSubcategorias()); } checkExpanded(categoria, holder); holder.nomeCategoria.setCompoundDrawablesWithIntrinsicBounds(0, 0, selecionadas.contains(categoria) ? R.drawable.filtros_check_categoria : 0, 0); holder.imagem.setImageBitmap(ImageUtils.getScaledCustom(getContext(), "reports", selecionadas.contains(categoria) ? categoria.getIconeAtivo() : categoria.getIconeInativo(), 0.75f)); }); checkExpanded(categoria, holder); } protected void checkExpanded(CategoriaRelato categoria, ViewHolder holder) { if (holder.subcategorias.getChildCount() > 0) holder.subcategorias.removeAllViews(); if (expanded.contains(categoria.getId())) { holder.expander.setText("Ocultar subcategorias"); holder.subcategorias.setVisibility(View.VISIBLE); for (CategoriaRelato subcategory : categoria.getSubcategorias()) addSubcategoria(subcategory, holder.subcategorias); } else { holder.expander.setText("Ver subcategorias"); holder.subcategorias.setVisibility(View.GONE); } } private void addSubcategoria(CategoriaRelato subcategory, ViewGroup parent) { View view = getLayoutInflater().inflate(R.layout.item_subcategoria, parent, false); view.setTag(subcategory); final TextView nome = ButterKnife.findById(view, R.id.nome); nome.setCompoundDrawablesWithIntrinsicBounds(0, 0, selecionadas.contains(subcategory) ? R.drawable.filtros_check_categoria : 0, 0); nome.setText(subcategory.getNome()); view.setOnClickListener(v -> { if (selecionadas.contains(subcategory)) { selecionadas.remove(subcategory); } else { selecionadas.add(subcategory); } nome.setCompoundDrawablesWithIntrinsicBounds(0, 0, selecionadas.contains(subcategory) ? R.drawable.filtros_check_categoria : 0, 0); }); parent.addView(view); } protected void switchState(long id) { if (expanded.contains(id)) expanded.remove(id); else expanded.add(id); } @Override public int getItemCount() { return categories.size(); } public class ViewHolder extends RecyclerView.ViewHolder { ImageView imagem; ViewGroup subcategorias; TextView nomeCategoria; TextView expander; public ViewHolder(View view) { super(view); imagem = ButterKnife.findById(view, R.id.imagemCategoria); subcategorias = ButterKnife.findById(view, R.id.subcategorias); nomeCategoria = ButterKnife.findById(view, R.id.nomeCategoria); expander = ButterKnife.findById(view, R.id.expander); } } } }
package co.ello.ElloApp; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.ComponentCallbacks2; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.drawable.ColorDrawable; import android.Manifest; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.WindowManager; import android.webkit.ValueCallback; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import com.nispok.snackbar.Snackbar; import com.nispok.snackbar.SnackbarManager; import com.nispok.snackbar.enums.SnackbarType; import com.nispok.snackbar.listeners.ActionClickListener; import com.squareup.picasso.Picasso; import org.xwalk.core.JavascriptInterface; import org.xwalk.core.XWalkActivity; import org.xwalk.core.XWalkPreferences; import org.xwalk.core.XWalkResourceClient; import org.xwalk.core.XWalkUIClient; import org.xwalk.core.XWalkView; import java.io.File; import java.util.Date; import javax.inject.Inject; import co.ello.ElloApp.Dagger.ElloApp; import co.ello.ElloApp.PushNotifications.RegistrationIntentService; // Using a 3rd party Snackbar because we can't extend // AppCompatActivity, thanks a lot XWalkActivity public class MainActivity extends XWalkActivity implements SwipeRefreshLayout.OnRefreshListener { private final static String TAG = MainActivity.class.getSimpleName(); private final static int MY_PERMISSIONS_REQUEST_CAMERA = 333; @Inject protected Reachability reachability; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; public static Boolean inBackground = true; public XWalkView xWalkView; private ElloUIClient xWalkClient; private SwipeRefreshLayout swipeLayout; public String path = "https://ello.co"; private ProgressDialog progress; private Boolean shouldReload = false; private Boolean webAppReady = false; private Boolean isDeepLink = false; private BroadcastReceiver registerDeviceReceiver; private BroadcastReceiver pushReceivedReceiver; private BroadcastReceiver imageResizeReceiver; private Boolean isXWalkReady = false; private Intent imageSelectedIntent; private Date lastReloaded; TmpTarget target; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); lastReloaded = new Date(); ((ElloApp) getApplication()).getNetComponent().inject(this); setContentView(R.layout.activity_main); swipeLayout = (SwipeRefreshLayout) findViewById(R.id.container); swipeLayout.setOnRefreshListener(this); setupWebView(); setupRegisterDeviceReceiver(); setupPushReceivedReceiver(); setupImageResizeReceiver(); } protected void onXWalkReady() { isXWalkReady = true; xWalkView.getSettings().setUserAgentString(userAgentString()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)){ XWalkPreferences.setValue(XWalkPreferences.REMOTE_DEBUGGING, true); } } xWalkView.addJavascriptInterface(this, "AndroidInterface"); displayScreenContent(); deepLinkWhenPresent(); } @Override public void onRefresh() { if(!reachability.isNetworkConnected()) { displayScreenContent(); } if(isXWalkReady) { reloadXWalk(); progress.show(); } swipeLayout.setRefreshing(false); } @Override protected void onStop() { super.onStop(); inBackground = true; } @Override protected void onResume() { super.onResume(); if(shouldHardRefresh()) { shouldReload = true; } inBackground = false; if(isXWalkReady) { xWalkView.resumeTimers(); xWalkView.onShow(); registerForGCM(); } if(!reachability.isNetworkConnected() || xWalkView == null) { displayScreenContent(); } else if(shouldReload && isXWalkReady) { shouldReload = false; reloadXWalk(); } deepLinkWhenPresent(); } private boolean shouldHardRefresh() { Date now = new Date(); Date thirtyMinutesFromLastReloaded = new Date(lastReloaded.getTime() + (30 * 60 * 1000)); return now.compareTo(thirtyMinutesFromLastReloaded) == 0; } private void reloadXWalk() { lastReloaded = new Date(); xWalkView.reload(XWalkView.RELOAD_IGNORE_CACHE); } protected boolean cameraGranted() { return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED; } protected boolean writeExternalGranted() { return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; } protected boolean checkPermissions() { if (!cameraGranted() || !writeExternalGranted()) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_CAMERA); } else { return true; } return false; } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_CAMERA: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { xWalkClient.openFileChooser(); } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) { if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CAMERA)) { Alert.showCameraDenied(MainActivity.this); } else { Alert.showCameraDenied(MainActivity.this); } } } return; } } } @Override protected void onPause() { if (isXWalkReady) { xWalkView.pauseTimers(); xWalkView.onHide(); } super.onPause(); } @Override protected void onDestroy() { xWalkView.onDestroy(); if (registerDeviceReceiver != null) { unregisterReceiver(registerDeviceReceiver); } if (pushReceivedReceiver != null) { unregisterReceiver(pushReceivedReceiver); } if (imageResizeReceiver != null) { unregisterReceiver(imageResizeReceiver); } super.onDestroy(); } @Override public void onTrimMemory(int level) { super.onTrimMemory(level); if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) { shouldReload = true; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { target = new TmpTarget(this, "tmp.jpg"); if (intent != null && intent.getData() != null) { Uri imageURI = intent.getData(); File bitmap = new File(imageURI.toString()); imageSelectedIntent = intent; Picasso.with(MainActivity.this) .load(imageURI) .resize(1200, 3600) .centerInside() .onlyScaleDown() .into(target); } else { xWalkView.onActivityResult(requestCode, resultCode, intent); } } @Override protected void onNewIntent(Intent intent) { Uri data = intent.getData(); if (data != null) { path = data.toString(); isDeepLink = true; } if (isXWalkReady) { xWalkView.onNewIntent(intent); } } @JavascriptInterface public void webAppLoaded() { webAppReady = true; if (progress != null) { progress.dismiss(); } registerForGCM(); } private void setupRegisterDeviceReceiver() { registerDeviceReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String reg_id = intent.getExtras().getString("GCM_REG_ID"); String registerFunctionCall = "javascript:registerAndroidNotifications(\"" + reg_id + "\", \"" + packageName() + "\", \"" + versionName() + "\", \"" + versionCode() + "\")"; if(reg_id != null) { xWalkView.load(registerFunctionCall, null); } } }; registerReceiver(registerDeviceReceiver, new IntentFilter(ElloPreferences.REGISTRATION_COMPLETE)); } private void setupImageResizeReceiver() { imageResizeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String path = intent.getExtras().getString("RESIZED_IMAGE_PATH"); if(imageSelectedIntent != null && path != null) { Uri resizedURI = Uri.parse(path); if(resizedURI != null) { imageSelectedIntent.setData(resizedURI); xWalkView.onActivityResult(1, -1, imageSelectedIntent); } } imageSelectedIntent = null; } }; registerReceiver(imageResizeReceiver, new IntentFilter(ElloPreferences.IMAGE_RESIZED)); } private void setupPushReceivedReceiver() { pushReceivedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String title = intent.getExtras().getString("title"); String body = intent.getExtras().getString("body"); final String webUrl = intent.getExtras().getString("web_url"); if (title != null && body != null && webUrl != null ) { // Using a 3rd party Snackbar because we can't extend // AppCompatActivity, thanks a lot XWalkActivity Snackbar snackbar = Snackbar.with(context) .type(SnackbarType.MULTI_LINE) .text(title + " " + body) .actionLabel(R.string.view) .actionListener(new ActionClickListener() { @Override public void onActionClicked(Snackbar snackbar) { MainActivity.this.xWalkView.load(webUrl, null); } }); SnackbarManager.show(snackbar); } } }; registerReceiver(pushReceivedReceiver, new IntentFilter(ElloPreferences.PUSH_RECEIVED)); } private void deepLinkWhenPresent(){ if (progress == null) { progress = createProgressDialog(MainActivity.this); } Uri data = getIntent().getData(); Intent get = getIntent(); String webUrl = get.getStringExtra("web_url"); if (isXWalkReady && webUrl != null) { path = webUrl; loadPage(path); } else if (isXWalkReady && data != null) { path = data.toString(); getIntent().setData(null); loadPage(path); } else if (isXWalkReady && isDeepLink) { isDeepLink = false; loadPage(path); } } private void loadPage(String page) { xWalkView.load(page, null); progress.show(); } private void displayScreenContent() { if(reachability.isNetworkConnected()) { loadPage(path); } else { setupNoInternetView(); } } private void setupNoInternetView() { Intent intent = new Intent(this, NoInternetActivity.class); startActivity(intent); finish(); } private void setupWebView() { xWalkView = (XWalkView) findViewById(R.id.activity_main_webview); xWalkView.setResourceClient(new ElloResourceClient(xWalkView)); xWalkClient = new ElloUIClient(xWalkView); xWalkView.setUIClient(xWalkClient); } private String versionName() { PackageInfo pInfo; String versionName = ""; try { pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); versionName = pInfo.versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return versionName; } private String versionCode() { PackageInfo pInfo; String versionCode = ""; try { pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); versionCode = Integer.valueOf(pInfo.versionCode).toString(); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return versionCode; } private String packageName() { PackageInfo pInfo; String packageName = ""; try { pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); packageName = pInfo.packageName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return packageName; } private String userAgentString() { return xWalkView.getSettings().getUserAgentString() + " Ello Android/" + versionName() + " (" + versionCode() + ")"; } private ProgressDialog createProgressDialog(Context mContext) { ProgressDialog dialog = new ProgressDialog(mContext); try { dialog.show(); } catch (WindowManager.BadTokenException e) {} dialog.setCancelable(false); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); dialog.setContentView(R.layout.progress_dialog); return dialog; } private boolean checkPlayServices() { GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance(); int resultCode = apiAvailability.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (apiAvailability.isUserResolvableError(resultCode)) { apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST) .show(); } else { Log.i(TAG, "This device is not supported."); finish(); } return false; } return true; } private void registerForGCM() { if (checkPlayServices() && webAppReady) { Intent intent = new Intent(this, RegistrationIntentService.class); startService(intent); } } class ElloResourceClient extends XWalkResourceClient { public ElloResourceClient(XWalkView xwalkView) { super(xwalkView); } @Override public boolean shouldOverrideUrlLoading(XWalkView view, String url) { if (ElloURI.shouldLoadInApp(url)) { return false; } else { MainActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } } } class ElloUIClient extends XWalkUIClient { public ElloUIClient(XWalkView xwalkView) { super(xwalkView); } private XWalkView view; private ValueCallback<Uri> uploadMsg; private String acceptType; private String capture; @Override public void openFileChooser( XWalkView view, ValueCallback<Uri> uploadMsg, String acceptType, String capture) { boolean hasPermission = checkPermissions(); if(hasPermission) { super.openFileChooser(view, uploadMsg, acceptType, capture); } else { this.view = view; this.uploadMsg = uploadMsg; this.acceptType = acceptType; this.capture = capture; } } public void openFileChooser() { this.openFileChooser(this.view, this.uploadMsg, this.acceptType, this.capture); } } }
package com.marverenic.music; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.util.SparseIntArray; import android.view.View; import com.crashlytics.android.Crashlytics; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.marverenic.music.instances.Album; import com.marverenic.music.instances.Artist; import com.marverenic.music.instances.AutoPlaylist; import com.marverenic.music.instances.Genre; import com.marverenic.music.instances.Playlist; import com.marverenic.music.instances.Song; import com.marverenic.music.utils.Themes; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.Properties; public class Library { public static final String PLAY_COUNT_FILENAME = ".playcount"; public static final String PLAY_COUNT_FILE_COMMENT = "This file contains play count information for Jockey and should not be edited"; public static final int PERMISSION_REQUEST_ID = 0x01; private static final String AUTO_PLAYLIST_EXTENSION = ".jpl"; private static final ArrayList<Playlist> playlistLib = new ArrayList<>(); private static final ArrayList<Song> songLib = new ArrayList<>(); private static final ArrayList<Artist> artistLib = new ArrayList<>(); private static final ArrayList<Album> albumLib = new ArrayList<>(); private static final ArrayList<Genre> genreLib = new ArrayList<>(); private static final SparseIntArray playCounts = new SparseIntArray(); private static final SparseIntArray skipCounts = new SparseIntArray(); private static final SparseIntArray playDates = new SparseIntArray(); private static final String[] songProjection = new String[]{ MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.YEAR, MediaStore.Audio.Media.DATE_ADDED, MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.TRACK }; private static final String[] artistProjection = new String[]{ MediaStore.Audio.Artists._ID, MediaStore.Audio.Artists.ARTIST, }; private static final String[] albumProjection = new String[]{ MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Albums.ARTIST, MediaStore.Audio.Albums.LAST_YEAR, MediaStore.Audio.Albums.ALBUM_ART }; private static final String[] playlistProjection = new String[]{ MediaStore.Audio.Playlists._ID, MediaStore.Audio.Playlists.NAME }; private static final String[] genreProjection = new String[]{ MediaStore.Audio.Genres._ID, MediaStore.Audio.Genres.NAME }; private static final String[] playlistEntryProjection = new String[]{ MediaStore.Audio.Playlists.Members.TITLE, MediaStore.Audio.Playlists.Members.AUDIO_ID, MediaStore.Audio.Playlists.Members.ARTIST, MediaStore.Audio.Playlists.Members.ALBUM, MediaStore.Audio.Playlists.Members.DURATION, MediaStore.Audio.Playlists.Members.DATA, MediaStore.Audio.Playlists.Members.YEAR, MediaStore.Audio.Playlists.Members.DATE_ADDED, MediaStore.Audio.Playlists.Members.ALBUM_ID, MediaStore.Audio.Playlists.Members.ARTIST_ID }; // LIBRARY LISTENERS // Since it's important to know when the Library has entries added or removed so we can update // the UI accordingly, associate listeners to receive callbacks for such events. These listeners // will get called only when entries are added or removed -- not changed. This lets us do a lot // of things on the UI like adding and removing playlists without having to create the associated // Snackbars, AlertDialogs, etc. and is slightly cleaner than passing a callback as a parameter // to methods that cause such changes since we don't have to instantiate a single-use Object. private static final ArrayList<PlaylistChangeListener> PLAYLIST_LISTENERS = new ArrayList<>(); private static final ArrayList<LibraryRefreshListener> REFRESH_LISTENERS = new ArrayList<>(); public interface PlaylistChangeListener { void onPlaylistRemoved(Playlist removed); void onPlaylistAdded(Playlist added); } public interface LibraryRefreshListener { void onLibraryRefreshed(); } /** * In certain cases like in {@link com.marverenic.music.fragments.PlaylistFragment}, editing the * library can break a lot of things if not done carefully. (i.e. if * {@link android.support.v7.widget.RecyclerView.Adapter#notifyDataSetChanged()} (or similar) * isn't called after adding a playlist, then the UI process can throw an exception and crash) * * If this is the case, call this method to set a callback whenever the library gets updated * (Not all library update calls will be relevant to the context, but better safe than sorry). * * <b>When using this method MAKE SURE TO CALL {@link Library#removePlaylistListener(PlaylistChangeListener)} * WHEN THE ACTIVITY PAUSES -- OTHERWISE YOU WILL CAUSE A LEAK.</b> * * @param listener A {@link PlaylistChangeListener} to act as a callback * when the library is changed in any way */ public static void addPlaylistListener(PlaylistChangeListener listener){ if (!PLAYLIST_LISTENERS.contains(listener)) PLAYLIST_LISTENERS.add(listener); } public static void addRefreshListener(LibraryRefreshListener listener) { if (!REFRESH_LISTENERS.contains(listener)) REFRESH_LISTENERS.add(listener); } /** * Remove a {@link PlaylistChangeListener} previously added to listen * for library updates. * @param listener A {@link PlaylistChangeListener} currently registered * to recieve a callback when the library gets modified. If it's not already * registered, then nothing will happen. */ public static void removePlaylistListener(PlaylistChangeListener listener){ if (PLAYLIST_LISTENERS.contains(listener)) PLAYLIST_LISTENERS.remove(listener); } public static void removeRefreshListener(LibraryRefreshListener listener) { REFRESH_LISTENERS.remove(listener); } /** * Private method for notifying registered {@link PlaylistChangeListener}s * that the library has lost an entry. (Changing entries doesn't matter) */ private static void notifyPlaylistRemoved(Playlist removed){ for (PlaylistChangeListener l : PLAYLIST_LISTENERS) l.onPlaylistRemoved(removed); } /** * Private method for notifying registered {@link PlaylistChangeListener}s * that the library has gained an entry. (Changing entries doesn't matter) */ private static void notifyPlaylistAdded(Playlist added){ for (PlaylistChangeListener l : PLAYLIST_LISTENERS) l.onPlaylistAdded(added); } private static void notifyLibraryRefreshed() { for (LibraryRefreshListener l : REFRESH_LISTENERS) l.onLibraryRefreshed(); } @TargetApi(23) public static boolean hasRWPermission(Context context){ return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; } @TargetApi(23) public static void requestRWPermission(Activity activity){ activity.requestPermissions( new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }, PERMISSION_REQUEST_ID); } // LIBRARY BUILDING METHODS public static void scanAll (final Activity activity){ if (hasRWPermission(activity)) { resetAll(); setPlaylistLib(scanPlaylists(activity)); setSongLib(scanSongs(activity)); setArtistLib(scanArtists(activity)); setAlbumLib(scanAlbums(activity)); setGenreLib(scanGenres(activity)); sort(); notifyLibraryRefreshed(); } else{ requestRWPermission(activity); } } /** * Scans the MediaStore for songs * @param context {@link Context} to use to open a {@link Cursor} * @return An {@link ArrayList} with the {@link Song}s in the MediaStore */ public static ArrayList<Song> scanSongs (Context context){ ArrayList<Song> songs = new ArrayList<>(); Cursor cur = context.getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, songProjection, MediaStore.Audio.Media.IS_MUSIC + "!= 0", null, MediaStore.Audio.Media.TITLE + " ASC"); if (cur == null) { throw new RuntimeException("Content resolver query returned null"); } for (int i = 0; i < cur.getCount(); i++) { cur.moveToPosition(i); Song s = new Song( cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media._ID)), (cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST)).equals(MediaStore.UNKNOWN_STRING)) ? context.getString(R.string.no_artist) : cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DURATION)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.YEAR)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID))); s.trackNumber = cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.TRACK)); songs.add(s); } cur.close(); return songs; } /** * Scans the MediaStore for artists * @param context {@link Context} to use to open a {@link Cursor} * @return An {@link ArrayList} with the {@link Artist}s in the MediaStore */ public static ArrayList<Artist> scanArtists (Context context){ ArrayList<Artist> artists = new ArrayList<>(); Cursor cur = context.getContentResolver().query( MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, artistProjection, null, null, MediaStore.Audio.Artists.ARTIST + " ASC"); if (cur == null) { throw new RuntimeException("Content resolver query returned null"); } for (int i = 0; i < cur.getCount(); i++) { cur.moveToPosition(i); if (!cur.getString(cur.getColumnIndex(MediaStore.Audio.Artists.ARTIST)).equals(MediaStore.UNKNOWN_STRING)) { artists.add(new Artist( cur.getInt(cur.getColumnIndex(MediaStore.Audio.Artists._ID)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Artists.ARTIST)))); } else{ artists.add(new Artist( cur.getInt(cur.getColumnIndex(MediaStore.Audio.Artists._ID)), context.getString(R.string.no_artist))); } } cur.close(); return artists; } /** * Scans the MediaStore for albums * @param context {@link Context} to use to open a {@link Cursor} * @return An {@link ArrayList} with the {@link Album}s in the MediaStore */ public static ArrayList<Album> scanAlbums (Context context){ ArrayList<Album> albums = new ArrayList<>(); Cursor cur = context.getContentResolver().query( MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumProjection, null, null, MediaStore.Audio.Albums.ALBUM + " ASC"); if (cur == null) { throw new RuntimeException("Content resolver query returned null"); } for (int i = 0; i < cur.getCount(); i++) { cur.moveToPosition(i); albums.add(new Album( cur.getInt(cur.getColumnIndex(MediaStore.Audio.Albums._ID)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ALBUM)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)), (cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)).equals(MediaStore.UNKNOWN_STRING)) ? context.getString(R.string.no_artist) : cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.LAST_YEAR)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART)))); } cur.close(); return albums; } /** * Scans the MediaStore for playlists * @param context {@link Context} to use to open a {@link Cursor} * @return An {@link ArrayList} with the {@link Playlist}s in the MediaStore */ public static ArrayList<Playlist> scanPlaylists (Context context){ ArrayList<Playlist> playlists = new ArrayList<>(); Cursor cur = context.getContentResolver().query( MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, playlistProjection, null, null, MediaStore.Audio.Playlists.NAME + " ASC"); if (cur == null) { throw new RuntimeException("Content resolver query returned null"); } for (int i = 0; i < cur.getCount(); i++) { cur.moveToPosition(i); playlists.add(new Playlist( cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists._ID)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.NAME)))); } cur.close(); for (Playlist p : scanAutoPlaylists(context)) { if (playlists.remove(p)) { playlists.add(p); } else { // If AutoPlaylists have been deleted outside of Jockey, delete its configuration //noinspection ResultOfMethodCallIgnored new File(context.getExternalFilesDir(null) + "/" + p.playlistName + AUTO_PLAYLIST_EXTENSION) .delete(); } } return playlists; } /** * Scans storage for Auto Playlist configurations * @param context {@link Context} to use to read files on the device * @return An {@link ArrayList} with the loaded {@link AutoPlaylist}s */ public static ArrayList<AutoPlaylist> scanAutoPlaylists (Context context) { ArrayList<AutoPlaylist> autoPlaylists = new ArrayList<>(); final Gson gson = new Gson(); try { File externalFiles = new File(context.getExternalFilesDir(null) + "/"); if (!externalFiles.exists()) { //noinspection ResultOfMethodCallIgnored externalFiles.mkdirs(); } String[] files = externalFiles.list(); for (String s : files) { if (s.endsWith(AUTO_PLAYLIST_EXTENSION)) { autoPlaylists.add(gson.fromJson(new FileReader(externalFiles + "/" + s), AutoPlaylist.class)); } } } catch (IOException e) { Crashlytics.logException(e); } return autoPlaylists; } /** * Scans the MediaStore for genres * @param context {@link Context} to use to open a {@link Cursor} * @return An {@link ArrayList} with the {@link Genre}s in the MediaStore */ public static ArrayList<Genre> scanGenres (Context context){ ArrayList<Genre> genres = new ArrayList<>(); Cursor cur = context.getContentResolver().query( MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, genreProjection, null, null, MediaStore.Audio.Genres.NAME + " ASC"); if (cur == null) { throw new RuntimeException("Content resolver query returned null"); } for (int i = 0; i < cur.getCount(); i++) { cur.moveToPosition(i); int thisGenreId = cur.getInt(cur.getColumnIndex(MediaStore.Audio.Genres._ID)); if (cur.getString(cur.getColumnIndex(MediaStore.Audio.Genres.NAME)).equalsIgnoreCase("Unknown")){ genres.add(new Genre(-1, context.getString(R.string.unknown))); } else { genres.add(new Genre( thisGenreId, cur.getString(cur.getColumnIndex(MediaStore.Audio.Genres.NAME)))); // Associate all songs in this genre by setting the genreID field of each song in the genre Cursor genreCur = context.getContentResolver().query( MediaStore.Audio.Genres.Members.getContentUri("external", thisGenreId), new String[]{MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + " != 0 ", null, null); if (genreCur == null) { throw new RuntimeException("Content resolver query returned null"); } genreCur.moveToFirst(); final int ID_INDEX = genreCur.getColumnIndex(MediaStore.Audio.Media._ID); for (int j = 0; j < genreCur.getCount(); j++) { genreCur.moveToPosition(j); final Song s = findSongById(genreCur.getInt(ID_INDEX)); if (s != null) s.genreId = thisGenreId; } genreCur.close(); } } cur.close(); return genres; } // LIBRARY STORAGE METHODS /** * Remove all library entries from memory */ public static void resetAll(){ playlistLib.clear(); songLib.clear(); artistLib.clear(); albumLib.clear(); genreLib.clear(); } /** * Replace the playlist library in memory with another one * @param newLib The new playlist library */ public static void setPlaylistLib(ArrayList<Playlist> newLib){ playlistLib.clear(); playlistLib.addAll(newLib); } /** * Replace the song library in memory with another one * @param newLib The new song library */ public static void setSongLib(ArrayList<Song> newLib){ songLib.clear(); songLib.addAll(newLib); } /** * Replace the album library in memory with another one * @param newLib The new album library */ public static void setAlbumLib(ArrayList<Album> newLib){ albumLib.clear(); albumLib.addAll(newLib); } /** * Replace the artist library in memory with another one * @param newLib The new artist library */ public static void setArtistLib(ArrayList<Artist> newLib){ artistLib.clear(); artistLib.addAll(newLib); } /** * Replace the genre library in memory with another one * @param newLib The new genre library */ public static void setGenreLib(ArrayList<Genre> newLib){ genreLib.clear(); genreLib.addAll(newLib); } /** * Sorts the libraries in memory using the default {@link Library} sort methods */ public static void sort (){ Collections.sort(songLib); Collections.sort(albumLib); Collections.sort(artistLib); Collections.sort(playlistLib); Collections.sort(genreLib); } /** * @return true if the library is populated with any entries */ public static boolean isEmpty (){ return songLib.isEmpty() && albumLib.isEmpty() && artistLib.isEmpty() && playlistLib.isEmpty() && genreLib.isEmpty(); } /** * @return An {@link ArrayList} of {@link Playlist}s in the MediaStore */ public static ArrayList<Playlist> getPlaylists(){ return playlistLib; } /** * @return An {@link ArrayList} of {@link Song}s in the MediaStore */ public static ArrayList<Song> getSongs(){ return songLib; } /** * @return An {@link ArrayList} of {@link Album}s in the MediaStore */ public static ArrayList<Album> getAlbums(){ return albumLib; } /** * @return An {@link ArrayList} of {@link Artist}s in the MediaStore */ public static ArrayList<Artist> getArtists(){ return artistLib; } /** * @return An {@link ArrayList} of {@link Genre}s in the MediaStore */ public static ArrayList<Genre> getGenres(){ return genreLib; } // LIBRARY SEARCH METHODS /** * Finds a {@link Song} in the library based on its Id * @param songId the MediaStore Id of the {@link Song} * @return A {@link Song} with a matching Id */ public static Song findSongById (int songId){ for (Song s : songLib){ if (s.songId == songId){ return s; } } return null; } /** * Build an {@link ArrayList} of {@link Song}s from a list of id's. Doesn't require the library to be loaded * @param songIDs The list of song ids to convert to {@link Song}s * @param context The {@link Context} used to open a {@link Cursor} * @return An {@link ArrayList} of {@link Song}s with ids matching those of the songIDs parameter */ public static ArrayList<Song> buildSongListFromIds (int[] songIDs, Context context){ ArrayList<Song> contents = new ArrayList<>(); if (songIDs.length == 0) return contents; String query = MediaStore.Audio.Media._ID + " IN(?"; String[] ids = new String[songIDs.length]; ids[0] = Integer.toString(songIDs[0]); for (int i = 1; i < songIDs.length; i++){ query += ",?"; ids[i] = Integer.toString(songIDs[i]); } query += ")"; Cursor cur = context.getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, songProjection, query, ids, MediaStore.Audio.Media.TITLE + " ASC"); if (cur == null) { throw new RuntimeException("Content resolver query returned null"); } for (int i = 0; i < cur.getCount(); i++) { cur.moveToPosition(i); Song s = new Song( cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media._ID)), (cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST)).equals(MediaStore.UNKNOWN_STRING)) ? context.getString(R.string.no_artist) : cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DURATION)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.YEAR)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID))); s.trackNumber = cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.TRACK)); contents.add(s); } cur.close(); // Sort the contents of the list so that it matches the order of the int array ArrayList<Song> songs = new ArrayList<>(); Song dummy = new Song(null, 0, null, null, 0, null, 0, 0, 0, 0); for (int i : songIDs){ dummy.songId = i; // Because Songs are equal if their ids are equal, we can use a dummy song with the ID // we want to find it in the list songs.add(contents.get(contents.indexOf(dummy))); } return songs; } /** * Finds a {@link Artist} in the library based on its Id * @param artistId the MediaStore Id of the {@link Artist} * @return A {@link Artist} with a matching Id */ public static Artist findArtistById (int artistId){ for (Artist a : artistLib){ if (a.artistId == artistId){ return a; } } return null; } /** * Finds a {@link Album} in a library based on its Id * @param albumId the MediaStore Id of the {@link Album} * @return A {@link Album} with a matching Id */ public static Album findAlbumById (int albumId){ // Returns the first Artist object in the library with a matching id for (Album a : albumLib){ if (a.albumId == albumId){ return a; } } return null; } /** * Finds a {@link Genre} in a library based on its Id * @param genreId the MediaStore Id of the {@link Genre} * @return A {@link Genre} with a matching Id */ public static Genre findGenreById (int genreId){ // Returns the first Genre object in the library with a matching id for (Genre g : genreLib){ if (g.genreId == genreId){ return g; } } return null; } public static Artist findArtistByName (String artistName){ final String trimmedQuery = artistName.trim(); for (Artist a : artistLib){ if (a.artistName.equalsIgnoreCase(trimmedQuery)) return a; } return null; } // CONTENTS QUERY METHODS /** * Get a list of songs in a certain playlist * @param context A {@link Context} to open a {@link Cursor} * @param playlist The {@link Playlist} to get the entries of * @return An {@link ArrayList} of {@link Song}s contained in the playlist */ public static ArrayList<Song> getPlaylistEntries (Context context, Playlist playlist){ if (playlist instanceof AutoPlaylist){ ArrayList<Song> entries = ((AutoPlaylist) playlist).generatePlaylist(context); editPlaylist(context, playlist, entries); return entries; } ArrayList<Song> songEntries = new ArrayList<>(); Cursor cur = context.getContentResolver().query( MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId), playlistEntryProjection, MediaStore.Audio.Media.IS_MUSIC + " != 0", null, null); if (cur == null) { throw new RuntimeException("Content resolver query returned null"); } for (int i = 0; i < cur.getCount(); i++) { cur.moveToPosition(i); songEntries.add(new Song( cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.TITLE)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.ARTIST)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.ALBUM)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.DURATION)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.DATA)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.YEAR)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.DATE_ADDED)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.ALBUM_ID)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.ARTIST_ID)))); } cur.close(); return songEntries; } /** * Get a list of songs on a certain album * @param album The {@link Album} to get the entries of * @return An {@link ArrayList} of {@link Song}s contained in the album */ public static ArrayList<Song> getAlbumEntries (Album album){ ArrayList<Song> songEntries = new ArrayList<>(); for (Song s : songLib){ if (s.albumId == album.albumId){ songEntries.add(s); } } Collections.sort(songEntries, new Comparator<Song>() { @Override public int compare(Song o1, Song o2) { return ((Integer) o1.trackNumber).compareTo(o2.trackNumber); } }); return songEntries; } /** * Get a list of songs by a certain artist * @param artist The {@link Artist} to get the entries of * @return An {@link ArrayList} of {@link Song}s by the artist */ public static ArrayList<Song> getArtistSongEntries (Artist artist){ ArrayList<Song> songEntries = new ArrayList<>(); for(Song s : songLib){ if (s.artistId == artist.artistId){ songEntries.add(s); } } return songEntries; } /** * Get a list of albums by a certain artist * @param artist The {@link Artist} to get the entries of * @return An {@link ArrayList} of {@link Album}s by the artist */ public static ArrayList<Album> getArtistAlbumEntries (Artist artist){ ArrayList<Album> albumEntries = new ArrayList<>(); for (Album a : albumLib){ if (a.artistId == artist.artistId){ albumEntries.add(a); } } return albumEntries; } /** * Get a list of songs in a certain genre * @param genre The {@link Genre} to get the entries of * @return An {@link ArrayList} of {@link Song}s contained in the genre */ public static ArrayList<Song> getGenreEntries (Genre genre){ ArrayList<Song> songEntries = new ArrayList<>(); for(Song s : songLib){ if (s.genreId == genre.genreId){ songEntries.add(s); } } return songEntries; } // PLAY COUNT READING & ACCESSING METHODS public static void loadPlayCounts(Context context) { playCounts.clear(); skipCounts.clear(); playDates.clear(); try { Properties countProperties = openPlayCountFile(context); Enumeration iterator = countProperties.propertyNames(); while (iterator.hasMoreElements()){ String key = (String) iterator.nextElement(); String value = countProperties.getProperty(key, "0,0"); final String[] originalValues = value.split(","); int playCount = Integer.parseInt(originalValues[0]); int skipCount = Integer.parseInt(originalValues[1]); int playDate = 0; if (originalValues.length > 2) { playDate = Integer.parseInt(originalValues[2]); } playCounts.put(Integer.parseInt(key), playCount); skipCounts.put(Integer.parseInt(key), skipCount); playDates.put(Integer.parseInt(key), playDate); } } catch (IOException e){ Crashlytics.logException(e); } } /** * Returns a readable {@link Properties} to be used with {@link Library#loadPlayCounts(Context)} * @param context Used to read files from external storage * @return A {@link Properties} object that has been initialized with values saved by * {@link Player#logPlayCount(long, boolean)} and {@link Player#savePlayCountFile()} * @throws IOException */ private static Properties openPlayCountFile(Context context) throws IOException{ File file = new File(context.getExternalFilesDir(null) + "/" + Library.PLAY_COUNT_FILENAME); if (!file.exists()) //noinspection ResultOfMethodCallIgnored file.createNewFile(); InputStream is = new FileInputStream(file); Properties playCountHashtable; try { playCountHashtable = new Properties(); playCountHashtable.load(is); } finally { is.close(); } return playCountHashtable; } /** * Returns the number of skips a song has. Note that you may need to call * {@link Library#loadPlayCounts(Context)} in case the data has gone stale * @param songId The {@link Song#songId} as written in the MediaStore * @return The number of times a song has been skipped */ public static int getSkipCount (int songId){ return skipCounts.get(songId, 0); } /** * Returns the number of plays a song has. Note that you may need to call * {@link Library#loadPlayCounts(Context)} in case the data has gone stale * @param songId The {@link Song#songId} as written in the MediaStore * @return The number of times a song has been plays */ public static int getPlayCount (int songId){ return playCounts.get(songId, 0); } /** * * Returns the last time a song was played with Jockey. Note that you may need to call * {@link Library#loadPlayCounts(Context)} in case the data has gone stale * @param songId The {@link Song#songId} as written in the MediaStore * @return The last time a song was played given in seconds as a UTC timestamp * (since midnight of January 1, 1970 UTC) */ public static int getPlayDate(int songId) { return playDates.get(songId, 0); } // PLAYLIST WRITING METHODS /** * Add a new playlist to the MediaStore * @param view A {@link View} to put a {@link Snackbar} in. Will also be used to get a {@link Context}. * @param playlistName The name of the new playlist * @param songList An {@link ArrayList} of {@link Song}s to populate the new playlist * @return The Playlist that was added to the library */ public static Playlist createPlaylist(final View view, final String playlistName, @Nullable final ArrayList<Song> songList){ final Context context = view.getContext(); String trimmedName = playlistName.trim(); setPlaylistLib(scanPlaylists(context)); String error = verifyPlaylistName(context, trimmedName); if (error != null){ Snackbar .make( view, error, Snackbar.LENGTH_SHORT) .show(); return null; } // Add the playlist to the MediaStore final Playlist created = addPlaylist(context, trimmedName, songList); Snackbar .make( view, String.format(context.getResources().getString(R.string.message_created_playlist), playlistName), Snackbar.LENGTH_LONG) .setAction( R.string.action_undo, new View.OnClickListener() { @Override public void onClick(View v) { deletePlaylist(context, created); } }) .show(); return created; } /** * Test a playlist name to make sure it is valid when making a new playlist. Invalid playlist names * are instance_empty or already exist in the MediaStore * @param context A {@link Context} used to get localized Strings * @param playlistName The playlist name that needs to be validated * @return null if there is no error, or a {@link String} describing the error that can be * presented to the user */ public static String verifyPlaylistName (final Context context, final String playlistName){ String trimmedName = playlistName.trim(); if (trimmedName.length() == 0){ return context.getResources().getString(R.string.error_hint_empty_playlist); } for (Playlist p : playlistLib){ if (p.playlistName.equalsIgnoreCase(trimmedName)){ return context.getResources().getString(R.string.error_hint_duplicate_playlist); } } return null; } /** * Removes a playlist from the MediaStore * @param view A {@link View} to show a {@link Snackbar} and to get a {@link Context} used to edit the MediaStore * @param playlist A {@link Playlist} which will be removed from the MediaStore */ public static void removePlaylist(final View view, final Playlist playlist){ final Context context = view.getContext(); final ArrayList<Song> entries = getPlaylistEntries(context, playlist); deletePlaylist(context, playlist); Snackbar .make( view, String.format(context.getString(R.string.message_removed_playlist), playlist), Snackbar.LENGTH_LONG) .setAction( context.getString(R.string.action_undo), new View.OnClickListener() { @Override public void onClick(View v) { if (playlist instanceof AutoPlaylist) { createAutoPlaylist(context, (AutoPlaylist) playlist); } else { addPlaylist(context, playlist.playlistName, entries); } } }) .show(); } /** * Replace the entries of a playlist in the MediaStore with a new {@link ArrayList} of {@link Song}s * @param context A {@link Context} to open a {@link Cursor} * @param playlist The {@link Playlist} to edit in the MediaStore * @param newSongList An {@link ArrayList} of {@link Song}s to overwrite the list contained in the MediaStore */ public static void editPlaylist(final Context context, final Playlist playlist, final ArrayList<Song> newSongList){ // Clear the playlist... Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId); ContentResolver resolver = context.getContentResolver(); resolver.delete(uri, null, null); // Then add all of the songs to it ContentValues[] values = new ContentValues[newSongList.size()]; for (int i = 0; i < newSongList.size(); i++) { values[i] = new ContentValues(); values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, i + 1); values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, newSongList.get(i).songId); } resolver.bulkInsert(uri, values); resolver.notifyChange(Uri.parse("content://media"), null); } /** * Rename a playlist in the MediaStore * @param context A {@link Context} to open a {@link ContentResolver} * @param playlistID The id of the {@link Playlist} to be renamed * @param name The new name of the playlist */ public static void renamePlaylist(final Context context, final long playlistID, final String name) { if (verifyPlaylistName(context, name) == null) { ContentValues values = new ContentValues(1); values.put(MediaStore.Audio.Playlists.NAME, name); ContentResolver resolver = context.getContentResolver(); resolver.update( MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, values, MediaStore.Audio.Playlists._ID + "=?", new String[]{Long.toString(playlistID)}); } } /** * Append a song to the end of a playlist. Alerts the user about duplicates * @param context A {@link Context} to open a {@link Cursor} * @param playlist The {@link Playlist} to edit in the MediaStore * @param song The {@link Song} to be added to the playlist in the MediaStore */ public static void addPlaylistEntry(final Context context, final Playlist playlist, final Song song){ // Public method to add a song to a playlist // Checks the playlist for duplicate entries if (getPlaylistEntries(context, playlist).contains(song)){ AlertDialog dialog = new AlertDialog.Builder(context) .setTitle(context.getResources().getQuantityString(R.plurals.alert_confirm_duplicates, 1)) .setMessage(context.getString(R.string.playlist_confirm_duplicate, playlist, song)) .setPositiveButton(R.string.action_add, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { addSongToEndOfPlaylist(context, playlist, song); } }) .setNegativeButton(R.string.action_cancel, null) .show(); Themes.themeAlertDialog(dialog); } else{ addSongToEndOfPlaylist(context, playlist, song); } } /** * Append a list of songs to the end of a playlist. Alerts the user about duplicates * @param view A {@link View} to put a {@link android.support.design.widget.Snackbar} in. Will * also be used to get a {@link Context}. * @param playlist The {@link Playlist} to edit in the MediaStore * @param songs The {@link ArrayList} of {@link Song}s to be added to the playlist in the MediaStore */ public static void addPlaylistEntries(final View view, final Playlist playlist, final ArrayList<Song> songs){ // Public method to add songs to a playlist // Checks the playlist for duplicate entries final Context context = view.getContext(); int duplicateCount = 0; final ArrayList<Song> currentEntries = getPlaylistEntries(context, playlist); final ArrayList<Song> newEntries = new ArrayList<>(); for (Song s : songs){ if (currentEntries.contains(s))duplicateCount++; else newEntries.add(s); } if (duplicateCount > 0){ AlertDialog.Builder alert = new AlertDialog.Builder(context).setTitle(context.getResources().getQuantityString(R.plurals.alert_confirm_duplicates, duplicateCount)); if (duplicateCount == songs.size()) { alert .setMessage(context.getString(R.string.playlist_confirm_all_duplicates, duplicateCount)) .setPositiveButton(context.getResources().getQuantityText(R.plurals.playlist_positive_add_duplicates, duplicateCount), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { addSongsToEndOfPlaylist(context, playlist, songs); Snackbar.make( view, context.getString(R.string.confirm_add_songs, songs.size(), playlist.playlistName), Snackbar.LENGTH_LONG) .setAction(context.getString(R.string.action_undo), new View.OnClickListener() { @Override public void onClick(View v) { Library.editPlaylist( context, playlist, currentEntries); } }).show(); } }) .setNeutralButton(context.getString(R.string.action_cancel), null); } else{ alert .setMessage(context.getResources().getQuantityString(R.plurals.playlist_confirm_some_duplicates, duplicateCount, duplicateCount)) .setPositiveButton(R.string.action_add_new, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { addSongsToEndOfPlaylist(context, playlist, newEntries); Snackbar.make( view, context.getString(R.string.confirm_add_songs, newEntries.size(), playlist.playlistName), Snackbar.LENGTH_LONG) .setAction(R.string.action_undo, new View.OnClickListener() { @Override public void onClick(View v) { Library.editPlaylist( context, playlist, currentEntries); } }).show(); } }) .setNegativeButton(R.string.action_add_all, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { addSongsToEndOfPlaylist(context, playlist, songs); Snackbar.make( view, context.getString(R.string.confirm_add_songs, songs.size(), playlist.playlistName), Snackbar.LENGTH_LONG) .setAction(R.string.action_undo, new View.OnClickListener() { @Override public void onClick(View v) { Library.editPlaylist( context, playlist, currentEntries); } }).show(); } }) .setNeutralButton(R.string.action_cancel, null); } Themes.themeAlertDialog(alert.show()); } else{ addSongsToEndOfPlaylist(context, playlist, songs); Snackbar.make( view, context.getString(R.string.confirm_add_songs, newEntries.size(), playlist.playlistName), Snackbar.LENGTH_LONG) .setAction(R.string.action_undo, new View.OnClickListener() { @Override public void onClick(View v) { Library.editPlaylist( context, playlist, currentEntries); } }).show(); } } // MEDIA_STORE EDIT METHODS // These methods only perform actions to the MediaStore. They do not validate inputs, and they // do not display confirmation messages to the user. /** * Add a new playlist to the MediaStore and to the application's current library instance. Use * this when making regular playlists. * Outside of this class, use {@link Library#createPlaylist(View, String, ArrayList)} instead * <b>This method DOES NOT validate inputs or display a confirmation message to the user</b>. * @param context A {@link Context} used to edit the MediaStore * @param playlistName The name of the new playlist * @param songList An {@link ArrayList} of {@link Song}s to populate the new playlist * @return The Playlist that was added to the library */ private static Playlist addPlaylist(final Context context, final String playlistName, @Nullable final ArrayList<Song> songList) { final Playlist added = makePlaylist(context, playlistName, songList); playlistLib.add(added); Collections.sort(playlistLib); notifyPlaylistAdded(added); return added; } /** * Internal logic for adding a playlist to the MediaStore only. * @param context A {@link Context} used to edit the MediaStore * @param playlistName The name of the new playlist * @param songList An {@link ArrayList} of {@link Song}s to populate the new playlist * @return The Playlist that was added to the library * @see Library#addPlaylist(Context, String, ArrayList) for playlist creation * @see Library#createAutoPlaylist(Context, AutoPlaylist) for AutoPlaylist creation */ private static Playlist makePlaylist(final Context context, final String playlistName, @Nullable final ArrayList<Song> songList){ String trimmedName = playlistName.trim(); // Add the playlist to the MediaStore ContentValues mInserts = new ContentValues(); mInserts.put(MediaStore.Audio.Playlists.NAME, trimmedName); mInserts.put(MediaStore.Audio.Playlists.DATE_ADDED, System.currentTimeMillis()); mInserts.put(MediaStore.Audio.Playlists.DATE_MODIFIED, System.currentTimeMillis()); Uri newPlaylistUri = context.getContentResolver().insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, mInserts); if (newPlaylistUri == null) { throw new RuntimeException("Content resolver insert returned null"); } // Get the id of the new playlist Cursor cursor = context.getContentResolver().query( newPlaylistUri, new String[] {MediaStore.Audio.Playlists._ID}, null, null, null); if (cursor == null) { throw new RuntimeException("Content resolver query returned null"); } cursor.moveToFirst(); final Playlist playlist = new Playlist(cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Playlists._ID)), playlistName); cursor.close(); // If we have a list of songs, associate it with the playlist if(songList != null) { ContentValues[] values = new ContentValues[songList.size()]; for (int i = 0; i < songList.size(); i++) { values[i] = new ContentValues(); values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, i); values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songList.get(i).songId); } Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId); ContentResolver resolver = context.getContentResolver(); resolver.bulkInsert(uri, values); resolver.notifyChange(Uri.parse("content://media"), null); } return playlist; } /** * Removes a playlist from the MediaStore * @param context A {@link Context} to update the MediaStore * @param playlist A {@link Playlist} whose matching playlist will be removed from the MediaStore */ public static void deletePlaylist(final Context context, final Playlist playlist){ // Remove the playlist from the MediaStore context.getContentResolver().delete( MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, MediaStore.Audio.Playlists._ID + "=?", new String[]{playlist.playlistId + ""}); // If the playlist is an AutoPlaylist, make sure to delete its configuration if (playlist instanceof AutoPlaylist) { //noinspection ResultOfMethodCallIgnored new File(context.getExternalFilesDir(null) + "/" + playlist.playlistName + AUTO_PLAYLIST_EXTENSION).delete(); } // Update the playlist library & resort it playlistLib.clear(); setPlaylistLib(scanPlaylists(context)); Collections.sort(playlistLib); notifyPlaylistRemoved(playlist); } /** * Append a song to the end of a playlist. Doesn't check for duplicates * @param context A {@link Context} to open a {@link Cursor} * @param playlist The {@link Playlist} to edit in the MediaStore * @param song The {@link Song} to be added to the playlist in the MediaStore */ private static void addSongToEndOfPlaylist (final Context context, final Playlist playlist, final Song song){ // Private method to add a song to a playlist // This method does the actual operation to the MediaStore Cursor cur = context.getContentResolver().query( MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId), null, null, null, MediaStore.Audio.Playlists.Members.TRACK + " ASC"); if (cur == null) { throw new RuntimeException("Content resolver query returned null"); } long count = 0; if (cur.moveToLast()) count = cur.getLong(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.TRACK)); cur.close(); ContentValues values = new ContentValues(); values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, count + 1); values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, song.songId); Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId); ContentResolver resolver = context.getContentResolver(); resolver.insert(uri, values); resolver.notifyChange(Uri.parse("content://media"), null); } /** * Append a list of songs to the end of a playlist. Doesn't check for duplicates * @param context A {@link Context} to open a {@link Cursor} * @param playlist The {@link Playlist} to edit in the MediaStore * @param songs The {@link ArrayList} of {@link Song}s to be added to the playlist in the MediaStore */ private static void addSongsToEndOfPlaylist(final Context context, final Playlist playlist, final ArrayList<Song> songs){ // Private method to add a song to a playlist // This method does the actual operation to the MediaStore Cursor cur = context.getContentResolver().query( MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId), null, null, null, MediaStore.Audio.Playlists.Members.TRACK + " ASC"); if (cur == null) { throw new RuntimeException("Content resolver query returned null"); } long count = 0; if (cur.moveToLast()) count = cur.getLong(cur.getColumnIndex(MediaStore.Audio.Playlists.Members.TRACK)); cur.close(); ContentValues[] values = new ContentValues[songs.size()]; for (int i = 0; i < songs.size(); i++) { values[i] = new ContentValues(); values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, count + 1); values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songs.get(i).songId); } Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.playlistId); ContentResolver resolver = context.getContentResolver(); resolver.bulkInsert(uri, values); resolver.notifyChange(Uri.parse("content://media"), null); } // AUTO PLAYLIST EDIT METHODS /** * Add an {@link AutoPlaylist} to the library. * @param playlist the AutoPlaylist to be added to the library. The configuration of this * playlist will be saved so that it can be loaded when the library is next * rescanned, and a "stale" copy with current entries will be written in the * MediaStore so that other applications may access this playlist */ public static void createAutoPlaylist(Context context, AutoPlaylist playlist) { try { // Add the playlist to the MediaStore Playlist p = makePlaylist(context, playlist.playlistName, playlist.generatePlaylist(context)); // Assign the auto playlist's ID to match the one in the MediaStore playlist.playlistId = p.playlistId; // Save the playlist configuration with GSON Gson gson = new GsonBuilder().setPrettyPrinting().create(); FileWriter playlistWriter = new FileWriter(context.getExternalFilesDir(null) + "/" + playlist.playlistName + AUTO_PLAYLIST_EXTENSION); playlistWriter.write(gson.toJson(playlist, AutoPlaylist.class)); playlistWriter.close(); // Add the playlist to the library and resort the playlist library playlistLib.add(playlist); Collections.sort(playlistLib); notifyPlaylistAdded(playlist); } catch (IOException e) { Crashlytics.logException(e); } } public static void editAutoPlaylist(Context context, AutoPlaylist playlist) { try { // Save the playlist configuration with GSON Gson gson = new GsonBuilder().setPrettyPrinting().create(); FileWriter playlistWriter = new FileWriter(context.getExternalFilesDir(null) + "/" + playlist.playlistName + AUTO_PLAYLIST_EXTENSION); playlistWriter.write(gson.toJson(playlist, AutoPlaylist.class)); playlistWriter.close(); // Edit the contents of this playlist in the MediaStore editPlaylist(context, playlist, playlist.generatePlaylist(context)); // Remove the old index of this playlist, but keep the Object for reference. // Since playlists are compared by Id's, this will remove the old index AutoPlaylist oldReference = (AutoPlaylist) playlistLib.remove(playlistLib.indexOf(playlist)); // If the user renamed the playlist, update it now if (!oldReference.playlistName.equals(playlist.playlistName)) { renamePlaylist(context, playlist.playlistId, playlist.playlistName); // Delete the old config file so that it doesn't reappear on restart //noinspection ResultOfMethodCallIgnored new File(context.getExternalFilesDir(null) + "/" + oldReference.playlistName + AUTO_PLAYLIST_EXTENSION).delete(); } // Add the playlist again. This makes sure that if the values have been cloned before // being changed that their values will be updated without having to rescan the // entire library playlistLib.add(playlist); Collections.sort(playlistLib); } catch (IOException e) { Crashlytics.logException(e); } } // Media file open method /** * Get a list of songs to play for a certain input file. If a song is passed as the file, then * the list will include other songs in the same directory. If a playlist is passed as the file, * then the playlist will be opened as a regular playlist. * * @param activity An {@link Activity} to use when building the list * @param file The {@link File} which the list will be built around * @param type The MIME type of the file being opened * @param queue An {@link ArrayList} which will be populated with the {@link Song}s * @return The position that this list should be started from * @throws IOException */ public static int getSongListFromFile(Activity activity, File file, String type, final ArrayList<Song> queue) throws IOException{ // A somewhat convoluted method for getting a list of songs from a path // Songs are put into the queue array list // The integer returned is the position in this queue that corresponds to the requested song if (isEmpty()){ // We depend on the library being scanned, so make sure it's scanned before we go any further scanAll(activity); } // PLAYLISTS if (type.equals("audio/x-mpegurl") || type.equals("audio/x-scpls") || type.equals("application/vnd.ms-wpl")){ // If a playlist was opened, try to find and play its entry from the MediaStore Cursor cur = activity.getContentResolver().query( MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, null, MediaStore.Audio.Playlists.DATA + "=?", new String[] {file.getPath()}, MediaStore.Audio.Playlists.NAME + " ASC"); if (cur == null) { throw new RuntimeException("Content resolver query returned null"); } // If the media store contains this playlist, play it like a regular playlist if (cur.getCount() > 0){ cur.moveToFirst(); queue.addAll(getPlaylistEntries(activity, new Playlist( cur.getInt(cur.getColumnIndex(MediaStore.Audio.Playlists._ID)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Playlists.NAME))))); } //TODO Attempt to manually read common playlist writing schemes /*else{ // If the MediaStore doesn't contain this playlist, attempt to read it manually Scanner sc = new Scanner(file); ArrayList<String> lines = new ArrayList<>(); while (sc.hasNextLine()) { lines.add(sc.nextLine()); } if (lines.size() > 0){ // Do stuff } }*/ cur.close(); // Return 0 to start at the beginning of the playlist return 0; } // ALL OTHER TYPES OF MEDIA else { // If the file isn't a playlist, use a content resolver to find the song and play it // Find all songs in the directory Cursor cur = activity.getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Audio.Media.DATA + " like ?", new String[] {"%" + file.getParent() + "/%"}, MediaStore.Audio.Media.DATA + " ASC"); if (cur == null) { throw new RuntimeException("Content resolver query returned null"); } // Create song objects to match those in the music library for (int i = 0; i < cur.getCount(); i++) { cur.moveToPosition(i); queue.add(new Song( cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media._ID)), (cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)).equals(MediaStore.UNKNOWN_STRING)) ? activity.getString(R.string.unknown_artist) : cur.getString(cur.getColumnIndex(MediaStore.Audio.Albums.ARTIST)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DURATION)), cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.DATA)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.YEAR)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)), cur.getInt(cur.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)))); } cur.close(); // Find the position of the song that should be played for(int i = 0; i < queue.size(); i++){ if (queue.get(i).location.equals(file.getPath())) return i; } } return 0; } }
package io.bisq.provider; import ch.qos.logback.classic.Level; import io.bisq.common.app.Log; import io.bisq.common.app.Version; import io.bisq.common.util.Utilities; import io.bisq.network.http.HttpException; import io.bisq.provider.fee.FeeRequestService; import io.bisq.provider.price.PriceRequestService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.spec.InvalidKeySpecException; import java.util.Locale; import static spark.Spark.get; import static spark.Spark.port; public class ProviderMain { private static final Logger log = LoggerFactory.getLogger(ProviderMain.class); static { // Need to set default locale initially otherwise we get problems at non-english OS Locale.setDefault(new Locale("en", Locale.getDefault().getCountry())); Utilities.removeCryptographyRestrictions(); } public static void main(String[] args) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, InvalidKeyException, HttpException { final String logPath = System.getProperty("user.home") + File.separator + "provider"; Log.setup(logPath); Log.setLevel(Level.INFO); log.info("Log files under: " + logPath); log.info("ProviderVersion.VERSION: " + ProviderVersion.VERSION); log.info("Bisq exchange Version{" + "VERSION=" + Version.VERSION + ", P2P_NETWORK_VERSION=" + Version.P2P_NETWORK_VERSION + ", LOCAL_DB_VERSION=" + Version.LOCAL_DB_VERSION + ", TRADE_PROTOCOL_VERSION=" + Version.TRADE_PROTOCOL_VERSION + ", BASE_CURRENCY_NETWORK=NOT SET" + ", getP2PNetworkId()=NOT SET" + '}'); Utilities.printSysInfo(); port(8080); handleGetAllMarketPrices(args); handleGetFees(); handleGetVersion(); } private static void handleGetAllMarketPrices(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException { if (args.length == 2) { String bitcoinAveragePrivKey = args[0]; String bitcoinAveragePubKey = args[1]; PriceRequestService priceRequestService = new PriceRequestService(bitcoinAveragePrivKey, bitcoinAveragePubKey); get("/getAllMarketPrices", (req, res) -> { log.info("Incoming getAllMarketPrices request from: " + req.userAgent()); return priceRequestService.getJson(); }); } else { throw new IllegalArgumentException("You need to provide the BitcoinAverage API keys. Private key as first argument, public key as second argument."); } } private static void handleGetFees() throws IOException { FeeRequestService feeRequestService = new FeeRequestService(); get("/getFees", (req, res) -> { log.info("Incoming getFees request from: " + req.userAgent()); return feeRequestService.getJson(); }); } private static void handleGetVersion() throws IOException { FeeRequestService feeRequestService = new FeeRequestService(); get("/getVersion", (req, res) -> { log.info("Incoming getVersion request from: " + req.userAgent()); return ProviderVersion.VERSION; }); } }
package org.myrobotlab.service; import org.junit.Ignore; import org.myrobotlab.document.connector.AbstractConnector; import org.myrobotlab.service.interfaces.AbstractConnectorTest; import org.myrobotlab.service.interfaces.MockDocumentListener; @Ignore public class FileConnectorTest extends AbstractConnectorTest { @Override public AbstractConnector createConnector() { FileConnector connector = new FileConnector("testconnector"); connector.setDirectory("."); return connector; } @Override public MockDocumentListener createListener() { return new MockDocumentListener("mocklistener"); } @Override public void validate(MockDocumentListener listener) { // TODO: actually validate something here. log.info("Final Count: {}" , listener.getCount()); } }
package org.commcare.views.widgets; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.provider.MediaStore.Audio; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import org.commcare.CommCareApplication; import org.commcare.activities.components.FormEntryConstants; import org.commcare.dalvik.R; import org.commcare.logic.PendingCalloutInterface; import org.commcare.utils.FileUtil; import org.commcare.utils.StringUtils; import org.commcare.utils.UriToFilePath; import org.javarosa.form.api.FormEntryPrompt; import java.io.File; import java.io.IOException; /** * Widget that allows user to take pictures, sounds or video and add them to * the form. * * @author Carl Hartung (carlhartung@gmail.com) * @author Yaw Anokwa (yanokwa@gmail.com) */ public class AudioWidget extends MediaWidget { private static final String TAG = AudioWidget.class.getSimpleName(); protected static final String CUSTOM_TAG = "custom"; protected String recordedFileName; private String customFileTag; public AudioWidget(Context context, final FormEntryPrompt prompt, PendingCalloutInterface pic) { super(context, prompt, pic); } @Override protected void initializeButtons(){ // setup capture button mCaptureButton = new Button(getContext()); WidgetUtils.setupButton(mCaptureButton, StringUtils.getStringSpannableRobust(getContext(), R.string.capture_audio), mAnswerFontSize, !mPrompt.isReadOnly()); // setup audio filechooser button mChooseButton = new Button(getContext()); WidgetUtils.setupButton(mChooseButton, StringUtils.getStringSpannableRobust(getContext(), R.string.choose_sound), mAnswerFontSize, !mPrompt.isReadOnly()); // setup play button mPlayButton = new Button(getContext()); WidgetUtils.setupButton(mPlayButton, StringUtils.getStringSpannableRobust(getContext(), R.string.play_audio), mAnswerFontSize, !mPrompt.isReadOnly()); // launch capture intent on click mCaptureButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { captureAudio(mPrompt); } }); // launch audio filechooser intent on click mChooseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(Intent.ACTION_GET_CONTENT); /** * If file is chosen by user, the file selection intent will return an URI * If file is auto-selected after recording_fragment, then the recordingfragment will provide a string file path * Set value of customFileTag if the file is a recent recording from the RecordingFragment */ @Override protected String createFilePath(Object binaryuri){ String path; if(binaryuri instanceof Uri){ path = UriToFilePath.getPathFromUri(CommCareApplication.instance(), (Uri)binaryuri); customFileTag = ""; }else{ path = (String) binaryuri; customFileTag = CUSTOM_TAG; } return path; } }
public class Job implements Runnable { private int jobNumber; Job (int jobNumber) { this.jobNumber = jobNumber; } public void run () { // Undertake required work, here we will emulate it by sleeping for a period System.out.println ("Job: " + jobNumber + " is being processed by thread : " + Thread.currentThread ().getName()); try { Thread.sleep((int)(1000)); } catch (InterruptedException e) { // no catching as example should not experience interruptions } System.out.println("Job: " + jobNumber + " is ending in thread : " + Thread.currentThread().getName()); } }
package com.hida; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.sql.SQLException; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import org.springframework.web.bind.annotation.ExceptionHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.locks.ReentrantLock; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.web.servlet.ModelAndView; /** * A controller class that paths the user to all jsp files in WEB_INF/jsp. * * @author lruffin */ @Controller public class MinterController { // Logger; logfile to be stored in resource folder private static final Logger Logger = LoggerFactory.getLogger(MinterController.class); /** * Creates a fair reentrant RequestLock to serialize each request * sequentially instead of concurrently. pids */ private static final ReentrantLock RequestLock = new ReentrantLock(true); /** * fields for minter's default values, cached values */ private static final String CONFIG_FILE = "minter_config.properties"; /** * create a database to be used to create and count number of ids */ private final DatabaseManager DatabaseManager; private final CachedSettings Settings; /** * Constructor that loads the property file and retrieves the values stored * at the databasePath and databaseName keys. If the the keys are empty then * a database called PID.db will be made at the default location specified * by the server. * * @throws IOException Thrown if the property file was not found. */ public MinterController() throws IOException, SQLException, BadParameterException, ClassNotFoundException { Properties properties = new Properties(); properties.load(Thread.currentThread(). getContextClassLoader().getResourceAsStream(CONFIG_FILE)); // Retrieves the path and the name of a database from the property file for this session String path = properties.getProperty("databasePath"); Logger.info("Getting database path: " + path); String name = properties.getProperty("databaseName"); Logger.info("getting Database Name: " + name); // Creates the database at a location specified by the properties file if (!name.isEmpty()) { if (!path.endsWith("\\")) { path += "\\"; Logger.warn("Database Path not set correctly: adding \\"); } DatabaseManager = new DatabaseManager(path, name); Logger.info("Creating DataBase Manager with Path=" + path + ", Name=" + name); } else { DatabaseManager = new DatabaseManager(); Logger.info("Creating DatabaseManager with " + "Path=" + DatabaseManager.getDatabasePath() + ", " + "Name=" + DatabaseManager.getDatabaseName()); } // create connection and sets up the database if need be DatabaseManager.createConnection(); Logger.info("Database Connection Created to: " + DatabaseManager.getDatabaseName()); // retrieve the default settings from the database and store it in Settings Settings = new CachedSettings(); Settings.retrieveSettings(); DatabaseManager.closeConnection(); } /** * Redirects to the index after retrieving updated settings from the * administration panel. * * @param request HTTP request from the administration panel * @param response HTTP response that redirects to the administration panel * after updating the new settings. * @return The name of the page to redirect. * @throws SQLException * @throws BadParameterException Thrown whenever a bad parameter is * detected. * @throws ClassNotFoundException Thrown whenever a class does not exist. */ @RequestMapping(value = {"/confirmation"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public String handleForm(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, SQLException, BadParameterException { try { // prevents other clients from accessing the database whenever the form is submitted RequestLock.lock(); DatabaseManager.createConnection(); Logger.info("in handleForm"); String prepend = request.getParameter("prepend"); String prefix = request.getParameter("idprefix"); String isAuto = request.getParameter("mintType"); String isRandom = request.getParameter("mintOrder"); String sansVowels = request.getParameter("vowels"); String digitToken; String lowerToken; String upperToken; String charMap; String rootLength = request.getParameter("idlength"); boolean auto = isAuto.equals("auto"); boolean random = isRandom.equals("random"); boolean vowels = sansVowels == null; // assign a non-null value to prepend, prefix, and rootLength if (prepend == null) { prepend = ""; } if (prefix == null) { prefix = ""; } if ((rootLength == null || rootLength.isEmpty()) && !auto) { rootLength = "1"; } int length = Integer.parseInt(rootLength); // assign values based on which minter type was selected if (auto) { digitToken = request.getParameter("digits"); lowerToken = request.getParameter("lowercase"); upperToken = request.getParameter("uppercase"); TokenType tokenType; // gets the tokenmap value if (digitToken != null && lowerToken == null && upperToken == null) { tokenType = TokenType.DIGIT; } else if (digitToken == null && lowerToken != null && upperToken == null) { tokenType = TokenType.LOWERCASE; } else if (digitToken == null && lowerToken == null && upperToken != null) { tokenType = TokenType.UPPERCASE; } else if (digitToken == null && lowerToken != null && upperToken != null) { tokenType = TokenType.MIXEDCASE; } else if (digitToken != null && lowerToken != null && upperToken == null) { tokenType = TokenType.LOWER_EXTENDED; } else if (digitToken == null && lowerToken == null && upperToken != null) { tokenType = TokenType.UPPER_EXTENDED; } else if (digitToken != null && lowerToken != null && upperToken != null) { tokenType = TokenType.MIXED_EXTENDED; } else { throw new BadParameterException(); } DatabaseManager.assignSettings( prepend, prefix, tokenType, length, auto, random, vowels); } else { charMap = request.getParameter("charmapping"); if (charMap == null || charMap.isEmpty()) { throw new BadParameterException(); } DatabaseManager.assignSettings(prepend, prefix, charMap, auto, random, vowels); } // close the connection and update the cache Settings.retrieveSettings(); DatabaseManager.closeConnection(); } finally { // unlocks RequestLock and gives access to longest waiting thread RequestLock.unlock(); Logger.warn("Request to update default settings finished, UNLOCKING MINTER"); } return "redirect:"; } /** * Creates a path to mint ids. If parameters aren't given then printPids * will resort to using the default values found in minter_config.properties * * @param requestedAmount requested number of ids to mint * @param model serves as a holder for the model so that attributes can be * added. * @param parameters parameters given by user to instill variety in ids * @return paths user to mint.jsp * @throws Exception catches all sorts of exceptions that may be thrown by * any methods */ @RequestMapping(value = {"/mint/{requestedAmount}"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}) public String printPids(@PathVariable long requestedAmount, ModelMap model, @RequestParam Map<String, String> parameters) throws Exception { // ensure that only one thread access the minter at any given time RequestLock.lock(); Logger.warn("Request to Minter made, LOCKING MINTER"); // message variable to be sent to mint.jsp String message; try { // create a connection DatabaseManager.createConnection(); Logger.info("Database Connection Created to: " + DatabaseManager.getDatabaseName()); // override default settings CachedSettings tempSettings = overrideDefaults(parameters); if(tempSettings.Auto){ DatabaseManager.createAutoMinter(tempSettings.getPrepend(), tempSettings.getPrefix(), tempSettings.isSansVowels(), tempSettings.getTokenType(), tempSettings.getRootLength()); }else{ DatabaseManager.createCustomMinter(tempSettings.getPrepend(), tempSettings.getPrefix(), tempSettings.isSansVowels(), tempSettings.getCharMap()); } Set<Id> idList = DatabaseManager.mint(requestedAmount, tempSettings.Random); /* // instantiate the correct minter and calculate remaining number of permutations long remainingPermutations; Minter minter; if (tempSettings.isAuto()) { minter = createAutoMinter(requestedAmount, tempSettings); remainingPermutations = DatabaseManager.getPermutations(tempSettings.getPrefix(), tempSettings.getTokenType(), tempSettings.getRootLength(), tempSettings.isSansVowels()); } else { minter = createCustomMinter(requestedAmount, tempSettings); remainingPermutations = DatabaseManager.getPermutations(tempSettings.getPrefix(), tempSettings.isSansVowels(), tempSettings.getCharMap(), minter.getTokenType()); } // throw an exception if the requested amount of ids can't be generated if (remainingPermutations < requestedAmount) { Logger.error("Not enough remaining Permutations, " + "Requested Amount=" + requestedAmount + " --> " + "Amount Remaining=" + remainingPermutations); throw new NotEnoughPermutationsException(remainingPermutations, requestedAmount); } Set<Id> idList; // have the minter create the ids and assign it to message if (tempSettings.isAuto()) { if (tempSettings.isRandom()) { idList = minter.genIdAutoRandom(requestedAmount); Logger.info("Generated IDs will use the Format: " + tempSettings); Logger.info("Making autoRandom Generated IDs, Amount Requested=" + requestedAmount); } else { idList = minter.genIdAutoSequential(requestedAmount); Logger.info("Generated IDs will use the Format: " + tempSettings); Logger.info("Making autoSequential Generated IDs, Amount Requested=" + requestedAmount); } } else { if (tempSettings.isRandom()) { idList = minter.genIdCustomRandom(requestedAmount); Logger.info("Generated IDs will use the Format: " + tempSettings); Logger.info("Making customRandom Generated IDs, Amount Requested=" + requestedAmount); } else { idList = minter.genIdCustomSequential(requestedAmount); Logger.info("Generated IDs will use the Format: " + tempSettings); Logger.info("Making customSequential Generated IDs, Amount Requested=" + requestedAmount); } } */ message = convertListToJson(idList, tempSettings.getPrepend()); //Logger.info("Message from Minter: "+message); // print list of ids to screen model.addAttribute("message", message); // close the connection DatabaseManager.closeConnection(); } finally { // unlocks RequestLock and gives access to longest waiting thread RequestLock.unlock(); Logger.warn("Request to Minter Finished, UNLOCKING MINTER"); } // return to mint.jsp return "mint"; } /** * Maps to the admin panel on the home page. * * @return name of the index page */ @RequestMapping(value = {""}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}) public ModelAndView displayIndex() { ModelAndView model = new ModelAndView(); Logger.info("index page called"); model.addObject("prepend", Settings.getPrepend()); model.addObject("prefix", Settings.getPrefix()); model.addObject("charMap", Settings.getCharMap()); model.addObject("tokenType", Settings.getTokenType()); model.addObject("rootLength", Settings.getRootLength()); model.addObject("isAuto", Settings.isAuto()); model.addObject("isRandom", Settings.isRandom()); model.addObject("sansVowel", Settings.isSansVowels()); model.setViewName("settings"); return model; } /** * Because the minter construction checks the parameters for validity, this * method not only instantiates an AutoMinter but also checks whether or not * the requested amount of ids is valid. * * @param tempSettings The parameters of the minter given by the rest end * point and default values. * @param requestedAmount The amount of ids requested. * @return an AutoMinter * @throws BadParameterException thrown whenever a malformed or invalid * parameter is passed */ private Minter createAutoMinter(long requestedAmount, CachedSettings tempSettings) throws BadParameterException { Minter minter = new Minter(DatabaseManager, tempSettings.getPrepend(), tempSettings.getTokenType(), tempSettings.getRootLength(), tempSettings.getPrefix(), tempSettings.isSansVowels()); if (minter.isValidAmount(requestedAmount)) { return minter; } else { throw new BadParameterException(requestedAmount, "Requested Amount"); } } /** * Overrides the default value of cached value with values given in the * parameter. If the parameters do not contain any of the valid parameters, * the default values are maintained. * * @param parameters List of parameters given by the client. * @return The settings used for the particular session it was called. * @throws BadParameterException */ private CachedSettings overrideDefaults(Map<String, String> parameters) throws BadParameterException { CachedSettings tempSetting = new CachedSettings(Settings); if (parameters.containsKey("prepend")) { tempSetting.Prepend = parameters.get("prepend"); } if (parameters.containsKey("prefix")) { tempSetting.Prefix = (parameters.get("prefix")); } if (parameters.containsKey("rootLength")) { tempSetting.RootLength = (Integer.parseInt(parameters.get("rootLength"))); } if (parameters.containsKey("charMap")) { tempSetting.CharMap = (parameters.get("charMap")); } if (parameters.containsKey("tokenType")) { tempSetting.TokenType = getValidTokenType(parameters.get("tokenType")); } if (parameters.containsKey("auto")) { tempSetting.Auto = convertBoolean(parameters.get("auto"), "auto"); } if (parameters.containsKey("random")) { tempSetting.Random = convertBoolean(parameters.get("random"),"random"); } if (parameters.containsKey("sansVowels")) { tempSetting.SansVowels = convertBoolean(parameters.get("sansVowels"), "sansVowels"); } return tempSetting; } /** * Because the minter construction checks the parameters for validity, this * method not only instantiates a CustomMinter but also checks whether or * not the requested amount of ids is valid. * * @param tempSettings The parameters of the minter given by the rest end * point and default values. * @param requestedAmount The amount of ids requested. * @return a CustomMinter * @throws BadParameterException thrown whenever a malformed or invalid * parameter is passed */ private Minter createCustomMinter(long requestedAmount, CachedSettings tempSettings) throws BadParameterException { Minter minter = new Minter(DatabaseManager, tempSettings.getPrepend(), tempSettings.getCharMap(), tempSettings.getPrefix(), tempSettings.isSansVowels()); if (minter.isValidAmount(requestedAmount)) { return minter; } else { Logger.error("Request amount of " + requestedAmount + " IDs is unavailable"); throw new BadParameterException(requestedAmount, "Requested Amount"); } } /** * This method is used to check to see whether or not the given parameter is explicitly * equivalent to "true" or "false" and returns them respectively. The method * provided by the Boolean wrapper class converts all Strings that do no explictly * contain true to false. * @param parameter the given string to convert. * @param parameterType the type of the parameter. * @throws BadParameterException Thrown whenever a malformed parameter is formed or passed * @return the equivalent version of true or false. */ private boolean convertBoolean(String parameter, String parameterType) throws BadParameterException{ if(parameter.equals("true")){ return true; }else if(parameter.equals("false")){ return false; }else{ throw new BadParameterException(parameter, parameterType); } } /** * Returns a view that displays the error message of * NotEnoughPermutationsException. * * @param req The HTTP request. * @param exception NotEnoughPermutationsException. * @return The view of the error message in json format. */ @ExceptionHandler(NotEnoughPermutationsException.class) public ModelAndView handlePermutationError(HttpServletRequest req, Exception exception) { //logger.error("Request: " + req.getRequestURL() + " raised " + exception); ModelAndView mav = new ModelAndView(); mav.addObject("status", 400); mav.addObject("exception", exception.getClass().getSimpleName()); mav.addObject("message", exception.getMessage()); Logger.error("Error with permutation: " + exception.getMessage()); mav.setViewName("error"); return mav; } /** * Returns a view that displays the error message of BadParameterException. * * @param req The HTTP request. * @param exception BadParameterException. * @return The view of the error message in json format. */ @ExceptionHandler(BadParameterException.class) public ModelAndView handleBadParameterError(HttpServletRequest req, Exception exception) { //logger.error("Request: " + req.getRequestURL() + " raised " + exception); ModelAndView mav = new ModelAndView(); mav.addObject("status", 400); mav.addObject("exception", exception.getClass().getSimpleName()); mav.addObject("message", exception.getMessage()); Logger.error("Error with bad parameter: " + exception.getMessage()); mav.setViewName("error"); return mav; } /** * Throws any exception that may be caught within the program * * @param req the HTTP request * @param exception the caught exception * @return The view of the error message */ @ExceptionHandler(Exception.class) public ModelAndView handleGeneralError(HttpServletRequest req, Exception exception) { ModelAndView mav = new ModelAndView(); mav.addObject("status", 500); mav.addObject("exception", exception.getClass().getSimpleName()); mav.addObject("message", exception.getMessage()); Logger.error("Error" + "General Error: " + exception.getMessage()); mav.setViewName("error"); return mav; } /** * Gets the current length of the queue of RequestLock * * @return length of the queue */ public int getRequestLockQueueLength() { return this.RequestLock.getQueueLength(); } /** * Creates a Json object based off a list of ids given in the parameter * * @param list A list of ids to display into JSON * @param prepend A value to attach to the beginning of every id. Typically * used to determine the format of the id. For example, ARK or DOI. * @return A reference to a String that contains Json list of ids * @throws IOException thrown whenever a file could not be found */ public String convertListToJson(Set<Id> list, String prepend) throws IOException { // Jackson objects to create formatted Json string String jsonString = ""; ObjectMapper mapper = new ObjectMapper(); Object formattedJson; // Object used to iterate through list of ids Iterator<Id> iterator = list.iterator(); for (int i = 0; iterator.hasNext(); i++) { // Creates desired JSON format and adds the prepended string to be displayed String id = String.format("{\"id\":%d,\"name\":\"%s%s\"}", i, prepend, iterator.next()); formattedJson = mapper.readValue(id, Object.class); // append formatted json jsonString += mapper.writerWithDefaultPrettyPrinter(). writeValueAsString(formattedJson) + "\n"; } return jsonString; } /** * Attempts to convert a string into an equivalent enum TokenType. * * @param tokenType Designates what characters are contained in the id's * root. * @return Returns the enum type if succesful, throws BadParameterException * otherwise. * @throws BadParameterException thrown whenever a malformed or invalid * parameter is passed */ public final TokenType getValidTokenType(String tokenType) throws BadParameterException { switch (tokenType) { case "DIGIT": return TokenType.DIGIT; case "LOWERCASE": return TokenType.LOWERCASE; case "UPPERCASE": return TokenType.UPPERCASE; case "MIXEDCASE": return TokenType.MIXEDCASE; case "LOWER_EXTENDED": return TokenType.LOWER_EXTENDED; case "UPPER_EXTENDED": return TokenType.UPPER_EXTENDED; case "MIXED_EXTENDED": return TokenType.MIXED_EXTENDED; default: throw new BadParameterException(tokenType, "TokenType"); } } /** * A class used to store the minter settings of a given session. */ private class CachedSettings { // Fields; detailed description in Minter class private String Prepend; private String Prefix; private TokenType TokenType; private String CharMap; private int RootLength; private boolean SansVowels; private boolean Auto; private boolean Random; /** * Copy constructor * * @param s the CachedSetting to copy */ public CachedSettings(CachedSettings s) { Prepend = s.getPrepend(); Prefix = s.getPrefix(); TokenType = s.getTokenType(); CharMap = s.getCharMap(); RootLength = s.getRootLength(); SansVowels = s.isSansVowels(); Auto = s.isAuto(); Random = s.isRandom(); } /** * Default constructor */ public CachedSettings() { } /** * Retrieves the default settings stored in a database * * @throws SQLException thrown whenever there is an error with the * database. * @throws BadParameterException thrown whenever a malformed or invalid * parameter is passed */ public void retrieveSettings() throws SQLException, BadParameterException { Prepend = (String) DatabaseManager.retrieveSetting(DatabaseManager.getPREPEND_COLUMN()); Prefix = (String) DatabaseManager.retrieveSetting(DatabaseManager.getPREFIX_COLUMN()); if (Prepend == null) { Prepend = ""; } if (Prefix == null) { Prefix = ""; } TokenType = getValidTokenType((String) DatabaseManager.retrieveSetting( DatabaseManager.getTOKEN_TYPE_COLUMN())); CharMap = (String) DatabaseManager.retrieveSetting(DatabaseManager.getCHAR_MAP_COLUMN()); RootLength = (int) DatabaseManager.retrieveSetting(DatabaseManager.getROOT_LENGTH_COLUMN()); int autoFlag = (int) DatabaseManager.retrieveSetting(DatabaseManager.getAUTO_COLUMN()); int randomFlag = (int) DatabaseManager.retrieveSetting(DatabaseManager.getRANDOM_COLUMN()); int vowelFlag = (int) DatabaseManager.retrieveSetting(DatabaseManager.getSANS_VOWEL_COLUMN()); SansVowels = (vowelFlag == 1); Auto = (autoFlag == 1); Random = (randomFlag == 1); } @Override public String toString() { return String.format("prepend=%s\tprefix=%s\ttokenType=%s\tlength=%d\tcharMap=%s" + "\tauto=%b\trandom=%b\tsans%b", Prepend, Prefix, TokenType, RootLength, CharMap, Auto, Random, SansVowels); } // Typical getters and setters public String getPrepend() { return Prepend; } public void setPrepend(String Prepend) { this.Prepend = Prepend; } public String getPrefix() { return Prefix; } public void setPrefix(String Prefix) { this.Prefix = Prefix; } public TokenType getTokenType() { return TokenType; } public void setTokenType(TokenType TokenType) { this.TokenType = TokenType; } public String getCharMap() { return CharMap; } public void setCharMap(String CharMap) { this.CharMap = CharMap; } public int getRootLength() { return RootLength; } public void setRootLength(int RootLength) { this.RootLength = RootLength; } public boolean isSansVowels() { return SansVowels; } public void setSansVowels(boolean SansVowels) { this.SansVowels = SansVowels; } public boolean isAuto() { return Auto; } public void setAuto(boolean Auto) { this.Auto = Auto; } public boolean isRandom() { return Random; } public void setRandom(boolean Random) { this.Random = Random; } } }
package team.cs6365.payfive.model; import android.graphics.Bitmap; /* model object for menu item */ public class MenuItem { private String name, category, description; private double price; private Bitmap thumbnail; public MenuItem() { this("", "", "", 0.0, null); } public MenuItem(String name, String category, String description, double price, Bitmap thumbnail) { this.name = name; this.category = category; this.description = description; this.price = price; this.thumbnail = thumbnail; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Bitmap getThumbnail() { return thumbnail; } public void setThumbnail(Bitmap thumbnail) { this.thumbnail = thumbnail; } }
package com.kaltura.playersdk; import java.util.Timer; import java.util.TimerTask; import android.content.Context; import android.media.MediaPlayer; import android.net.Uri; import android.widget.VideoView; import com.kaltura.playersdk.events.OnPlayerStateChangeListener; import com.kaltura.playersdk.events.OnPlayheadUpdateListener; import com.kaltura.playersdk.events.OnProgressListener; import com.kaltura.playersdk.types.PlayerStates; public class PlayerView extends VideoView implements VideoPlayerInterface { //TODO make configurable public static int PLAYHEAD_UPDATE_INTERVAL = 200; private String mVideoUrl; private OnPlayerStateChangeListener mPlayerStateListener; private MediaPlayer.OnPreparedListener mPreparedListener; private OnPlayheadUpdateListener mPlayheadUpdateListener; private OnProgressListener mProgressListener; private Timer mTimer; public PlayerView(Context context) { super(context); super.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { pause(); seekTo( 0 ); updateStopState(); } }); super.setOnPreparedListener( new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { mPlayerStateListener.onStateChanged(PlayerStates.START); mediaPlayer.setOnSeekCompleteListener( new MediaPlayer.OnSeekCompleteListener() { @Override public void onSeekComplete(MediaPlayer mediaPlayer) { if ( mediaPlayer.isPlaying() ) { mPlayerStateListener.onStateChanged(PlayerStates.PLAY); } else { mPlayerStateListener.onStateChanged(PlayerStates.PAUSE); } } }); if ( mPreparedListener != null ) { mPreparedListener.onPrepared(mediaPlayer); } mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { @Override public void onBufferingUpdate(MediaPlayer mp, int progress) { if ( mProgressListener != null ) { mProgressListener.onProgressUpdate(progress); } } }); } }); } @Override public String getVideoUrl() { return mVideoUrl; } @Override public void setVideoUrl(String url) { mVideoUrl = url; super.setVideoURI(Uri.parse(url)); } @Override public int getDuration() { return super.getDuration(); } public int getCurrentPosition() { return super.getCurrentPosition(); } @Override public boolean getIsPlaying() { return super.isPlaying(); } @Override public void play() { if ( !this.isPlaying() ) { super.start(); if ( mTimer == null ) { mTimer = new Timer(); } mTimer.schedule(new TimerTask() { @Override public void run() { mPlayheadUpdateListener.onPlayheadUpdated(getCurrentPosition()); } }, 0, PLAYHEAD_UPDATE_INTERVAL); mPlayerStateListener.onStateChanged(PlayerStates.PLAY); } } @Override public void pause() { if ( this.isPlaying() ) { super.pause(); mPlayerStateListener.onStateChanged(PlayerStates.PAUSE); } } @Override public void stop() { super.stopPlayback(); updateStopState(); } private void updateStopState() { if ( mTimer != null ) { mTimer.cancel(); mTimer = null; } mPlayerStateListener.onStateChanged(PlayerStates.END); } @Override public void seek(int msec) { super.seekTo(msec); mPlayerStateListener.onStateChanged(PlayerStates.LOAD); } @Override public void registerPlayerStateChange( OnPlayerStateChangeListener listener) { mPlayerStateListener = listener; } @Override public void registerReadyToPlay( MediaPlayer.OnPreparedListener listener) { mPreparedListener = listener; } @Override public void registerError( MediaPlayer.OnErrorListener listener) { super.setOnErrorListener(listener); } @Override public void registerPlayheadUpdate( OnPlayheadUpdateListener listener ) { mPlayheadUpdateListener = listener; } @Override public void registerProgressUpdate ( OnProgressListener listener ) { mProgressListener = listener; } }
package com.diluv.catalejo.java.readers; import java.io.DataInputStream; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import com.diluv.catalejo.reader.MetadataReader; /** * This reader can scan Java class files, and determine which version of Java * they were compiled with. * * @author Tyler Hancock (Darkhax) */ public class JavaVersionReader implements MetadataReader { /** * A constant instance, which can be used to save memory. */ public static final MetadataReader JAVA_VERSION_READER = new JavaVersionReader(); @Override public void readArchiveEntry (Map<String, Object> metadata, ZipFile file, ZipEntry entry) throws Exception { if (entry.getName().endsWith(".class")) { this.addJavaVersion(metadata, this.getVersion(new DataInputStream(file.getInputStream(entry)))); } } /** * Gets a version string from a class file stream. * * @param in The input stream. * @return The version read. The invalid string is used for when an invalid * class is read. */ private String getVersion (DataInputStream in) { try { final int magic = in.readInt(); if (magic != 0xcafebabe) { return "invalid"; } final int minor = in.readUnsignedShort(); final int major = in.readUnsignedShort(); return major + "." + minor; } catch (final IOException e) { } return "invalid"; } /** * Safely adds a Java version to the set of known java versions for a * project. * * @param metadata The metadata to add the version to. * @param type The Java version type. */ private void addJavaVersion (Map<String, Object> metadata, String type) { final Set<String> types = (Set<String>) metadata.getOrDefault("JavaVersions", new HashSet<String>()); types.add(type); metadata.put("JavaVersions", types); } }
package com.kylantraynor.civilizations.groups; import org.bukkit.ChatColor; import mkremins.fanciful.civilizations.FancyMessage; public class GroupAction { private String name; private String tooltip; private String command; private ActionType type; private boolean enabled; public GroupAction(String name, String description, ActionType type, String command, boolean enabled){ this.name = name; this.tooltip = description; this.type = type; this.command = command; this.enabled = enabled; } public FancyMessage addTo(FancyMessage fm){ fm.then(this.name); if(type == ActionType.TOGGLE){ if(this.enabled){ fm.color(ChatColor.GREEN); } else { fm.color(ChatColor.RED); } if(command != null){ fm.command(command); } } else { if(this.enabled){ fm.color(ChatColor.GOLD); } else { fm.color(ChatColor.GRAY); } if(command != null && this.enabled){ if(this.type == ActionType.SUGGEST){ fm.suggest(command); } else { fm.command(command); } } } fm.tooltip(this.tooltip); return fm; } }
package com.rgi.routingnetworks; import com.rgi.common.BoundingBox; import com.rgi.common.Dimensions; import com.rgi.common.Pair; import com.rgi.common.coordinate.Coordinate; import com.rgi.common.coordinate.CoordinateReferenceSystem; import com.rgi.g2t.GeoTransformation; import com.rgi.store.routingnetworks.Edge; import com.rgi.store.routingnetworks.EdgeDirecctionality; import com.rgi.store.routingnetworks.Node; import com.rgi.store.routingnetworks.RoutingNetworkStoreException; import com.rgi.store.routingnetworks.RoutingNetworkStoreReader; import com.rgi.store.routingnetworks.NodeDimensionality; import org.gdal.gdal.Dataset; import org.gdal.gdal.gdal; import org.gdal.gdalconst.gdalconstConstants; import org.gdal.ogr.DataSource; import org.gdal.ogr.Feature; import org.gdal.ogr.Geometry; import org.gdal.ogr.Layer; import org.gdal.ogr.ogr; import org.gdal.ogr.ogrConstants; import org.gdal.osr.CoordinateTransformation; import org.gdal.osr.SpatialReference; import utility.GdalError; import utility.GdalUtility; import java.io.File; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * @author Luke Lambert */ public class DemRoutingNetworkStoreReader implements RoutingNetworkStoreReader { /** * Constructor * * @param file File containing the digital elevation model dataset * @param rasterBand Band of the raster to treat as elevation data * @param contourInterval Elevation interval (elevation values will be multiples of the interval) * @param noDataValue Value that indicates that a pixel contains no elevation data, and is to be ignored (nullable) * @param coordinatePrecision Number of decimal places to round the coordinates. A negative value will cause no rounding to occur * @param simplificationTolerance Tolerance used to simplify the contour rings that are used in the triangulation of the data * @param triangulationTolerance Snaps points that are within a tolerance's distance from one another (we THINK) * @throws RoutingNetworkStoreException thrown if the resulting network would contain invalid data */ public DemRoutingNetworkStoreReader(final File file, final int rasterBand, final double contourInterval, final Double noDataValue, final int coordinatePrecision, final double simplificationTolerance, final double triangulationTolerance) throws RoutingNetworkStoreException { final Dataset dataset = GdalUtility.open(file); final Dimensions<Double> metersPerPixel = this.getMetersPerPixel(dataset); // We cannot tile an image with no geo referencing information if(!GdalUtility.hasGeoReference(dataset)) { throw new IllegalArgumentException("Input raster image has no georeference."); } final SpatialReference spatialReference = new SpatialReference(dataset.GetProjection()); this.sourceSpatialReferenceIsNotWgs84 = spatialReference.IsSame(wgs84SpatialReference) == 0; this.sourceToWgs84Transformation = CoordinateTransformation.CreateCoordinateTransformation(new SpatialReference(dataset.GetProjection()), wgs84SpatialReference); this.coordinateReferenceSystem = GdalUtility.getCoordinateReferenceSystem(GdalUtility.getSpatialReference(dataset)); if(this.coordinateReferenceSystem == null) { throw new IllegalArgumentException("Image file is not in a recognized coordinate reference system"); } final DataSource dataSource = ogr.GetDriverByName("Memory") // Make constant .CreateDataSource("data source"); final Layer outputLayer = dataSource.CreateLayer("contours", spatialReference); // http://www.gdal.org/gdal__alg_8h.html#aceaf98ad40f159cbfb626988c054c085 final int gdalError = gdal.ContourGenerate(dataset.GetRasterBand(rasterBand), // Band srcBand - The band to read raster data from. The whole band will be processed contourInterval, // double contourInterval - The elevation interval between contours generated 0, // double contourBase - The "base" relative to which contour intervals are applied. This is normally zero, but could be different. To generate 10m contours at 5, 15, 25, ... the ContourBase would be 5 null, // double[] fixedLevels - The list of fixed contour levels at which contours should be generated. It will contain FixedLevelCount entries, and may be NULL (noDataValue == null) ? 0 : 1, // int useNoData - If TRUE the noDataValue will be used (noDataValue == null) ? 0.0 : noDataValue, // double noDataValue - The value to use as a "no data" value. That is, a pixel value which should be ignored in generating contours as if the value of the pixel were not known outputLayer, // Layer dstLayer - The layer to which new contour vectors will be written. Each contour will have a LINESTRING geometry attached to it -1, // int idField - If not -1 this will be used as a field index to indicate where a unique id should be written for each feature (contour) written -1, // int elevField - If not -1 this will be used as a field index to indicate where the elevation value of the contour should be written null); // ProgressCallback callback - A ProgressCallback that may be used to report progress to the user, or to interrupt the algorithm. May be NULL if not required if(gdalError != gdalconstConstants.CE_None) { throw new RuntimeException(new GdalError().getMessage()); } final Geometry pointCollection = new Geometry(ogrConstants.wkbMultiPoint);//pointCollectionFeature.GetGeometryRef(); for(Feature feature = outputLayer.GetNextFeature(); feature != null; feature = outputLayer.GetNextFeature()) { final Geometry originalGeometry = feature.GetGeometryRef(); // http://gdal.org/java/org/gdal/ogr/Geometry.html#SimplifyPreserveTopology(double) -> // This function is built on the GEOS library, check it for the definition of the geometry operation. If OGR is built without the GEOS library, this function will always fail, issuing a CPLE_NotSupported error. // All vertices in the simplified geometry will be within this distance of the original geometry. The tolerance value must be non-negative. A tolerance value of zero is effectively a no-op. final Geometry simplifiedGeometry = originalGeometry.SimplifyPreserveTopology(simplificationTolerance); // Topology preserving means in practice that parts of the multilinestring meet after simplification, polygons // do not have self-intersections, inner rings in polygons stay inside outer rings, etc. Especially for polygon // layers this method does not prevent gaps, overlaps, and slivers from appearing, even though this is the // general belief. I would say that the method has a misleading name which makes users to believe that it saves // the topology for the whole layer. However, the name and behaviour is the same in PostGIS and in JTS final int pointCount = simplifiedGeometry.GetPointCount(); for(int x = 0; x < pointCount; ++x) { final double[] point = simplifiedGeometry.GetPoint(x); final Geometry pointGeometry = new Geometry(ogrConstants.wkbPoint); pointGeometry.AddPoint(round(point[0], coordinatePrecision), round(point[1], coordinatePrecision), round(point[2], coordinatePrecision)); pointCollection.AddGeometry(pointGeometry); } } dataSource.delete(); // http://www.gdal.org/classOGRGeometry.html#ab7d3c3e5b033ca6bbb470016e7661da7 final Geometry triangulation = pointCollection.DelaunayTriangulation(triangulationTolerance, // double tolerance - optional snapping tolerance to use for improved robustness 1); // int onlyEdges - if TRUE, will return a MULTILINESTRING, otherwise it will return a GEOMETRYCOLLECTION containing triangular POLYGONs final double[] envelope = new double[4]; // minX, maxX, minY, maxY triangulation.GetEnvelope(envelope); this.bounds = new BoundingBox(envelope[0], envelope[2], envelope[1], envelope[3]); final int lineStringCount = triangulation.GetGeometryCount(); for(int x = 0; x < lineStringCount; ++x) { final Geometry edge = triangulation.GetGeometryRef(x); // Aline string that represents an edge in the Delaunay triangulation final Node node0 = this.getNode(edge.GetPoint(0)); final Node node1 = this.getNode(edge.GetPoint(1)); //noinspection FloatingPointEquality if(this.haversineDistance(new Coordinate<>(node0.getX(), node0.getY()), new Coordinate<>(node1.getX(), node1.getY())) <= 0.0) { throw new RoutingNetworkStoreException("Attempting to add an edge with a cartesian distance of 0"); } this.edges.add(new Edge(this.edges.size(), node0.getIdentifier(), node1.getIdentifier(), EdgeDirecctionality.TWO_WAY, Arrays.asList("footway"))); } this.description = String.format("Elevation model routing network generated from source data %s, band %d. Original pixel size was %fm x %fm. Contains %d nodes and %d edges. Created with parameters, contour interval: %s, pixel no data value: %s, contour simplification tolerance: %s, triangulation tolerance: %s.", file.getName(), rasterBand, metersPerPixel.getWidth(), metersPerPixel.getHeight(), this.nodes.size(), this.edges.size(), contourInterval, noDataValue, simplificationTolerance, triangulationTolerance); } private static double round(final double real, final int numberOfDecimalPlaces) { if(numberOfDecimalPlaces < 0) { return real; } return new BigDecimal(real).setScale(numberOfDecimalPlaces, RoundingMode.FLOOR) .doubleValue(); } private Dimensions<Double> getMetersPerPixel(final Dataset dataset) { final GeoTransformation transformation = new GeoTransformation(dataset.GetGeoTransform()); final BoundingBox bounds = transformation.getBounds(dataset); final double rasterWidthKilometers = this.haversineDistance(bounds.getBottomLeft(), bounds.getBottomRight()); final double rasterHeightKilometers = this.haversineDistance(bounds.getTopLeft(), bounds.getBottomLeft()); //noinspection MagicNumber // 1km = 1000m return new Dimensions<>((rasterWidthKilometers *1000.0) / (double)dataset.getRasterXSize(), (rasterHeightKilometers*1000.0) / (double)dataset.getRasterYSize()); } @Override public List<Pair<String, Type>> getNodeAttributeDescriptions() { return Collections.emptyList(); } @Override public List<Pair<String, Type>> getEdgeAttributeDescriptions() { return Arrays.asList(Pair.of("highway", String.class)); } @Override public List<Node> getNodes() { return Collections.unmodifiableList(this.nodes); } @Override public List<Edge> getEdges() { return Collections.unmodifiableList(this.edges); } @Override public CoordinateReferenceSystem getCoordinateReferenceSystem() { return this.coordinateReferenceSystem; } @Override public BoundingBox getBounds() { return this.bounds; } @Override public String getDescription() { return this.description; } @Override public NodeDimensionality getNodeDimensionality() { return NodeDimensionality.HAS_ELEVATION; } private Coordinate<Double> toWgs84(final double x, final double y) { if(this.sourceSpatialReferenceIsNotWgs84) { final double[] coordinate = this.sourceToWgs84Transformation.TransformPoint(x, y); return new Coordinate<>(coordinate[0], coordinate[1]); } return new Coordinate<>(x, y); } private Node getNode(final double[] coordinate) { final int coordinateHash = Arrays.hashCode(coordinate); final double longitude = coordinate[0]; final double latitude = coordinate[1]; final Double elevation = coordinate.length > 2 ? coordinate[2] : null; final String key = Double.toString(longitude) + '_' + Double.toString(latitude) + '_' + (elevation != null ? Double.toString(coordinate[2]) : ""); if(this.nodeMap.containsKey(key)) { return this.nodeMap.get(key); } final Node node = new Node(this.nodes.size(), longitude, latitude, elevation, Collections.emptyList()); this.nodes.add(node); this.nodeMap.put(key, node); return node; } private double haversineDistance(final Coordinate<Double> from, final Coordinate<Double> to) { final Coordinate<Double> coordinate0 = this.toWgs84(from.getX(), from.getY()); final Coordinate<Double> coordinate1 = this.toWgs84(to.getX(), to.getY()); final double fromLongitude = coordinate0.getX(); final double fromLatitude = coordinate0.getY(); final double toLongitude = coordinate1.getX(); final double toLatitude = coordinate1.getY(); final double dLat = Math.toRadians(toLatitude - fromLatitude); final double dLon = Math.toRadians(toLongitude - fromLongitude); final double fromLatitudeRadians = Math.toRadians(fromLatitude); final double toLatitudeRadians = Math.toRadians(toLatitude); // Pandolf equation literally calls these two values "a" and "c" final double a = haversin(dLat) + StrictMath.cos(fromLatitudeRadians) * StrictMath.cos(toLatitudeRadians) * haversin(dLon); final double c = 2 * StrictMath.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return RADIUS_OF_EARTH_KILOMETERS * c; } /** * The Haversine function * * @param value * The angle between to points in radians * * @return The haversine */ private static double haversin(final double value) { return StrictMath.pow(StrictMath.sin(value / 2), 2); } private final List<Node> nodes = new LinkedList<>(); private final List<Edge> edges = new LinkedList<>(); private final Map<String, Node> nodeMap = new TreeMap<>(); private final BoundingBox bounds; private final String description; private final CoordinateReferenceSystem coordinateReferenceSystem; private final CoordinateTransformation sourceToWgs84Transformation; private final boolean sourceSpatialReferenceIsNotWgs84; private static final double RADIUS_OF_EARTH_KILOMETERS = 6372.8; private static final int WGS84_EPSG_IDENTIFIER = 4326; private static final SpatialReference wgs84SpatialReference = new SpatialReference(); static { wgs84SpatialReference.ImportFromEPSG(WGS84_EPSG_IDENTIFIER); } // TODO when progress is implemented, we'll want to use something like the following: // private static class ScaledProgress extends ProgressCallback // private final double percentMinimum; // private final double percentMaximum; // private final ProgressCallback mainCallback; // ScaledProgress(final double percentMinimum, // final double percentMaximum, // final ProgressCallback mainCallback) // this.percentMinimum = percentMinimum; // this.percentMaximum = percentMaximum; // this.mainCallback = mainCallback; // @Override // public int run(final double percentComplete, // final String message) // return this.mainCallback // .run(this.percentMinimum + percentComplete * (this.percentMaximum - this.percentMinimum), // message); }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.util.Arrays; import java.util.List; import javax.swing.*; public final class MainPanel extends JPanel { public static final int MIN_TAB_WIDTH = 100; private MainPanel() { super(new BorderLayout()); JPanel p = new JPanel(new GridLayout(0, 1, 0, 2)); JTabbedPane tabbedPane1 = new JTabbedPane() { @Override public void removeTabAt(int index) { if (getTabCount() > 0) { setSelectedIndex(0); super.removeTabAt(index); setSelectedIndex(index - 1); } else { super.removeTabAt(index); } } }; JTabbedPane tabbedPane2 = new JTabbedPane() { private Component getScrollableViewport() { Component cmp = null; for (Component c : getComponents()) { if ("TabbedPane.scrollableViewport".equals(c.getName())) { cmp = c; break; } } return cmp; } private void resetViewportPosition(int idx) { if (getTabCount() <= 0) { return; } Component o = getScrollableViewport(); if (o instanceof JViewport) { JViewport viewport = (JViewport) o; JComponent c = (JComponent) viewport.getView(); c.scrollRectToVisible(getBoundsAt(idx)); } } @Override public void removeTabAt(int index) { if (getTabCount() > 0) { resetViewportPosition(0); super.removeTabAt(index); resetViewportPosition(index - 1); } else { super.removeTabAt(index); } } }; List<JTabbedPane> list = Arrays.asList(new JTabbedPane(), tabbedPane1, tabbedPane2); list.forEach(tabs -> { tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); tabs.addTab("00000000", new JLabel("0")); tabs.addTab("11111111", new JLabel("1")); tabs.addTab("22222222", new JLabel("2")); tabs.addTab("33333333", new JLabel("3")); tabs.addTab("44444444", new JLabel("4")); tabs.addTab("55555555", new JLabel("5")); tabs.addTab("66666666", new JLabel("6")); tabs.addTab("77777777", new JLabel("7")); tabs.addTab("88888888", new JLabel("8")); tabs.addTab("99999999", new JLabel("9")); tabs.setSelectedIndex(tabs.getTabCount() - 1); // // TEST: // EventQueue.invokeLater(() -> { // tabs.setSelectedIndex(tabs.getTabCount() - 1); p.add(tabs); }); JButton button = new JButton("Remove"); button.addActionListener(e -> { list.forEach(tabs -> { if (tabs.getTabCount() > 0) { tabs.removeTabAt(tabs.getTabCount() - 1); } }); }); add(p); add(button, BorderLayout.SOUTH); setPreferredSize(new Dimension(320, 240)); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGui(); } }); } public static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
package de.aima13.whoami.modules; import de.aima13.whoami.Analyzable; import de.aima13.whoami.support.DataSourceManager; import de.aima13.whoami.support.Utilities; import java.nio.file.Path; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; public class Sports implements Analyzable{ private List<Path> inputFiles = new ArrayList<Path>(); private TreeMap<String,Integer> sportPopularity = new TreeMap<String,Integer>(); private final String SPORTS_TITLE = "Sport"; private Sportart[] sportsList; /** * Modul arbeitet mit SQLite von Firefox oder Chrome * @return List der Strings die den Filter spezifizieren */ @Override public List<String> getFilter() { ArrayList<String> myFilters = new ArrayList<String>(); // SQLite Datenbanken der Browser myFilters.add("**Firefox**places.sqlite"); myFilters.add("**Google/Chrome**History"); return myFilters; } /** * Setzen der Pfad Objekte die behandelt werden sollen * @param files Liste der gefundenen Dateien * @throws Exception */ @Override public void setFileInputs(List<Path> files) throws Exception { inputFiles = files; } @Override public String getHtml() { Map.Entry mostPopularSport = Utilities.getHighestEntry(sportPopularity); if((Integer)mostPopularSport.getValue()<25){ return "Du scheinst dich nicht viel für Sport zu interessieren!"; } return "Warum auch immer interessiert du dich am meisten für "+ mostPopularSport.getKey() +"!" + getCommentAccordingToSport(mostPopularSport.getKey().toString()); } private String getCommentAccordingToSport(String sport) { for (Sportart s : sportsList){ if (s.sportart.equals(sport)){ return s.kommentar; } } return ""; } @Override public String getReportTitle() { return SPORTS_TITLE; } @Override public String getCsvPrefix() { return SPORTS_TITLE; } @Override public String[] getCsvHeaders() { return new String[]{"kind"}; } @Override public SortedMap<String, String> getCsvContent() { TreeMap<String,String> csvResult = new TreeMap<String,String>(); try { csvResult.put("kind",Utilities.getHighestEntry(sportPopularity).getKey().toString()); } catch (NoSuchElementException e) { return null; } return csvResult; } @Override public void run() { sportsList = Utilities.loadDataFromJson("/data/sport.json",Sportart[].class); for(Sportart s : sportsList){ sportPopularity.put(s.sportart,0); } for (Path p : this.inputFiles){ if (p.toString().contains("Firefox")){ handleBrowserHistory(p,"moz_places"); }else if(p.toString().contains("Google/Chrome")){ handleBrowserHistory(p,"urls"); } } } private void handleBrowserHistory(Path sqliteDB, String fromTable) { try { DataSourceManager dSm = new DataSourceManager(sqliteDB); for (Sportart s : sportsList){ String sqlStatement = "SELECT sum(visit_count) FROM " + fromTable+ " where title" + " LIKE '%"+ s.sportart+"%' OR url LIKE '%"+s.sportart+"%' "; if(s.zusatz !=null) { for (String addition : s.zusatz) { sqlStatement += "OR url LIKE '%" + addition + "%' "; sqlStatement += "OR title LIKE '%" + addition + "%' "; } } sqlStatement += ";"; ResultSet rs = dSm.querySqlStatement(sqlStatement); if(rs != null){ while (rs.next()){ sportPopularity.put(s.sportart, sportPopularity.get(s.sportart)+ rs.getInt(1)); } } } } catch (ClassNotFoundException e) { } catch (SQLException e) { } } // Klasse zum Laden der JSON Resource private class Sportart{ String sportart; String [] zusatz; String kommentar; @Override public String toString(){ return sportart + " Extras:"+Arrays.toString(zusatz); } } }
package com.battlelancer.seriesguide; public class Constants { /** THESE ARE NOT INCLUDED IN THE OPEN SOURCE CODE FOR SECURITY REASONS **/ public static final String API_KEY = ""; public static final String CONSUMER_KEY = ""; public static final String CONSUMER_SECRET = ""; public static final String TRAKT_API_KEY = ""; }
package org.nakedobjects.object; import org.nakedobjects.utility.Debug; import org.nakedobjects.utility.DebugString; import java.util.Enumeration; import java.util.Vector; public class Dump { private static void collectionGraph( final NakedCollection collection, final int level, final Vector recursiveElements, DebugString s) { if (recursiveElements.contains(collection)) { s.append("*\n"); } else { recursiveElements.addElement(collection); Enumeration e = ((NakedCollection) collection).elements(); while (e.hasMoreElements()) { graphIndent(s, level); NakedObject element = ((NakedObject) e.nextElement()); s.append(element); graph(element, level + 1, recursiveElements, s); } } } /** * Creates an ascii object graph diagram for the specified object, up to three levels deep. */ public static String graph(Naked object) { DebugString s = new DebugString(); graph(object, s); return s.toString(); } public static void graph(Naked object, DebugString s) { s.append(object); graph(object, 0, new Vector(25, 10), s); } private static void graph(final Naked object, final int level, final Vector ignoreObjects, DebugString info) { if (level > 3) { info.appendln("..."); // only go 3 levels? } else { info.blankLine(); if (object instanceof NakedCollection) { collectionGraph((NakedCollection) object, level, ignoreObjects, info); } else if (object instanceof NakedObject) { objectGraph((NakedObject) object, level, ignoreObjects, info); } else { // info.append("??? " + object); } } } /** * Creates an ascii object graph diagram for the specified object, up to three levels deep, and * not expanding any of the objects in the excludedObjects vector. */ public static String graph(Naked object, Vector excludedObjects) { DebugString s = new DebugString(); s.append(object); graph(object, 0, excludedObjects, s); return s.toString(); } private static void graphIndent(DebugString s, int level) { for (int indent = 0; indent < level; indent++) { s.append(Debug.indentString(4) + "|"); } s.append(Debug.indentString(4) + "+ } public static String object(Naked object) { DebugString s = new DebugString(); object(object, s); return s.toString(); } public static void object(Naked object, DebugString string) { string.appendln(0, "Specification", object.getSpecification().getFullName()); string.appendln(0, "Class", object.getObject() == null ? "none" : object.getObject().getClass().getName()); string.appendln(0, "Adapter", object.getClass().getName()); string.appendAsHexln(0, "Hash", object.hashCode()); string.appendln(0, "Title", object.titleString()); string.appendln(0, "Object", object.getObject()); if (object instanceof NakedObject) { NakedObject nakedObject = (NakedObject) object; string.appendln(0, "OID", nakedObject.getOid()); string.appendln(0, "State", nakedObject.getResolveState()); string.appendln(0, "Version", nakedObject.getVersion()); string.appendln(0, "Icon", nakedObject.getIconName()); string.appendln(0, "Persistable", nakedObject.persistable()); } } private static void objectGraph(final NakedObject object, final int level, final Vector ignoreObjects, DebugString s) { ignoreObjects.addElement(object); // work through all its fields NakedObjectField[] fields; fields = object.getSpecification().getFields(); for (int i = 0; i < fields.length; i++) { NakedObjectField field = fields[i]; Naked obj = object.getField(field); String name = field.getId(); graphIndent(s, level); if (obj == null) { s.append(name + ": null\n"); } else if (obj.getSpecification().isValue()) { s.append(name + ": " + obj); s.append("\n"); } else { if (ignoreObjects.contains(obj)) { s.append(name + ": " + obj + "*\n"); } else { s.append(name + ": " + obj); graph(obj, level + 1, ignoreObjects, s); } } } } public static String specification(Naked object) { DebugString s = new DebugString(); specification(object, s); return s.toString(); } public static void specification(Naked naked, DebugString debug) { NakedObjectSpecification specification = naked.getSpecification(); debug.appendTitle(specification.getClass().getName()); debug.appendln(0, "Full Name", specification.getFullName()); debug.appendln(0, "Short Name", specification.getShortName()); debug.appendln(0, "Plural Name", specification.getPluralName()); debug.appendln(0, "Singular Name", specification.getSingularName()); debug.blankLine(); debug.appendln(0, "Abstract", specification.isAbstract()); debug.appendln(0, "Lookup", specification.isLookup()); debug.appendln(0, "Object", specification.isObject()); debug.appendln(0, "Value", specification.isValue()); debug.appendln(0, "Persistable", specification.persistable()); if (specification.superclass() != null) { debug.appendln(0, "Superclass", specification.superclass().getFullName()); } debug.appendln(0, "Subclasses", specificationNames(specification.subclasses())); debug.appendln(0, "Interfaces", specificationNames(specification.interfaces())); debug.appendln("Fields"); specificationFields(specification, debug); debug.appendln("Object Actions"); specificationActionMethods(specification, debug); debug.appendln("Class Actions"); specificationClassMethods(specification, debug); } private static void specificationActionMethods(NakedObjectSpecification specification, DebugString debug) { Action[] userActions = specification.getObjectActions(Action.USER); Action[] explActions = specification.getObjectActions(Action.EXPLORATION); Action[] debActions = specification.getObjectActions(Action.DEBUG); specificationMethods(userActions, explActions, debActions, debug); } private static void specificationClassMethods(NakedObjectSpecification specification, DebugString debug) { Action[] userActions = specification.getClassActions(Action.USER); Action[] explActions = specification.getClassActions(Action.EXPLORATION); Action[] debActions = specification.getClassActions(Action.DEBUG); specificationMethods(userActions, explActions, debActions, debug); } private static void specificationFields(NakedObjectSpecification specification, DebugString debug) { NakedObjectField[] fields = specification.getFields(); if (fields.length == 0) { debug.appendln(4, "none"); } else { for (int i = 0; i < fields.length; i++) { NakedObjectField f = (NakedObjectField) fields[i]; debug.appendln(4, f.getName()); if(f.getDescription() != null && ! f.getDescription().equals("") ) { debug.appendln(12, "Description", f.getDescription()); } debug.appendln(8, f.getClass().getName()); debug.appendln(8, "ID", f.getId()); debug.appendln(8, "Type", (f.isCollection() ? "Collection" : f.isObject() ? "Object" : f.isValue() ? "Value" : "Unknown") + " (" + f.getSpecification().getFullName() + ")"); debug.appendln(8, "Flags", (f.isAuthorised() ? "Authorised " : "") + (f.isDerived() ? "Derived " : "") + (f.isHidden() ? "Hidden " : "") + (f.isMandatory() ? "Mandatory " : "")); Class[] extensions = f.getExtensions(); if(extensions.length > 0) { debug.appendln(12, "Extensions"); for (int j = 0; j < extensions.length; j++) { debug.appendln(16, extensions[j].getName()); } } } } } private static void specificationMethods(Action[] userActions, Action[] explActions, Action[] debActions, DebugString debug) { if (userActions.length == 0 && explActions.length == 0 && debActions.length == 0) { debug.append(" none\n"); } else { debug.appendln(4, "User actions"); for (int i = 0; i < userActions.length; i++) { actionDetails(debug, userActions[i]); } debug.appendln(4, "Exploration actions"); for (int i = 0; i < explActions.length; i++) { actionDetails(debug, explActions[i]); } debug.appendln(4, "Debug actions"); for (int i = 0; i < debActions.length; i++) { actionDetails(debug, debActions[i]); } } } private static void actionDetails(DebugString debug, Action f) { debug.appendln(8, f.getName()); if(f.getDescription() != null && ! f.getDescription().equals("") ) { debug.appendln(12, "Description", f.getDescription()); } debug.appendln(12, f.getClass().getName()); debug.appendln(12, "ID", f.getId()); // debug.appendln(12, "Returns", f.getReturnType() == null ? "Nothing" : f.getReturnType().getFullName()); NakedObjectSpecification[] parameters = f.getParameterTypes(); if(parameters.length == 0) { debug.appendln(12, "Parameters: none"); } else { debug.appendln(12, "Parameters"); } for (int j = 0; j < parameters.length; j++) { debug.appendln(16, parameters[j].getFullName()); } debug.appendln(12, "Target", f.getTarget()); Class[] extensions = f.getExtensions(); if(extensions.length > 0) { debug.appendln(12, "Extensions"); for (int j = 0; j < extensions.length; j++) { debug.appendln(16, extensions[j].getName()); } } } private static String[] specificationNames(NakedObjectSpecification[] specifications) { String[] names = new String[specifications.length]; for (int i = 0; i < names.length; i++) { names[i] = specifications[i].getFullName(); } return names; } }
package jug.retrofit; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.guava.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; import com.google.common.base.Optional; import com.google.gson.Gson; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; import retrofit.RestAdapter; import retrofit.client.Response; import retrofit.http.Body; import retrofit.http.POST; public class RetrofitPostTest { // Google's json converter (it's used internally in retrofit). Gson gson = new Gson(); /** * This is a very simple interface for a client. */ public static interface ClientInterface { /** * As a retrofit limitation, we cannot have <code>void</code> method, * but you can return a generic retrofit's {@link Response}, and ignore * it at runtime. * * @param toAdd the object to add * @return nothing useful. */ @POST("/things/") Response saveMyObjectToIdentifier(@Body MyObject toAdd); } /** * A simple bean to be serialized. */ public static class MyObject{ private String firstField; private Integer secondField; public Optional<String> getFirstField() { return Optional.fromNullable(firstField); } public Optional<Integer> getSecondField() { return Optional.fromNullable(secondField); } public static MyObject create(String firstField, Integer secondField) { MyObject toreturn = new MyObject(); toreturn.firstField = firstField; toreturn.secondField = secondField; return toreturn; } } // the fake server MockWebServer mockServer; String serverUrl; @Before public void setUp() throws Exception{ mockServer = new MockWebServer(); // star the server mockServer.play(); // get the server url serverUrl = mockServer.getUrl("/").toString(); } /** * Creates the client for the given url. * * @param url * the server url. * @return a client with {@link ClientInterface} interface. */ private ClientInterface createRetrofitClient(String url){ RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(url) .build(); return restAdapter.create(ClientInterface.class); } @Test public void shouldGetTheCorrectValueForGoodResponse() throws Exception { // prepare the server with canned response MockResponse mockResponse = new MockResponse(); mockResponse.setResponseCode(201); mockServer.enqueue(mockResponse); // get the client ClientInterface client = createRetrofitClient(serverUrl); // create object to save MyObject objectToSave = MyObject.create("I love JSON", 3); // invoke the method client.saveMyObjectToIdentifier(objectToSave); // verify that the request was made correctly RecordedRequest request = mockServer.takeRequest(); assertThat(request.getMethod()).isEqualTo("POST"); assertThat(request.getPath()).isEqualTo("/things/"); MyObject fromJson = convertFromJson(request.getBody(), MyObject.class); assertThat(fromJson.getFirstField()).contains("I love JSON"); assertThat(fromJson.getSecondField()).contains(3); } private MyObject convertFromJson(final byte[] body, final Class<MyObject> clazz) { String jsonBody = new String(body); return gson.fromJson(jsonBody, clazz); } }
package net.runelite.api; // Note: This class won't always be complete: these sprites were manually gathered // through the cache and widget inspector. Please add new sprites as you happen to use them. public final class SpriteID { public static final int RS2_CHATBOX_BUTTONS = 0; public static final int RS2_TABS_ROW_BOTTOM = 1; public static final int RS2_TABS_ROW_TOP = 2; public static final int RS2_CHATBOX_EDGE_TOP = 3; public static final int RS2_WINDOW_FRAME_EDGE_LEFT = 4; public static final int RS2_CHATBOX_EDGE_LEFT = 5; public static final int RS2_MINIMAP_FRAME_EDGE_RIGHT = 6; public static final int RS2_SIDE_PANEL_EDGES_LEFT_AND_RIGHT = 7; public static final int RS2_WINDOW_FRAME_EDGE_TOP = 8; public static final int RS2_MINIMAP_FRAME_EDGE_LEFT = 9; public static final int RS2_SIDE_PANEL_EDGE_LEFT_UPPER = 10; public static final int RS2_SIDE_PANEL_EDGE_LEFT_LOWER_JOINING_CHATBOX_EDGE_RIGHT = 11; public static final int RS2_MINIMAP_FRAME = 12; public static final int RS2_CHATBOX_BACKGROUND = 13; public static final int RS2_SIDE_PANEL_BACKGROUND = 14; public static final int SPELL_WIND_STRIKE = 15; public static final int SPELL_CONFUSE = 16; public static final int SPELL_WATER_STRIKE = 17; public static final int SPELL_LVL_1_ENCHANT = 18; public static final int SPELL_EARTH_STRIKE = 19; public static final int SPELL_WEAKEN = 20; public static final int SPELL_FIRE_STRIKE = 21; public static final int SPELL_BONES_TO_BANANAS = 22; public static final int SPELL_WIND_BOLT = 23; public static final int SPELL_CURSE = 24; public static final int SPELL_LOW_LEVEL_ALCHEMY = 25; public static final int SPELL_WATER_BOLT = 26; public static final int SPELL_VARROCK_TELEPORT = 27; public static final int SPELL_LVL_2_ENCHANT = 28; public static final int SPELL_EARTH_BOLT = 29; public static final int SPELL_LUMBRIDGE_TELEPORT = 30; public static final int SPELL_TELEKINETIC_GRAB = 31; public static final int SPELL_FIRE_BOLT = 32; public static final int SPELL_FALADOR_TELEPORT = 33; public static final int SPELL_CRUMBLE_UNDEAD = 34; public static final int SPELL_WIND_BLAST = 35; public static final int SPELL_SUPERHEAT_ITEM = 36; public static final int SPELL_CAMELOT_TELEPORT = 37; public static final int SPELL_WATER_BLAST = 38; public static final int SPELL_LVL_3_ENCHANT = 39; public static final int SPELL_EARTH_BLAST = 40; public static final int SPELL_HIGH_LEVEL_ALCHEMY = 41; public static final int SPELL_CHARGE_WATER_ORB = 42; public static final int SPELL_LVL_4_ENCHANT = 43; public static final int SPELL_FIRE_BLAST = 44; public static final int SPELL_CHARGE_EARTH_ORB = 45; public static final int SPELL_WIND_WAVE = 46; public static final int SPELL_CHARGE_FIRE_ORB = 47; public static final int SPELL_WATER_WAVE = 48; public static final int SPELL_CHARGE_AIR_ORB = 49; public static final int SPELL_LVL_5_ENCHANT = 50; public static final int SPELL_EARTH_WAVE = 51; public static final int SPELL_FIRE_WAVE = 52; public static final int SPELL_IBAN_BLAST = 53; public static final int SPELL_ARDOUGNE_TELEPORT = 54; public static final int SPELL_WATCHTOWER_TELEPORT = 55; public static final int SPELL_VULNERABILITY = 56; public static final int SPELL_ENFEEBLE = 57; public static final int SPELL_STUN = 58; public static final int SPELL_FLAMES_OF_ZAMORAK = 59; public static final int SPELL_CLAWS_OF_GUTHIC = 60; public static final int SPELL_SARADOMIN_STRIKE = 61; public static final int UNUSED_SPELL_CALL_ANIMAL = 62; public static final int UNUSED_SPELL_RAISE_SKELETON = 63; public static final int UNUSED_SPELL_SUMMON_DEMON = 64; public static final int SPELL_WIND_STRIKE_DISABLED = 65; public static final int SPELL_CONFUSE_DISABLED = 66; public static final int SPELL_WATER_STRIKE_DISABLED = 67; public static final int SPELL_LVL_1_ENCHANT_DISABLED = 68; public static final int SPELL_EARTH_STRIKE_DISABLED = 69; public static final int SPELL_WEAKEN_DISABLED = 70; public static final int SPELL_FIRE_STRIKE_DISABLED = 71; public static final int SPELL_BONES_TO_BANANAS_DISABLED = 72; public static final int SPELL_WIND_BOLT_DISABLED = 73; public static final int SPELL_CURSE_DISABLED = 74; public static final int SPELL_LOW_LEVEL_ALCHEMY_DISABLED = 75; public static final int SPELL_WATER_BOLT_DISABLED = 76; public static final int SPELL_VARROCK_TELEPORT_DISABLED = 77; public static final int SPELL_LVL_2_ENCHANT_DISABLED = 78; public static final int SPELL_EARTH_BOLT_DISABLED = 79; public static final int SPELL_LUMBRIDGE_TELEPORT_DISABLED = 80; public static final int SPELL_TELEKINETIC_GRAB_DISABLED = 81; public static final int SPELL_FIRE_BOLT_DISABLED = 82; public static final int SPELL_FALADOR_TELEPORT_DISABLED = 83; public static final int SPELL_CRUMBLE_UNDEAD_DISABLED = 84; public static final int SPELL_WIND_BLAST_DISABLED = 85; public static final int SPELL_SUPERHEAT_ITEM_DISABLED = 86; public static final int SPELL_CAMELOT_TELEPORT_DISABLED = 87; public static final int SPELL_WATER_BLAST_DISABLED = 88; public static final int SPELL_LVL_3_ENCHANT_DISABLED = 89; public static final int SPELL_EARTH_BLAST_DISABLED = 90; public static final int SPELL_HIGH_LEVEL_ALCHEMY_DISABLED = 91; public static final int SPELL_CHARGE_WATER_ORB_DISABLED = 92; public static final int SPELL_LVL_4_ENCHANT_DISABLED = 93; public static final int SPELL_FIRE_BLAST_DISABLED = 94; public static final int SPELL_CHARGE_EARTH_ORB_DISABLED = 95; public static final int SPELL_WIND_WAVE_DISABLED = 96; public static final int SPELL_CHARGE_FIRE_ORB_DISABLED = 97; public static final int SPELL_WATER_WAVE_DISABLED = 98; public static final int SPELL_CHARGE_AIR_ORB_DISABLED = 99; public static final int SPELL_LVL_5_ENCHANT_DISABLED = 100; public static final int SPELL_EARTH_WAVE_DISABLED = 101; public static final int SPELL_FIRE_WAVE_DISABLED = 102; public static final int SPELL_IBAN_BLAST_DISABLED = 103; public static final int SPELL_ARDOUGNE_TELEPORT_DISABLED = 104; public static final int SPELL_WATCHTOWER_TELEPORT_DISABLED = 105; public static final int SPELL_VULNERABILITY_DISABLED = 106; public static final int SPELL_ENFEEBLE_DISABLED = 107; public static final int SPELL_STUN_DISABLED = 108; public static final int SPELL_FLAMES_OF_ZAMORAK_DISABLED = 109; public static final int SPELL_CLAWS_OF_GUTHIC_DISABLED = 110; public static final int SPELL_SARADOMIN_STRIKE_DISABLED = 111; public static final int UNUSED_SPELL_CALL_ANIMAL_DISABLED = 112; public static final int UNUSED_SPELL_RAISE_SKELETON_DISABLED = 113; public static final int UNUSED_SPELL_SUMMON_DEMON_DISABLED = 114; public static final int PRAYER_THICK_SKIN = 115; public static final int PRAYER_BURST_OF_STRENGTH = 116; public static final int PRAYER_CLARITY_OF_THOUGHT = 117; public static final int PRAYER_ROCK_SKIN = 118; public static final int PRAYER_SUPERHUMAN_STRENGTH = 119; public static final int PRAYER_IMPROVED_REFLEXES = 120; public static final int PRAYER_RAPID_RESTORE = 121; public static final int PRAYER_RAPID_HEAL = 122; public static final int PRAYER_PROTECT_ITEM = 123; public static final int PRAYER_STEEL_SKIN = 124; public static final int PRAYER_ULTIMATE_STRENGTH = 125; public static final int PRAYER_INCREDIBLE_REFLEXES = 126; public static final int PRAYER_PROTECT_FROM_MAGIC = 127; public static final int PRAYER_PROTECT_FROM_MISSILES = 128; public static final int PRAYER_PROTECT_FROM_MELEE = 129; public static final int PRAYER_REDEMPTION = 130; public static final int PRAYER_RETRIBUTION = 131; public static final int PRAYER_SMITE = 132; public static final int PRAYER_SHARP_EYE = 133; public static final int PRAYER_MYSTIC_WILL = 134; public static final int PRAYER_THICK_SKIN_DISABLED = 135; public static final int PRAYER_BURST_OF_STRENGTH_DISABLED = 136; public static final int PRAYER_CLARITY_OF_THOUGHT_DISABLED = 137; public static final int PRAYER_ROCK_SKIN_DISABLED = 138; public static final int PRAYER_SUPERHUMAN_STRENGTH_DISABLED = 139; public static final int PRAYER_IMPROVED_REFLEXES_DISABLED = 140; public static final int PRAYER_RAPID_RESTORE_DISABLED = 141; public static final int PRAYER_RAPID_HEAL_DISABLED = 142; public static final int PRAYER_PROTECT_ITEM_DISABLED = 143; public static final int PRAYER_STEEL_SKIN_DISABLED = 144; public static final int PRAYER_ULTIMATE_STRENGTH_DISABLED = 145; public static final int PRAYER_INCREDIBLE_REFLEXES_DISABLED = 146; public static final int PRAYER_PROTECT_FROM_MAGIC_DISABLED = 147; public static final int PRAYER_PROTECT_FROM_MISSILES_DISABLED = 148; public static final int PRAYER_PROTECT_FROM_MELEE_DISABLED = 149; public static final int PRAYER_REDEMPTION_DISABLED = 150; public static final int PRAYER_RETRIBUTION_DISABLED = 151; public static final int PRAYER_SMITE_DISABLED = 152; public static final int PRAYER_SHARP_EYE_DISABLED = 153; public static final int PRAYER_MYSTIC_WILL_DISABLED = 154; public static final int ACTIVATED_PRAYER_BACKGROUND = 155; public static final int EQUIPMENT_SLOT_HEAD = 156; public static final int EQUIPMENT_SLOT_CAPE = 157; public static final int EQUIPMENT_SLOT_NECK = 158; public static final int EQUIPMENT_SLOT_WEAPON = 159; public static final int EQUIPMENT_SLOT_RING = 160; public static final int EQUIPMENT_SLOT_TORSO = 161; public static final int EQUIPMENT_SLOT_SHIELD = 162; public static final int EQUIPMENT_SLOT_LEGS = 163; public static final int EQUIPMENT_SLOT_HANDS = 164; public static final int EQUIPMENT_SLOT_FEET = 165; public static final int EQUIPMENT_SLOT_AMMUNITION = 166; /* Unmapped: 167 */ public static final int TAB_COMBAT = 168; public static final int COMPASS_TEXTURE = 169; public static final int EQUIPMENT_SLOT_TILE = 170; public static final int IRON_RIVETS_SQUARE = 171; public static final int IRON_RIVETS_VERTICAL = 172; public static final int IRON_RIVETS_HORIZONTAL = 173; public static final int STATS_TILE_HALF_LEFT = 174; public static final int STATS_TILE_HALF_RIGHT_WITH_SLASH = 175; public static final int STATS_TILE_HALF_RIGHT = 176; public static final int STATS_TILE_HALF_LEFT_SELECTED = 177; public static final int STATS_TILE_HALF_RIGHT_SELECTED = 178; public static final int EQUIPMENT_SLOT_SELECTED = 179; public static final int PURO_PURO_ROUND_CHECK_BOX = 180; public static final int PURO_PURO_ROUND_CHECK_BOX_CHECKED_RED = 181; public static final int STATS_TILE_HALF_RIGHT_WITH_SLASH_SELECTED = 182; public static final int STATS_TILE_HALF_LEFT_BLACK = 183; public static final int STATS_TILE_HALF_RIGHT_BLACK = 184; public static final int MUSIC_PLAYER_BUTTON = 185; public static final int MUSIC_PLAYER_BUTTON_SELECTED = 186; /* Unmapped: 187~194 */ public static final int UNKNOWN_BUTTON_SQUARE_SMALL = 195; public static final int UNKNOWN_BUTTON_SQUARE_SMALL_SELECTED = 196; public static final int SKILL_ATTACK = 197; public static final int SKILL_STRENGTH = 198; public static final int SKILL_DEFENCE = 199; public static final int SKILL_RANGED = 200; public static final int SKILL_PRAYER = 201; public static final int SKILL_MAGIC = 202; public static final int SKILL_HITPOINTS = 203; public static final int SKILL_AGILITY = 204; public static final int SKILL_HERBLORE = 205; public static final int SKILL_THIEVING = 206; public static final int SKILL_CRAFTING = 207; public static final int SKILL_FLETCHING = 208; public static final int SKILL_MINING = 209; public static final int SKILL_SMITHING = 210; public static final int SKILL_FISHING = 211; public static final int SKILL_COOKING = 212; public static final int SKILL_FIREMAKING = 213; public static final int SKILL_WOODCUTTING = 214; public static final int SKILL_RUNECRAFT = 215; public static final int SKILL_SLAYER = 216; public static final int SKILL_FARMING = 217; public static final int UNKNOWN_SHOVEL = 218; public static final int RAT_PITS_ZONE_RAT = 219; public static final int SKILL_HUNTER = 220; public static final int SKILL_CONSTRUCTION = 221; public static final int SKILL_TOTAL = 222; public static final int UNKNOWN_EMPTY_VIAL = 223; public static final int UNKNOWN_DRAGON_DAGGER_P = 224; /* Unmapped: 225~232 */ public static final int COMBAT_STYLE_AXE_BLOCK = 233; public static final int COMBAT_STYLE_AXE_CHOP = 234; public static final int COMBAT_STYLE_AXE_HACK = 235; public static final int COMBAT_STYLE_AXE_SMASH = 236; public static final int COMBAT_STYLE_SWORD_BLOCK = 237; public static final int COMBAT_STYLE_SWORD_SLASH = 238; public static final int COMBAT_STYLE_SWORD_CHOP = 239; public static final int COMBAT_STYLE_SWORD_STAB = 240; public static final int COMBAT_STYLE_SPEAR_LUNGE = 241; public static final int COMBAT_STYLE_SPEAR_POUND = 242; public static final int COMBAT_STYLE_MACE_BLOCK = 243; public static final int COMBAT_STYLE_MACE_PUMMEL = 244; public static final int COMBAT_STYLE_MACE_SPIKE = 245; public static final int COMBAT_STYLE_MACE_POUND = 246; public static final int COMBAT_STYLE_UNARMED_PUNCH = 247; public static final int COMBAT_STYLE_UNARMED_KICK = 248; public static final int COMBAT_STYLE_UNARMED_BLOCK = 249; public static final int COMBAT_STYLE_SPEAR_BLOCK = 250; public static final int COMBAT_STYLE_SPEAR_SWIPE = 251; public static final int COMBAT_STYLE_STAFF_BLOCK = 252; public static final int COMBAT_STYLE_HAMMER_BLOCK = 253; public static final int UNUSED_COMBAT_STYLE_HAMMER = 254; public static final int COMBAT_STYLE_HAMMER_POUND = 255; public static final int COMBAT_STYLE_HAMMER_PUMMEL = 256; public static final int UNUSED_COMBAT_STYLE_STAKE = 257; public static final int COMBAT_STYLE_CROSSBOW_ACCURATE = 258; public static final int COMBAT_STYLE_CROSSBOW_RAPID = 259; public static final int COMBAT_STYLE_CROSSBOW_LONGRANGE = 260; public static final int COMBAT_STYLE_SCYTHE_BLOCK = 261; public static final int COMBAT_STYLE_SCYTHE_CHOP = 262; public static final int COMBAT_STYLE_MAGIC_ACCURATE = 263; public static final int COMBAT_STYLE_MAGIC_RAPID = 264; public static final int COMBAT_STYLE_MAGIC_LONGRANGE = 265; public static final int COMBAT_STYLE_STAFF_BASH = 266; public static final int COMBAT_STYLE_STAFF_POUND = 267; public static final int COMBAT_STYLE_BOW_ACCURATE = 268; public static final int COMBAT_STYLE_BOW_RAPID = 269; public static final int COMBAT_STYLE_BOW_LONGRANGE = 270; public static final int COMBAT_STYLE_SCYTHE_JAB = 271; public static final int COMBAT_STYLE_SCYTHE_REAP = 272; public static final int COMBAT_STYLE_PICKAXE_BLOCK = 273; public static final int COMBAT_STYLE_PICKAXE_SPIKE = 274; public static final int COMBAT_STYLE_PICKAXE_SMASH = 275; public static final int COMBAT_STYLE_PICKAXE_IMPALE = 276; public static final int COMBAT_STYLE_CLAWS_LUNGE = 277; public static final int COMBAT_STYLE_CLAWS_SLASH = 278; public static final int COMBAT_STYLE_CLAWS_CHOP = 279; public static final int COMBAT_STYLE_CLAWS_BLOCK = 280; public static final int COMBAT_STYLE_CHINCHOMPA_LONG_FUSE = 281; public static final int COMBAT_STYLE_CHINCHOMPA_MEDIUM_FUSE = 282; public static final int COMBAT_STYLE_HALBERD_BLOCK = 283; public static final int COMBAT_STYLE_HALBERD_JAB = 284; public static final int COMBAT_STYLE_HALBERD_SWIPE = 285; public static final int COMBAT_STYLE_WHIP_FLICK = 286; public static final int COMBAT_STYLE_WHIP_LASH = 287; public static final int COMBAT_STYLE_CHINCHOMPA_SHORT_FUSE = 288; public static final int COMBAT_STYLE_SALAMANDER_SCORCH = 289; public static final int COMBAT_STYLE_SALAMANDER_FLARE = 290; public static final int COMBAT_STYLE_SALAMANDER_BLAZE = 291; /* Unmapped: 292 */ public static final int COMBAT_STYLE_BUTTON_NARROW = 293; public static final int COMBAT_STYLE_BUTTON_NARROW_SELECTED = 294; public static final int COMBAT_STYLE_BUTTON_THIN = 295; public static final int COMBAT_STYLE_BUTTON_THIN_SELECTED = 296; public static final int DIALOG_BACKGROUND = 297; public static final int RS2_HITSPLAT_BLUE_NO_DAMAGE = 298; public static final int RS2_YELLOW_CLICK_ANIMATION_1 = 299; public static final int RS2_MINIMAP_MARKER_RED_ITEM = 300; public static final int RS2_SWORD_POINTED_LEFT = 301; public static final int RS2_SWORD_POINTED_RIGHT = 302; public static final int RS2_SWORD_POINTED_RIGHT_SHADOWED = 303; public static final int RS2_SWORD_POINTED_LEFT_SHADOWED = 304; public static final int RS2_TAB_STONE_FAR_LEFT_SELECTED = 305; public static final int RS2_TAB_STONE_MIDDLE_LEFT_SELECTED = 306; public static final int RS2_TAB_STONE_MIDDLE_SELECTED = 307; public static final int RS2_BUTTON_BACK_ARROW = 308; public static final int RS2_BUTTON_FORWARD_ARROW = 309; public static final int IRON_RIVETS_CORNER_TOP_LEFT = 310; public static final int IRON_RIVETS_CORNER_TOP_RIGHT = 311; public static final int IRON_RIVETS_CORNER_BOTTOM_LEFT = 312; public static final int IRON_RIVETS_CORNER_BOTTOM_RIGHT = 313; public static final int IRON_RIVETS_EDGE_TOP = 314; public static final int IRON_RIVETS_EDGE_RIGHT = 315; public static final int RS2_SCROLLBAR_ARROW_UP = 316; public static final int MAP_ICON_SMALL_TREE = 317; public static final int TEXTURE_INFERNAL_CAPE = 318; public static final int SPELL_BIND = 319; public static final int SPELL_SNARE = 320; public static final int SPELL_ENTANGLE = 321; public static final int SPELL_CHARGE = 322; public static final int SPELL_TROLLHEIM_TELEPORT = 323; public static final int SPELL_MAGIC_DART = 324; public static final int SPELL_ICE_RUSH = 325; public static final int SPELL_ICE_BURST = 326; public static final int SPELL_ICE_BLITZ = 327; public static final int SPELL_ICE_BARRAGE = 328; public static final int SPELL_SMOKE_RUSH = 329; public static final int SPELL_SMOKE_BURST = 330; public static final int SPELL_SMOKE_BLITZ = 331; public static final int SPELL_SMOKE_BARRAGE = 332; public static final int SPELL_BLOOD_RUSH = 333; public static final int SPELL_BLOOD_BURST = 334; public static final int SPELL_BLOOD_BLITZ = 335; public static final int SPELL_BLOOD_BARRAGE = 336; public static final int SPELL_SHADOW_RUSH = 337; public static final int SPELL_SHADOW_BURST = 338; public static final int SPELL_SHADOW_BLITZ = 339; public static final int SPELL_SHADOW_BARRAGE = 340; public static final int SPELL_PADDEWWA_TELEPORT = 341; public static final int SPELL_SENNTISTEN_TELEPORT = 342; public static final int SPELL_KHARYRLL_TELEPORT = 343; public static final int SPELL_LASSAR_TELEPORT = 344; public static final int SPELL_DAREEYAK_TELEPORT = 345; public static final int SPELL_CARRALLANGAR_TELEPORT = 346; public static final int SPELL_ANNAKARL_TELEPORT = 347; public static final int SPELL_GHORROCK_TELEPORT = 348; public static final int SPELL_TELEOTHER_LUMBRIDGE = 349; public static final int SPELL_TELEOTHER_FALADOR = 350; public static final int SPELL_TELEOTHER_CAMELOT = 351; public static final int SPELL_TELE_BLOCK = 352; public static final int SPELL_LVL_6_ENCHANT = 353; public static final int SPELL_BONES_TO_PEACHES = 354; public static final int SPELL_TELEPORT_TO_HOUSE = 355; public static final int SPELL_LUMBRIDGE_HOME_TELEPORT = 356; public static final int SPELL_TELEPORT_TO_APE_ATOLL = 357; public static final int SPELL_ENCHANT_CROSSBOW_BOLT = 358; public static final int SPELL_TELEPORT_TO_BOUNTY_TARGET = 359; public static final int SPELL_TELEPORT_TO_KOUREND = 360; public static final int SPELL_LVL_7_ENCHANT = 361; public static final int SPELL_WIND_SURGE = 362; public static final int SPELL_WATER_SURGE = 363; public static final int SPELL_EARTH_SURGE = 364; public static final int SPELL_FIRE_SURGE = 365; /* Unmapped: 366, 367, 368 */ public static final int SPELL_BIND_DISABLED = 369; public static final int SPELL_SNARE_DISABLED = 370; public static final int SPELL_ENTANGLE_DISABLED = 371; public static final int SPELL_CHARGE_DISABLED = 372; public static final int SPELL_TROLLHEIM_TELEPORT_DISABLED = 373; public static final int SPELL_MAGIC_DART_DISABLED = 374; public static final int SPELL_ICE_RUSH_DISABLED = 375; public static final int SPELL_ICE_BURST_DISABLED = 376; public static final int SPELL_ICE_BLITZ_DISABLED = 377; public static final int SPELL_ICE_BARRAGE_DISABLED = 378; public static final int SPELL_SMOKE_RUSH_DISABLED = 379; public static final int SPELL_SMOKE_BURST_DISABLED = 380; public static final int SPELL_SMOKE_BLITZ_DISABLED = 381; public static final int SPELL_SMOKE_BARRAGE_DISABLED = 382; public static final int SPELL_BLOOD_RUSH_DISABLED = 383; public static final int SPELL_BLOOD_BURST_DISABLED = 384; public static final int SPELL_BLOOD_BLITZ_DISABLED = 385; public static final int SPELL_BLOOD_BARRAGE_DISABLED = 386; public static final int SPELL_SHADOW_RUSH_DISABLED = 387; public static final int SPELL_SHADOW_BURST_DISABLED = 388; public static final int SPELL_SHADOW_BLITZ_DISABLED = 389; public static final int SPELL_SHADOW_BARRAGE_DISABLED = 390; public static final int SPELL_PADDEWWA_TELEPORT_DISABLED = 391; public static final int SPELL_SENNTISTEN_TELEPORT_DISABLED = 392; public static final int SPELL_KHARYRLL_TELEPORT_DISABLED = 393; public static final int SPELL_LASSAR_TELEPORT_DISABLED = 394; public static final int SPELL_DAREEYAK_TELEPORT_DISABLED = 395; public static final int SPELL_CARRALLANGAR_TELEPORT_DISABLED = 396; public static final int SPELL_ANNAKARL_TELEPORT_DISABLED = 397; public static final int SPELL_GHORROCK_TELEPORT_DISABLED = 398; public static final int SPELL_TELEOTHER_LUMBRIDGE_DISABLED = 399; public static final int SPELL_TELEOTHER_FALADOR_DISABLED = 400; public static final int SPELL_TELEOTHER_CAMELOT_DISABLED = 401; public static final int SPELL_TELE_BLOCK_DISABLED = 402; public static final int SPELL_LVL_6_ENCHANT_DISABLED = 403; public static final int SPELL_BONES_TO_PEACHES_DISABLED = 404; public static final int SPELL_TELEPORT_TO_HOUSE_DISABLED = 405; public static final int SPELL_LUMBRIDGE_HOME_TELEPORT_DISABLED = 406; public static final int SPELL_TELEPORT_TO_APE_ATOLL_DISABLED = 407; public static final int SPELL_ENCHANT_CROSSBOW_BOLT_DISABLED = 408; public static final int SPELL_TELEPORT_TO_BOUNTY_TARGET_DISABLED = 409; public static final int SPELL_TELEPORT_TO_KOUREND_DISABLED = 410; public static final int SPELL_LVL_7_ENCHANT_DISABLED = 411; public static final int SPELL_WIND_SURGE_DISABLED = 412; public static final int SPELL_WATER_SURGE_DISABLED = 413; public static final int SPELL_EARTH_SURGE_DISABLED = 414; public static final int SPELL_FIRE_SURGE_DISABLED = 415; /* Unmapped: 416, 417, 418 */ public static final int UNKNOWN_STANCE_ICON_1 = 419; public static final int UNKNOWN_STANCE_ICON_2 = 420; public static final int UNKNOWN_STANCE_ICON_3 = 421; public static final int MINIMAP_DESTINATION_FLAG = 422; public static final int CHATBOX_BADGE_CROWN_PLAYER_MODERATOR = 423; public static final int RED_GUIDE_ARROW = 424; public static final int BACK_ARROW_BUTTON_SMALL = 425; public static final int FORWARD_ARROW_BUTTON_SMALL = 426; public static final int UNKNOWN_X_3D_RENDER = 427; public static final int WELCOME_SCREEN_BUTTON_MARBLE = 428; public static final int WELCOME_SCREEN_BUTTON_CLICK_HERE_TO_PLAY = 429; public static final int WELCOME_SCREEN_BANK_CHEST = 430; public static final int WELCOME_SCREEN_COINS = 431; public static final int WELCOME_SCREEN_KEY = 432; public static final int WELCOME_SCREEN_KEYRING = 433; public static final int WELCOME_SCREEN_PEN_AND_INKPOT = 434; public static final int WELCOME_SCREEN_SWORD = 435; public static final int WELCOME_SCREEN_SCROLL_MESSAGE_OF_THE_WEEK = 436; public static final int WELCOME_SCREEN_SEALED_ENVELOPE = 437; public static final int WELCOME_SCREEN_BUTTON_COBBLESTONE = 438; public static final int PLAYER_KILLER_SKULL = 439; public static final int OVERHEAD_PROTECT_FROM_MELEE = 440; public static final int MINIMAP_GUIDE_ARROW_YELLOW = 441; public static final int MULTI_COMBAT_ZONE_CROSSED_SWORDS = 442; public static final int DUEL_ARENA_ZONE_SHINING_AXE = 443; public static final int BANK_PIN_MARBLE_BACKGROUND = 444; public static final int BANK_PIN_MARBLE_BACKGROUND_RED = 445; public static final int BANK_PIN_MARBLE_BUTTON_RED = 446; public static final int TEXTURE_TRAPDOOR = 447; public static final int TEXTURE_WATER = 448; public static final int TEXTURE_BRICKS_STONE = 449; public static final int TEXTURE_BRICKS = 450; public static final int TEXTURE_CHEST = 451; public static final int TEXTURE_WOOD_DARK = 452; public static final int TEXTURE_ROOF_TILES = 453; public static final int TEXTURE_454 = 454; public static final int TEXTURE_LEAVES = 455; public static final int TEXTURE_TREE_STUMP = 456; public static final int TEXTURE_STONE = 457; public static final int TEXTURE_PORTCULLIS = 458; public static final int TEXTURE_PAINTING_MOUNTAIN = 459; public static final int TEXTURE_PAINTING_KING = 460; public static final int TEXTURE_MARBLE = 461; public static final int TEXTURE_WOOD = 462; public static final int TEXTURE_FALLING_RAIN_EFFECT = 463; public static final int TEXTURE_WOOD_PALE = 464; public static final int TEXTURE_SCALY = 465; public static final int TEXTURE_BOOKSHELVES = 466; public static final int TEXTURE_ROOF_TILES_SCALY_EDGE = 467; public static final int TEXTURE_PLANKS = 468; public static final int TEXTURE_BRICKS_STONE_DIRTY = 469; public static final int TEXTURE_WATER_TURQUOISE = 470; public static final int TEXTURE_COBWEB = 471; public static final int TEXTURE_ROOF_TILES_SCALY = 472; public static final int TEXTURE_473 = 473; public static final int TEXTURE_FERN_LEAF = 474; public static final int TEXTURE_LEAVES_475 = 475; public static final int TEXTURE_LAVA = 476; public static final int TEXTURE_477 = 477; public static final int TEXTURE_LEAVES_MAPLE = 478; public static final int TEXTURE_MAGIC_TREE_STARS_EFFECT = 479; public static final int TEXTURE_BRICKS_COBBLESTONE = 480; public static final int TEXTURE_481 = 481; public static final int TEXTURE_482 = 482; public static final int TEXTURE_483 = 483; public static final int TEXTURE_PAINTING_ELVEN_ARCHER = 484; public static final int TEXTURE_LAVA_485 = 485; public static final int TEXTURE_LEAVES_486 = 486; public static final int TEXTURE_TILES_STONE = 487; public static final int TEXTURE_ROOF_TILES_STONE = 488; public static final int UNKNOWN_SMALL_GREEN_UP_ARROW = 489; public static final int TEXTURE_COBBLESTONE = 490; public static final int TEXTURE_BRICKS_SANDSTONE = 491; public static final int TEXTURE_HEIROGLYPHS = 492; public static final int TEXTURE_493 = 493; /* Unmapped: 494~497 */ public static final int LOGIN_SCREEN_RUNESCAPE_LOGO = 498; public static final int LOGIN_SCREEN_DIALOG_BACKGROUND = 499; public static final int LOGIN_SCREEN_BUTTON_BACKGROUND = 500; public static final int UNKNOWN_FIRE_RUNE_ALPHA_MASK = 501; public static final int PRAYER_HAWK_EYE = 502; public static final int PRAYER_MYSTIC_LORE = 503; public static final int PRAYER_EAGLE_EYE = 504; public static final int PRAYER_MYSTIC_MIGHT = 505; public static final int PRAYER_HAWK_EYE_DISABLED = 506; public static final int PRAYER_MYSTIC_LORE_DISABLED = 507; public static final int PRAYER_EAGLE_EYE_DISABLED = 508; public static final int PRAYER_MYSTIC_MIGHT_DISABLED = 509; public static final int MINIMAP_MARKER_RED_ITEM = 510; public static final int MINIMAP_MARKER_YELLOW_NPC = 511; public static final int MINIMAP_MARKER_WHITE_PLAYER = 512; public static final int MINIMAP_MARKER_GREEN_PLAYER_FRIEND = 513; public static final int MINIMAP_MARKER_BLUE_PLAYER_TEAM_CAPE = 514; public static final int YELLOW_CLICK_ANIMATION_1 = 515; public static final int YELLOW_CLICK_ANIMATION_2 = 516; public static final int YELLOW_CLICK_ANIMATION_3 = 517; public static final int YELLOW_CLICK_ANIMATION_4 = 518; public static final int RED_CLICK_ANIMATION_1 = 519; public static final int RED_CLICK_ANIMATION_2 = 520; public static final int RED_CLICK_ANIMATION_3 = 521; public static final int RED_CLICK_ANIMATION_4 = 522; public static final int PLAYER_KILLER_SKULL_523 = 523; public static final int FIGHT_PITS_WINNER_SKULL_RED = 524; public static final int BOUNTY_HUNTER_TARGET_WEALTH_5_VERY_HIGH = 525; public static final int BOUNTY_HUNTER_TARGET_WEALTH_4_HIGH = 526; public static final int BOUNTY_HUNTER_TARGET_WEALTH_3_MEDIUM = 527; public static final int BOUNTY_HUNTER_TARGET_WEALTH_2_LOW = 528; public static final int HOUSE_LOADING_SCREEN = 529; public static final int TEXTURE_ROUGH_STONE = 530; public static final int TEXTURE_WATER_531 = 531; public static final int TEXTURE_MARBLE_ROUGH = 532; public static final int TEXTURE_ROOF_TILES_SLATE_GREY = 533; public static final int UNKNOWN_SMALL_RED_DOWN_ARROW = 534; public static final int WINDOW_CLOSE_BUTTON = 535; public static final int WINDOW_CLOSE_BUTTON_HOVERED = 536; public static final int WINDOW_CLOSE_BUTTON_PARCHMENT = 537; public static final int WINDOW_CLOSE_BUTTON_PARCHMENT_HOVERED = 538; public static final int WINDOW_CLOSE_BUTTON_RED_X = 539; public static final int WINDOW_CLOSE_BUTTON_RED_X_HOVERED = 540; public static final int WINDOW_CLOSE_BUTTON_BROWN_X = 541; public static final int WINDOW_CLOSE_BUTTON_BROWN_X_HOVERED = 542; public static final int SPELL_BAKE_PIE = 543; public static final int SPELL_MOONCLAN_TELEPORT = 544; public static final int SPELL_WATERBIRTH_TELEPORT = 545; public static final int UNUSED_SPELL_BOW_AND_ARROW = 546; public static final int SPELL_BARBARIAN_TELEPORT = 547; public static final int SPELL_SUPERGLASS_MAKE = 548; public static final int SPELL_KHAZARD_TELEPORT = 549; public static final int SPELL_STRING_JEWELLERY = 550; public static final int SPELL_BOOST_POTION_SHARE = 551; public static final int SPELL_MAGIC_IMBUE = 552; public static final int SPELL_FERTILE_SOIL = 553; public static final int SPELL_STAT_RESTORE_POT_SHARE = 554; public static final int SPELL_FISHING_GUILD_TELEPORT = 555; public static final int SPELL_CATHERBY_TELEPORT = 556; public static final int SPELL_ICE_PLATEAU_TELEPORT = 557; public static final int SPELL_ENERGY_TRANSFER = 558; public static final int SPELL_CURE_OTHER = 559; public static final int SPELL_HEAL_OTHER = 560; public static final int SPELL_VENGEANCE_OTHER = 561; public static final int SPELL_CURE_ME = 562; public static final int SPELL_GEOMANCY = 563; public static final int SPELL_VENGEANCE = 564; public static final int SPELL_CURE_GROUP = 565; public static final int SPELL_HEAL_GROUP = 566; public static final int SPELL_CURE_PLANT = 567; public static final int SPELL_NPC_CONTACT = 568; public static final int SPELL_TELE_GROUP_MOONCLAN = 569; public static final int SPELL_TELE_GROUP_WATERBIRTH = 570; public static final int SPELL_TELE_GROUP_BARBARIAN = 571; public static final int SPELL_TELE_GROUP_KHAZARD = 572; public static final int SPELL_TELE_GROUP_FISHING_GUILD = 573; public static final int SPELL_TELE_GROUP_CATHERBY = 574; public static final int SPELL_TELE_GROUP_ICE_PLATEAU = 575; public static final int SPELL_STAT_SPY = 576; public static final int SPELL_MONSTER_EXAMINE = 577; public static final int SPELL_HUMIDIFY = 578; public static final int SPELL_HUNTER_KIT = 579; public static final int SPELL_DREAM = 580; public static final int SPELL_PLANK_MAKE = 581; public static final int SPELL_SPELLBOOK_SWAP = 582; public static final int SPELL_TAN_LEATHER = 583; public static final int SPELL_RECHARGE_DRAGONSTONE = 584; public static final int SPELL_SPIN_FLAX = 585; public static final int SPELL_OURANIA_TELEPORT = 586; /* Unmapped: 587~592 */ public static final int SPELL_BAKE_PIE_DISABLED = 593; public static final int SPELL_MOONCLAN_TELEPORT_DISABLED = 594; public static final int SPELL_WATERBIRTH_TELEPORT_DISABLED = 595; public static final int UNUSED_SPELL_BOW_AND_ARROW_DISABLED = 596; public static final int SPELL_BARBARIAN_TELEPORT_DISABLED = 597; public static final int SPELL_SUPERGLASS_MAKE_DISABLED = 598; public static final int SPELL_KHAZARD_TELEPORT_DISABLED = 599; public static final int SPELL_STRING_JEWELLERY_DISABLED = 600; public static final int SPELL_BOOST_POTION_SHARE_DISABLED = 601; public static final int SPELL_MAGIC_IMBUE_DISABLED = 602; public static final int SPELL_FERTILE_SOIL_DISABLED = 603; public static final int SPELL_STAT_RESTORE_POT_SHARE_DISABLED = 604; public static final int SPELL_FISHING_GUILD_TELEPORT_DISABLED = 605; public static final int SPELL_CATHERBY_TELEPORT_DISABLED = 606; public static final int SPELL_ICE_PLATEAU_TELEPORT_DISABLED = 607; public static final int SPELL_ENERGY_TRANSFER_DISABLED = 608; public static final int SPELL_CURE_OTHER_DISABLED = 609; public static final int SPELL_HEAL_OTHER_DISABLED = 610; public static final int SPELL_VENGEANCE_OTHER_DISABLED = 611; public static final int SPELL_CURE_ME_DISABLED = 612; public static final int SPELL_GEOMANCY_DISABLED = 613; public static final int SPELL_VENGEANCE_DISABLED = 614; public static final int SPELL_CURE_GROUP_DISABLED = 615; public static final int SPELL_HEAL_GROUP_DISABLED = 616; public static final int SPELL_CURE_PLANT_DISABLED = 617; public static final int SPELL_NPC_CONTACT_DISABLED = 618; public static final int SPELL_TELE_GROUP_MOONCLAN_DISABLED = 619; public static final int SPELL_TELE_GROUP_WATERBIRTH_DISABLED = 620; public static final int SPELL_TELE_GROUP_BARBARIAN_DISABLED = 621; public static final int SPELL_TELE_GROUP_KHAZARD_DISABLED = 622; public static final int SPELL_TELE_GROUP_FISHING_GUILD_DISABLED = 623; public static final int SPELL_TELE_GROUP_CATHERBY_DISABLED = 624; public static final int SPELL_TELE_GROUP_ICE_PLATEAU_DISABLED = 625; public static final int SPELL_STAT_SPY_DISABLED = 626; public static final int SPELL_MONSTER_EXAMINE_DISABLED = 627; public static final int SPELL_HUMIDIFY_DISABLED = 628; public static final int SPELL_HUNTER_KIT_DISABLED = 629; public static final int SPELL_DREAM_DISABLED = 630; public static final int SPELL_PLANK_MAKE_DISABLED = 631; public static final int SPELL_SPELLBOOK_SWAP_DISABLED = 632; public static final int SPELL_TAN_LEATHER_DISABLED = 633; public static final int SPELL_RECHARGE_DRAGONSTONE_DISABLED = 634; public static final int SPELL_SPIN_FLAX_DISABLED = 635; public static final int SPELL_OURANIA_TELEPORT_DISABLED = 636; /* Unmapped: 637~642 */ public static final int TEXTURE_ROOF_TILES_SLATE_DIRTY = 643; public static final int TEXTURE_POLISHED_TIMBER = 644; /* Unmapped: 645~648 */ public static final int EQUIPMENT_WEIGHT = 649; public static final int WORLD_MAP_KEY_EFFECTS_THUNDERBOLT = 650; public static final int UNKNOWN_PRAYER_ICON = 651; public static final int UNKNOWN_BUTTON_LONG_NARROW = 652; public static final int COMBAT_STYLE_BUTTON = 653; public static final int COMBAT_STYLE_BUTTON_SELECTED = 654; public static final int COMBAT_AUTO_RETALIATE_BUTTON = 655; public static final int COMBAT_AUTO_RETALIATE_BUTTON_SELECTED = 656; public static final int COMBAT_SPECIAL_ATTACK_BUTTON = 657; public static final int UNKNOWN_COMBAT_BUTTON = 658; public static final int OPTIONS_SCREEN_BRIGHTNESS = 659; public static final int OPTIONS_MUSIC_VOLUME = 660; public static final int OPTIONS_SOUND_EFFECT_VOLUME = 661; public static final int OPTIONS_CHAT_EFFECTS = 662; public static final int OPTIONS_MOUSE_BUTTONS = 663; public static final int OPTIONS_SPLIT_PRIVATE_CHAT = 664; public static final int OPTIONS_ACCEPT_AID = 665; public static final int OPTIONS_MUSIC_DISABLED = 666; public static final int OPTIONS_SOUND_EFFECTS_DISABLED = 667; public static final int UNKNOWN_SWORD_GRIP_ICON = 668; public static final int OPTIONS_WALKING = 669; public static final int OPTIONS_RUNNING = 670; public static final int OPTIONS_WALKING_DISABLED = 671; public static final int OPTIONS_RUNNING_DISABLED = 672; public static final int OPTIONS_AREA_SOUND_VOLUME = 673; public static final int OPTIONS_AREA_SOUND_DISABLED = 674; public static final int EQUIPMENT_EQUIPMENT_STATS = 675; public static final int OPTIONS_HOUSE_OPTIONS = 676; public static final int OPTIONS_RUN_ENERGY = 677; public static final int OPTIONS_HOUSE_VIEWER = 678; public static final int OPTIONS_SLIDER_1_OF_4 = 679; public static final int OPTIONS_SLIDER_2_OF_4 = 680; public static final int OPTIONS_SLIDER_3_OF_4 = 681; public static final int OPTIONS_SLIDER_4_OF_4 = 682; public static final int OPTIONS_SLIDER_AND_THUMB_1_OF_4 = 683; public static final int OPTIONS_SLIDER_AND_THUMB_2_OF_4 = 684; public static final int OPTIONS_SLIDER_AND_THUMB_3_OF_4 = 685; public static final int OPTIONS_SLIDER_AND_THUMB_4_OF_4 = 686; public static final int OPTIONS_SLIDER_AND_THUMB_1_OF_5 = 687; public static final int OPTIONS_SLIDER_AND_THUMB_2_OF_5 = 688; public static final int OPTIONS_SLIDER_AND_THUMB_3_OF_5 = 689; public static final int OPTIONS_SLIDER_AND_THUMB_4_OF_5 = 690; public static final int OPTIONS_SLIDER_AND_THUMB_5_OF_5 = 691; public static final int OPTIONS_SLIDER_1_OF_5 = 692; public static final int OPTIONS_SLIDER_2_OF_5 = 693; public static final int OPTIONS_SLIDER_3_OF_5 = 694; public static final int OPTIONS_SLIDER_4_OF_5 = 695; public static final int OPTIONS_SLIDER_5_OF_5 = 696; public static final int OPTIONS_ROUND_CHECK_BOX = 697; public static final int OPTIONS_ROUND_CHECK_BOX_CROSSED = 698; public static final int OPTIONS_ROUND_CHECK_BOX_CHECKED = 699; public static final int EMOTE_YES = 700; public static final int EMOTE_NO = 701; public static final int EMOTE_THINK = 702; public static final int EMOTE_BOW = 703; public static final int EMOTE_ANGRY = 704; public static final int EMOTE_CRY = 705; public static final int EMOTE_LAUGH = 706; public static final int EMOTE_CHEER = 707; public static final int EMOTE_WAVE = 708; public static final int EMOTE_BECKON = 709; public static final int EMOTE_DANCE = 710; public static final int EMOTE_CLAP = 711; public static final int EMOTE_PANIC = 712; public static final int EMOTE_JIG = 713; public static final int EMOTE_SPIN = 714; public static final int EMOTE_HEADBANG = 715; public static final int EMOTE_JUMP_FOR_JOY = 716; public static final int EMOTE_RASPBERRY = 717; public static final int EMOTE_YAWN = 718; public static final int EMOTE_SALUTE = 719; public static final int EMOTE_SHRUG = 720; public static final int EMOTE_BLOW_KISS = 721; public static final int EMOTE_GLASS_BOX = 722; public static final int EMOTE_CLIMB_ROPE = 723; public static final int EMOTE_LEAN = 724; public static final int EMOTE_GLASS_WALL = 725; public static final int EMOTE_GOBLIN_BOW = 726; public static final int EMOTE_GOBLIN_SALUTE = 727; public static final int EMOTE_SCARED = 728; public static final int EMOTE_SLAP_HEAD = 729; public static final int EMOTE_STAMP = 730; public static final int EMOTE_FLAP = 731; public static final int EMOTE_IDEA = 732; public static final int EMOTE_ZOMBIE_WALK = 733; public static final int EMOTE_ZOMBIE_DANCE = 734; public static final int EMOTE_RABBIT_HOP = 735; public static final int EMOTE_SKILLCAPE = 736; public static final int EMOTE_ZOMBIE_HAND = 737; public static final int EMOTE_AIR_GUITAR = 738; public static final int EMOTE_JOG = 739; public static final int EMOTE_SHRUG_LOCKED = 740; public static final int EMOTE_BLOW_KISS_LOCKED = 741; public static final int EMOTE_GLASS_BOX_LOCKED = 742; public static final int EMOTE_CLIMB_ROPE_LOCKED = 743; public static final int EMOTE_LEAN_LOCKED = 744; public static final int EMOTE_GLASS_WALL_LOCKED = 745; public static final int EMOTE_GOBLIN_BOW_LOCKED = 746; public static final int EMOTE_GOBLIN_SALUTE_LOCKED = 747; public static final int EMOTE_SCARED_LOCKED = 748; public static final int EMOTE_SLAP_HEAD_LOCKED = 749; public static final int EMOTE_STAMP_LOCKED = 750; public static final int EMOTE_FLAP_LOCKED = 751; public static final int EMOTE_IDEA_LOCKED = 752; public static final int EMOTE_ZOMBIE_WALK_LOCKED = 753; public static final int EMOTE_ZOMBIE_DANCE_LOCKED = 754; public static final int EMOTE_RABBIT_HOP_LOCKED = 755; public static final int EMOTE_SKILLCAPE_LOCKED = 756; public static final int EMOTE_ZOMBIE_HAND_LOCKED = 757; public static final int EMOTE_AIR_GUITAR_LOCKED = 758; public static final int EMOTE_JOG_LOCKED = 759; public static final int COMBAT_STYLE_DEFENSIVE_CASTING_SHIELD = 760; public static final int OPTIONS_SQUARE_BUTTON = 761; public static final int OPTIONS_SQUARE_BUTTON_SELECTED = 762; public static final int TEXTURE_FALLING_SNOW_EFFECT = 763; /* Unmapped: 764 */ public static final int BARBARIAN_ASSAULT_WAVE_ICON = 765; public static final int BARBARIAN_ASSAULT_EAR_ICON = 766; public static final int BARBARIAN_ASSAULT_MOUTH_ICON = 767; public static final int BARBARIAN_ASSAULT_HORN_FOR_ATTACKER_ICON = 768; public static final int BARBARIAN_ASSAULT_HORN_FOR_DEFENDER_ICON = 769; public static final int BARBARIAN_ASSAULT_HORN_FOR_COLLECTOR_ICON = 770; public static final int BARBARIAN_ASSAULT_HORN_FOR_HEALER_ICON = 771; public static final int UNKNOWN_ARROW_RIGHT_YELLOW = 772; public static final int SCROLLBAR_ARROW_UP = 773; public static final int RS2_TAB_COMBAT = 774; public static final int RS2_TAB_STATS = 775; public static final int TAB_QUESTS = 776; public static final int RS2_TAB_INVENTORY = 777; public static final int RS2_TAB_EQUIPMENT = 778; public static final int RS2_TAB_PRAYER = 779; public static final int TAB_MAGIC = 780; public static final int RS2_TAB_FRIENDS_CHAT = 781; public static final int TAB_FRIENDS = 782; public static final int TAB_IGNORES = 783; public static final int RS2_TAB_LOGOUT = 784; public static final int RS2_TAB_OPTIONS = 785; public static final int RS2_TAB_EMOTES = 786; public static final int RS2_TAB_MUSIC = 787; public static final int SCROLLBAR_ARROW_DOWN = 788; public static final int SCROLLBAR_THUMB_TOP = 789; public static final int SCROLLBAR_THUMB_MIDDLE = 790; public static final int SCROLLBAR_THUMB_BOTTOM = 791; public static final int SCROLLBAR_THUMB_MIDDLE_DARK = 792; public static final int UNKNOWN_DECORATED_ARROW_UP = 793; public static final int UNKNOWN_DECORATED_ARROW_DOWN = 794; public static final int UNKNOWN_DECORATED_FRAME_TOP = 795; public static final int UNKNOWN_DECORATED_FRAME_MIDDLE = 796; public static final int UNKNOWN_DECORATED_FRAME_BOTTOM = 797; public static final int UNKNOWN_DECORATED_MIDDLE = 798; public static final int UNKNOWN_WINDOW_CLOSE_BUTTON_BROWN_X = 799; public static final int UNKNOWN_WINDOW_CLOSE_BUTTON_BROWN_X_HOVERED = 800; public static final int RS2_SCROLLBAR_ARROW_UP_801 = 801; public static final int RS2_SCROLLBAR_ARROW_DOWN = 802; public static final int EMOTE_PENGUIN_SHIVER = 803; public static final int EMOTE_PENGUIN_SPIN = 804; public static final int EMOTE_PENGUIN_CLAP = 805; public static final int EMOTE_PENGUIN_BOW = 806; public static final int EMOTE_PENGUIN_CHEER = 807; public static final int EMOTE_PENGUIN_WAVE = 808; public static final int EMOTE_PENGUIN_PREEN = 809; public static final int EMOTE_PENGUIN_FLAP = 810; public static final int LOGIN_SCREEN_MUSIC_BUTTON = 811; public static final int SLAYER_REWARDS_AND_POLL_HISTORY_BUTTON = 812; public static final int SLAYER_REWARDS_AND_POLL_HISTORY_BUTTON_SELECTED = 813; public static final int LOGIN_SCREEN_FREE_WORLD_BACKGROUND = 814; public static final int LOGIN_SCREEN_REGION_USA = 815; public static final int LOGIN_SCREEN_SORTING_ARROW_UP_DISABLED = 816; public static final int LOGIN_SCREEN_WORLD_STAR_FREE = 817; public static final int LOGIN_SCREEN_WORLD_SELECT_BUTTON = 818; /* Unmapped: 819 */ public static final int BOTTOM_LINE_MODE_SIDE_PANEL_EDGE_TOP = 820; public static final int BOTTOM_LINE_MODE_SIDE_PANEL_EDGE_LEFT = 821; public static final int BOTTOM_LINE_MODE_SIDE_PANEL_EDGE_BOTTOM = 822; public static final int BOTTOM_LINE_MODE_SIDE_PANEL_EDGE_RIGHT = 823; public static final int BOTTOM_LINE_MODE_SIDE_PANEL_CORNER_TOP_LEFT = 824; public static final int BOTTOM_LINE_MODE_SIDE_PANEL_CORNER_TOP_RIGHT = 825; public static final int BOTTOM_LINE_MODE_SIDE_PANEL_CORNER_BOTTOM_LEFT = 826; public static final int BOTTOM_LINE_MODE_SIDE_PANEL_CORNER_BOTTOM_RIGHT = 827; public static final int BOTTOM_LINE_MODE_SIDE_PANEL_EDGE_HORIZONTAL = 828; public static final int BOTTOM_LINE_MODE_SIDE_PANEL_INTERSECTION_LEFT = 829; public static final int BOTTOM_LINE_MODE_SIDE_PANEL_INTERSECTION_RIGHT = 830; public static final int BOTTOM_LINE_MODE_WINDOW_CLOSE_BUTTON_SMALL = 831; public static final int BOTTOM_LINE_MODE_WINDOW_CLOSE_BUTTON_SMALL_HOVERED = 832; public static final int UNKNOWN_BUTTON_METAL_CORNERED = 833; public static final int UNKNOWN_BUTTON_METAL_CORNERED_HOVERED = 834; public static final int QUESTS_PAGE_ICON_BLUE_QUESTS = 835; public static final int QUESTS_PAGE_ICON_GREEN_ACHIEVEMENT_DIARIES = 836; public static final int CYRISUS_CHEST = 837; public static final int MONSTER_EXAMINE_STATS_ICON = 838; public static final int BOTTOM_LINE_MODE_SIDE_PANEL_INTERSECTION_BOTTOM = 839; public static final int BOTTOM_LINE_MODE_SIDE_PANEL_INTERSECTION_TOP = 840; public static final int BOTTOM_LINE_MODE_EDGE_VERTICAL = 841; public static final int BOTTOM_LINE_MODE_INTERSECTION_TOP = 842; public static final int BOTTOM_LINE_MODE_INTERSECTION_BOTTOM = 843; public static final int BOTTOM_LINE_MODE_INTERSECTION_LEFT = 844; public static final int BOTTOM_LINE_MODE_INTERSECTION_RIGHT = 845; public static final int BOTTOM_LINE_MODE_CORNER_TOP_LEFT = 846; public static final int BOTTOM_LINE_MODE_CORNER_TOP_RIGHT = 847; public static final int BOTTOM_LINE_MODE_CORNER_BOTTOM_LEFT = 848; public static final int BOTTOM_LINE_MODE_CORNER_BOTTOM_RIGHT = 849; public static final int BOTTOM_LINE_MODE_INTERSECTION_MIDDLE = 850; /* Unmapped: 851~860 */ public static final int UNKNOWN_GLASS_STREAKS = 861; public static final int WITCHS_HOUSE_PIANO_MUSICAL_NOTES_BEAMED = 862; public static final int WITCHS_HOUSE_PIANO_MUSICAL_NOTE_CROTCHET = 863; public static final int WITCHS_HOUSE_PIANO_MUSICAL_NOTE_MINIM = 864; public static final int WITCHS_HOUSE_PIANO_TREBLE_CLEF = 865; public static final int TEXTURE_ROOF_TILES_SLATE_DARK = 866; public static final int PURO_PURO_GOURMET_IMPLING = 867; public static final int PURO_PURO_BABY_IMPLING = 868; public static final int PURO_PURO_DRAGON_IMPLING = 869; public static final int PURO_PURO_NATURE_IMPLING = 870; public static final int PURO_PURO_ECLECTIC_IMPLING = 871; public static final int PURO_PURO_IMPLING_IN_JAR = 872; public static final int PURO_PURO_YOUNG_IMPLING = 873; public static final int PURO_PURO_MAGPIE_IMPLING = 874; public static final int PURO_PURO_ESSENCE_IMPLING = 875; public static final int PURO_PURO_EARTH_IMPLING = 876; public static final int PURO_PURO_NINJA_IMPLING = 877; public static final int PURO_PURO_LUCKY_IMPLING = 878; public static final int PURO_PURO_THUMB_UP_BUTTON = 879; public static final int PURO_PURO_THUMB_UP_BUTTON_HOVERED = 880; public static final int UNUSED_TAB_COMBAT = 881; public static final int UNUSED_TAB_STATS = 882; public static final int UNUSED_TAB_QUESTS = 883; public static final int UNUSED_TAB_EQUIPMENT = 885; public static final int UNUSED_TAB_PRAYER = 886; public static final int UNUSED_TAB_MAGIC = 887; public static final int UNUSED_TAB_FRIENDS = 888; public static final int UNUSED_TAB_IGNORES = 889; public static final int UNUSED_TAB_LOGOUT = 890; public static final int UNUSED_TAB_OPTIONS = 891; public static final int UNUSED_TAB_EMOTES = 892; public static final int UNUSED_TAB_MUSIC = 893; public static final int UNUSED_TAB_HOUSE = 894; public static final int UNUSED_TAB_SUMMONING = 896; public static final int RESIZEABLE_MODE_SIDE_PANEL_BACKGROUND = 897; public static final int TAB_STATS = 898; public static final int UNUSED_TAB_QUESTS_899 = 899; public static final int TAB_INVENTORY = 900; public static final int TAB_EQUIPMENT = 901; public static final int TAB_PRAYER = 902; public static final int UNUSED_TAB_MAGIC_903 = 903; public static final int TAB_FRIENDS_CHAT = 904; public static final int TAB_LOGOUT = 907; public static final int TAB_OPTIONS = 908; public static final int TAB_EMOTES = 909; public static final int TAB_MUSIC = 910; public static final int UNUSED_TAB_COMBAT_911 = 911; public static final int EQUIPMENT_ITEMS_LOST_ON_DEATH = 912; public static final int EQUIPMENT_BUTTON_METAL_CORNER_TOP_LEFT = 913; public static final int EQUIPMENT_BUTTON_METAL_CORNER_TOP_RIGHT = 914; public static final int EQUIPMENT_BUTTON_METAL_CORNER_BOTTOM_LEFT = 915; public static final int EQUIPMENT_BUTTON_METAL_CORNER_BOTTOM_RIGHT = 916; public static final int EQUIPMENT_BUTTON_EDGE_LEFT = 917; public static final int EQUIPMENT_BUTTON_EDGE_TOP = 918; public static final int EQUIPMENT_BUTTON_EDGE_RIGHT = 919; public static final int EQUIPMENT_BUTTON_EDGE_BOTTOM = 920; public static final int EQUIPMENT_BUTTON_METAL_CORNER_TOP_LEFT_HOVERED = 921; public static final int EQUIPMENT_BUTTON_METAL_CORNER_TOP_RIGHT_HOVERED = 922; public static final int EQUIPMENT_BUTTON_METAL_CORNER_BOTTOM_LEFT_HOVERED = 923; public static final int EQUIPMENT_BUTTON_METAL_CORNER_BOTTOM_RIGHT_HOVERED = 924; public static final int EQUIPMENT_BUTTON_EDGE_LEFT_HOVERED = 925; public static final int EQUIPMENT_BUTTON_EDGE_TOP_HOVERED = 926; public static final int EQUIPMENT_BUTTON_EDGE_RIGHT_HOVERED = 927; public static final int EQUIPMENT_BUTTON_EDGE_BOTTOM_HOVERED = 928; public static final int WORLD_MAP_BUTTON_METAL_CORNER_TOP_LEFT = 929; public static final int WORLD_MAP_BUTTON_METAL_CORNER_TOP_RIGHT = 930; public static final int WORLD_MAP_BUTTON_METAL_CORNER_BOTTOM_LEFT = 931; public static final int WORLD_MAP_BUTTON_METAL_CORNER_BOTTOM_RIGHT = 932; public static final int WORLD_MAP_BUTTON_EDGE_LEFT = 933; public static final int WORLD_MAP_BUTTON_EDGE_TOP = 934; public static final int WORLD_MAP_BUTTON_EDGE_RIGHT = 935; public static final int WORLD_MAP_BUTTON_EDGE_BOTTOM = 936; public static final int TRADE_EXCLAMATION_MARK_ITEM_REMOVAL_WARNING = 937; public static final int UNKNOWN_PURO_PURO_THUMB_UP = 938; public static final int UNKNOWN_PURO_PURO_THUMB_UP_HOVERED = 939; public static final int UNKNOWN_DISABLED_ICON = 940; public static final int UNKNOWN_ROUND_CHECK_BUTTON = 941; public static final int UNKNOWN_ROUND_CHECK_BUTTON_CHECKED = 942; public static final int UNKNOWN_LARGE_BUTTON_WITH_RED_X = 943; public static final int UNUSED_PRAYER_PROTECT_FROM_SUMMONING = 944; public static final int PRAYER_CHIVALRY = 945; public static final int PRAYER_PIETY = 946; public static final int PRAYER_PRESERVE = 947; public static final int UNUSED_PRAYER_PROTECT_FROM_SUMMONING_DISABLED = 948; public static final int PRAYER_CHIVALRY_DISABLED = 949; public static final int PRAYER_PIETY_DISABLED = 950; public static final int PRAYER_PRESERVE_DISABLED = 951; public static final int UNKNOWN_SLANTED_TAB = 952; public static final int UNKNOWN_SLANTED_TAB_HOVERED = 953; public static final int UNUSED_BOTTOM_LINE_MODE_SIDE_PANEL_EDGE_TOP = 954; public static final int UNUSED_BOTTOM_LINE_MODE_SIDE_PANEL_EDGE_LEFT = 955; public static final int UNUSED_BOTTOM_LINE_MODE_SIDE_PANEL_EDGE_BOTTOM = 956; public static final int UNUSED_BOTTOM_LINE_MODE_SIDE_PANEL_EDGE_RIGHT = 957; public static final int UNUSED_BOTTOM_LINE_MODE_SIDE_PANEL_CORNER_TOP_LEFT = 958; public static final int UNUSED_BOTTOM_LINE_MODE_SIDE_PANEL_CORNER_TOP_RIGHT = 959; public static final int UNUSED_BOTTOM_LINE_MODE_SIDE_PANEL_CORNER_BOTTOM_LEFT = 960; public static final int UNUSED_BOTTOM_LINE_MODE_SIDE_PANEL_CORNER_BOTTOM_RIGHT = 961; public static final int UNUSED_BOTTOM_LINE_MODE_EDGE_HORIZONTAL = 962; public static final int UNUSED_BOTTOM_LINE_MODE_SIDE_PANEL_INTERSECTION_LEFT = 963; public static final int UNUSED_BOTTOM_LINE_MODE_SIDE_PANEL_INTERSECTION_RIGHT = 964; public static final int UNUSED_BOTTOM_LINE_MODE_SIDE_PANEL_INTERSECTION_BOTTOM = 965; public static final int UNUSED_BOTTOM_LINE_MODE_SIDE_PANEL_INTERSECTION_TOP = 966; public static final int UNUSED_BOTTOM_LINE_MODE_EDGE_VERTICAL = 967; public static final int UNUSED_BOTTOM_LINE_MODE_INTERSECTION_TOP = 968; public static final int UNUSED_BOTTOM_LINE_MODE_INTERSECTION_BOTTOM = 969; public static final int UNUSED_BOTTOM_LINE_MODE_INTERSECTION_LEFT = 970; public static final int UNUSED_BOTTOM_LINE_MODE_INTERSECTION_RIGHT = 971; public static final int UNUSED_BOTTOM_LINE_MODE_CORNER_TOP_LEFT = 972; public static final int UNUSED_BOTTOM_LINE_MODE_CORNER_TOP_RIGHT = 973; public static final int UNUSED_BOTTOM_LINE_MODE_CORNER_BOTTOM_LEFT = 974; public static final int UNUSED_BOTTOM_LINE_MODE_CORNER_BOTTOM_RIGHT = 975; public static final int UNUSED_BOTTOM_LINE_MODE_INTERSECTION_MIDDLE = 976; /* Unmapped: 977~986 */ public static final int UNKNOWN_BORDER_EDGE_HORIZONTAL = 987; public static final int UNKNOWN_BORDER_EDGE_VERTICAL = 988; public static final int UNKNOWN_BORDER_EDGE_HORIZONTAL_989 = 989; public static final int UNKNOWN_BORDER_EDGE_VERTICAL_990 = 990; public static final int UNKNOWN_BORDER_CORNER_TOP_LEFT = 991; public static final int UNKNOWN_BORDER_CORNER_TOP_RIGHT = 992; public static final int UNKNOWN_BORDER_CORNER_BOTTOM_LEFT = 993; public static final int UNKNOWN_BORDER_CORNER_BOTTOM_RIGHT = 994; public static final int UNKNOWN_BORDER_EDGE_HORIZONTAL_995 = 995; public static final int UNKNOWN_BORDER_INTERSECTION_LEFT = 996; public static final int UNKNOWN_BORDER_INTERSECTION_RIGHT = 997; public static final int STASH_UNITS_SLANTED_TAB_EDGE_LEFT = 998; public static final int STASH_UNITS_SLANTED_TAB_MIDDLE = 999; public static final int STASH_UNITS_SLANTED_TAB_EDGE_RIGHT = 1000; public static final int STASH_UNITS_SLANTED_TAB_EDGE_LEFT_HOVERED = 1001; public static final int STASH_UNITS_SLANTED_TAB_MIDDLE_HOVERED = 1002; public static final int STASH_UNITS_SLANTED_TAB_EDGE_RIGHT_HOVERED = 1003; public static final int UNKNOWN_BUTTON_METAL_CORNERS = 1013; public static final int UNKNOWN_BUTTON_METAL_CORNERS_HOVERED = 1014; public static final int UNKNOWN_SLANTED_TAB_LONG = 1015; public static final int UNKNOWN_SLANTED_TAB_LONG_HOVERED = 1016; public static final int CHATBOX = 1017; public static final int CHATBOX_BUTTONS_BACKGROUND_STONES = 1018; public static final int CHATBOX_BUTTON = 1019; public static final int CHATBOX_BUTTON_HOVERED = 1020; public static final int CHATBOX_BUTTON_NEW_MESSAGES = 1021; public static final int CHATBOX_BUTTON_SELECTED = 1022; public static final int CHATBOX_BUTTON_SELECTED_HOVERED = 1023; public static final int CHATBOX_REPORT_BUTTON = 1024; public static final int CHATBOX_REPORT_BUTTON_HOVERED = 1025; public static final int TAB_STONE_TOP_LEFT_SELECTED = 1026; public static final int TAB_STONE_TOP_RIGHT_SELECTED = 1027; public static final int TAB_STONE_BOTTOM_LEFT_SELECTED = 1028; public static final int TAB_STONE_BOTTOM_RIGHT_SELECTED = 1029; public static final int TAB_STONE_MIDDLE_SELECTED = 1030; public static final int FIXED_MODE_SIDE_PANEL_BACKGROUND = 1031; public static final int FIXED_MODE_TABS_ROW_BOTTOM = 1032; public static final int OLD_SCHOOl_MODE_SIDE_PANEL_EDGE_LEFT_UPPER = 1033; public static final int OLD_SCHOOl_MODE_SIDE_PANEL_EDGE_LEFT_LOWER = 1034; public static final int OLD_SCHOOl_MODE_SIDE_PANEL_EDGE_RIGHT = 1035; public static final int FIXED_MODE_TABS_TOP_ROW = 1036; public static final int FIXED_MODE_MINIMAP_LEFT_EDGE = 1037; public static final int FIXED_MODE_MINIMAP_RIGHT_EDGE = 1038; public static final int FIXED_MODE_WINDOW_FRAME_EDGE_TOP = 1039; public static final int DIALOG_BACKGROUND_BRIGHTER = 1040; public static final int BANK_DEPOSIT_INVENTORY = 1041; public static final int BANK_DEPOSIT_EQUIPMENT = 1042; public static final int BANK_SEARCH = 1043; public static final int MINIMAP_MARKER_PURPLE_PLAYER_FRIENDS_CHAT = 1044; public static final int OPTIONS_PROFANITY_FILTER = 1045; public static final int PLAYER_KILLER_SKULL_1046 = 1046; public static final int PLAYER_KILLING_DISABLED_OVERLAY = 1047; public static final int UNKNOWN_BUTTON_MIDDLE = 1048; public static final int UNKNOWN_BUTTON_MIDDLE_SELECTED = 1049; public static final int LIST_SORTING_ARROW_ASCENDING = 1050; public static final int LIST_SORTING_ARROW_DESCENDING = 1051; public static final int TAB_HOUSE_UNUSED = 1052; public static final int TAB_QUESTS_RED_MINIGAMES = 1053; public static final int QUESTS_PAGE_ICON_RED_MINIGAMES = 1054; public static final int TAB_HOUSE_UNUSED_1055 = 1055; public static final int UNUSED_TAB_QUESTS_RED_MINIGAMES = 1056; public static final int OPTIONS_DATA_ORBS = 1057; public static final int MINIMAP_ORB_PRAYER_ICON_ACTIVATED = 1058; public static final int MINIMAP_ORB_EMPTY = 1059; public static final int MINIMAP_ORB_HITPOINTS = 1060; public static final int MINIMAP_ORB_HITPOINTS_POISON = 1061; public static final int MINIMAP_ORB_HITPOINTS_DISEASE = 1062; public static final int MINIMAP_ORB_PRAYER = 1063; public static final int MINIMAP_ORB_RUN = 1064; public static final int MINIMAP_ORB_RUN_ACTIVATED = 1065; public static final int MINIMAP_ORB_PRAYER_ACTIVATED = 1066; public static final int MINIMAP_ORB_HITPOINTS_ICON = 1067; public static final int MINIMAP_ORB_PRAYER_ICON = 1068; public static final int MINIMAP_ORB_WALK_ICON = 1069; public static final int MINIMAP_ORB_RUN_ICON = 1070; public static final int MINIMAP_ORB_FRAME = 1071; public static final int MINIMAP_ORB_FRAME_HOVERED = 1072; public static final int OPTIONS_CAMERA = 1073; public static final int BANK_DEPOSIT_LOOTING_BAG = 1074; public static final int TEXTURE_LAVA_RED = 1075; public static final int TEXTURE_LAVA_WHITE = 1076; public static final int BANK_TAB = 1077; public static final int BANK_TAB_HOVERED = 1078; public static final int BANK_TAB_SELECTED = 1079; public static final int BANK_TAB_EMPTY = 1080; public static final int BANK_ALL_ITEMS_TAB_ICON = 1081; public static final int BANK_ADD_TAB_ICON = 1082; public static final int BANK_SHOW_MENU_ICON = 1083; public static final int OPTIONS_DISPLAY = 1084; public static final int OPTIONS_CHAT = 1085; public static final int OPTIONS_ROOFS = 1086; public static final int OPTIONS_XP_TO_NEXT_LEVEL = 1087; public static final int OPTIONS_CONTROLS = 1088; public static final int OPTIONS_LOGIN_LOGOUT_NOTIFICATION_TIMEOUT = 1089; public static final int EQUIPMENT_GUIDE_PRICES = 1090; public static final int OPTIONS_SIDE_PANELS = 1091; public static final int MINIMAP_ORB_RUN_ICON_SLOWED_DEPLETION = 1092; public static final int FRIENDS_PREVIOUS_USERNAME = 1093; public static final int UNKNOWN_MAP_ICON_INFORMATION_I = 1094; public static final int BOUNTY_HUNTER_TARGET_NONE = 1095; public static final int BOUNTY_HUNTER_TARGET_WEALTH_1_VERY_LOW = 1096; public static final int DEADMAN_BANK_KEYS_5 = 1097; public static final int ABLEGAMERS_PROMO_BANNER = 1098; public static final int YOUNGMINDS_PROMO_BANNER = 1099; public static final int DONATEGAMES_PROMO_BANNER = 1100; public static final int UNKNOWN_GREEN_FRIEND_ICON = 1101; public static final int MINIMAP_ORB_HITPOINTS_VENOM = 1102; public static final int PAYPAL_DONATE_BUTTON = 1103; public static final int GAMEBLAST15_PROMO_BANNER = 1104; public static final int SPECIALEFFECT_PROMO_BANNER = 1105; public static final int GE_MAKE_OFFER_SELL = 1106; public static final int GE_MAKE_OFFER_SELL_HOVERED = 1107; public static final int GE_MAKE_OFFER_BUY = 1108; public static final int GE_MAKE_OFFER_BUY_HOVERED = 1109; public static final int GE_BUTTON = 1110; public static final int GE_BUTTON_HOVERED = 1111; public static final int GE_GUIDE_PRICE = 1112; public static final int GE_SEARCH = 1113; public static final int GE_FAST_DECREMENT_ARROW = 1114; public static final int GE_FAST_INCREMENT_ARROW = 1115; public static final int GE_DECREMENT_BUTTON = 1116; public static final int GE_INCREMENT_BUTTON = 1117; public static final int GE_COLLECTION_BOX_OFFER_BUY = 1118; public static final int GE_COLLECTION_BOX_OFFER_SELL = 1119; public static final int GE_SELECTED_ITEM_BOX = 1120; public static final int GE_SELECTED_ITEM_BOX_GLOWING = 1121; public static final int GE_BACK_ARROW_BUTTON = 1122; public static final int GE_NUMBER_FIELD_EDGE_LEFT = 1123; public static final int GE_NUMBER_FIELD_MIDDLE = 1124; public static final int GE_NUMBER_FIELD_EDGE_RIGHT = 1125; public static final int GE_CANCEL_OFFER_BUTTON = 1126; public static final int GE_CANCEL_OFFER_BUTTON_HOVERED = 1127; public static final int DIALOG_BONDS_MEMBERSHIP_JEWEL = 1128; public static final int DIALOG_BONDS_MEMBERSHIP_JEWEL_SMALL = 1129; public static final int WORLD_SWITCHER_STAR_FREE = 1130; public static final int WORLD_SWITCHER_STAR_MEMBERS = 1131; public static final int WORLD_SWITCHER_REGION_NONE = 1132; public static final int WORLD_SWITCHER_REGION_USA = 1133; public static final int WORLD_SWITCHER_REGION_CANADA = 1134; public static final int WORLD_SWITCHER_REGION_UK = 1135; public static final int WORLD_SWITCHER_REGION_NETHERLANDS = 1136; public static final int WORLD_SWITCHER_REGION_AUSTRALIA = 1137; public static final int WORLD_SWITCHER_REGION_SWEDEN = 1138; public static final int WORLD_SWITCHER_REGION_FINLAND = 1139; public static final int WORLD_SWITCHER_REGION_GERMANY = 1140; public static final int BUTTON_CORNER_TOP_LEFT = 1141; public static final int BUTTON_EDGE_TOP = 1142; public static final int BUTTON_CORNER_TOP_RIGHT = 1143; public static final int BUTTON_EDGE_LEFT = 1144; public static final int BUTTON_MIDDLE = 1145; public static final int BUTTON_EDGE_RIGHT = 1146; public static final int BUTTON_CORNER_BOTTOM_LEFT = 1147; public static final int BUTTON_EDGE_BOTTOM = 1148; public static final int BUTTON_CORNER_BOTTOM_RIGHT = 1149; public static final int BUTTON_CORNER_TOP_LEFT_SELECTED = 1150; public static final int BUTTON_EDGE_TOP_SELECTED = 1151; public static final int BUTTON_CORNER_TOP_RIGHT_SELECTED = 1152; public static final int BUTTON_EDGE_LEFT_SELECTED = 1153; public static final int BUTTON_MIDDLE_SELECTED = 1154; public static final int BUTTON_EDGE_RIGHT_SELECTED = 1155; public static final int BUTTON_CORNER_BOTTOM_LEFT_SELECTED = 1156; public static final int BUTTON_EDGE_BOTTOM_SELECTED = 1157; public static final int BUTTON_CORNER_BOTTOM_RIGHT_SELECTED = 1158; public static final int OPTIONS_TRANSPARENT_CHATBOX = 1159; public static final int OPTIONS_TRANSPARENT_SIDE_PANEL = 1160; public static final int OPTIONS_KEYBINDINGS = 1161; public static final int OPTIONS_SCROLL_WHEEL_ZOOM = 1162; public static final int OPTIONS_HIDE_PRIVATE_CHAT = 1163; public static final int OPTIONS_NOTIFICATIONS = 1164; public static final int OPTIONS_SHIFT_CLICK_DROP = 1165; public static final int OPTIONS_FOLLOWER_RIGHT_CLICK_MENU = 1166; public static final int OPTIONS_PRAYER_TOOLTIPS = 1167; public static final int OPTIONS_SPECIAL_ATTACK_TOOLTIP = 1168; public static final int OPTIONS_FIXED_MODE_DISABLED = 1169; public static final int OPTIONS_RESIZEABLE_MODE_DISABLED = 1170; public static final int OPTIONS_FIXED_MODE_DISABLED_VERTICAL = 1171; public static final int OPTIONS_RESIZEABLE_MODE_DISABLED_VERTICAL = 1172; public static final int RESIZEABLE_MODE_TABS_TOP_ROW = 1173; public static final int RESIZEABLE_MODE_TABS_BOTTOM_ROW = 1174; public static final int RESIZEABLE_MODE_SIDE_PANEL_EDGE_LEFT = 1175; public static final int RESIZEABLE_MODE_SIDE_PANEL_EDGE_RIGHT = 1176; public static final int RESIZEABLE_MODE_MINIMAP_AND_COMPASS_FRAME = 1177; public static final int RESIZEABLE_MODE_MINIMAP_ALPHA_MASK = 1178; public static final int RESIZEABLE_MODE_COMPASS_ALPHA_MASK = 1179; public static final int RESIZEABLE_MODE_TAB_STONE_MIDDLE = 1180; public static final int RESIZEABLE_MODE_TAB_STONE_MIDDLE_SELECTED = 1181; public static final int FIXED_MODE_MINIMAP_AND_COMPASS_FRAME = 1182; public static final int FIXED_MODE_MINIMAP_ALPHA_MASK = 1183; public static final int FIXED_MODE_COMPASS_ALPHA_MASK = 1184; public static final int CHATBOX_TRANSPARENT_SCROLLBAR_ARROW_UP = 1185; public static final int CHATBOX_TRANSPARENT_SCROLLBAR_ARROW_DOWN = 1186; public static final int CHATBOX_TRANSPARENT_SCROLLBAR_THUMB_TOP = 1187; public static final int CHATBOX_TRANSPARENT_SCROLLBAR_THUMB_MIDDLE = 1188; public static final int CHATBOX_TRANSPARENT_SCROLLBAR_THUMB_BOTTOM = 1190; public static final int UNUSED_TAB_LOGOUT_1191 = 1191; public static final int ROUND_CHECK_BOX_CHECKED_RED_HOVERED = 1192; public static final int OPTIONS_DISABLED_OPTION_OVERLAY = 1193; public static final int DUEL_ARENA_SAVE_PRESET = 1194; public static final int DUEL_ARENA_LOAD_PRESET = 1195; public static final int MINIMAP_ORB_XP = 1196; public static final int MINIMAP_ORB_XP_ACTIVATED = 1197; public static final int MINIMAP_ORB_XP_HOVERED = 1198; public static final int MINIMAP_ORB_XP_ACTIVATED_HOVERED = 1199; public static final int MINIMAP_CLICK_MASK = 1200; public static final int OPTIONS_ZOOM_SLIDER_THUMB = 1201; public static final int EMOTE_SIT_UP = 1202; public static final int EMOTE_STAR_JUMP = 1203; public static final int EMOTE_PUSH_UP = 1204; public static final int EMOTE_HYPERMOBILE_DRINKER = 1205; public static final int EMOTE_SIT_UP_LOCKED = 1206; public static final int EMOTE_STAR_JUMP_LOCKED = 1207; public static final int EMOTE_PUSH_UP_LOCKED = 1208; public static final int EMOTE_HYPERMOBILE_DRINKER_LOCKED = 1209; public static final int STASH_UNITS_GREEN_CHECK_MARK = 1210; public static final int ROUND_CHECK_BOX = 1211; public static final int ROUND_CHECK_BOX_CROSSED = 1212; public static final int ROUND_CHECK_BOX_CHECKED_GREEN = 1213; public static final int ROUND_CHECK_BOX_CHECKED_RED = 1214; public static final int SQUARE_CHECK_BOX = 1215; public static final int SQUARE_CHECK_BOX_CROSSED = 1216; public static final int SQUARE_CHECK_BOX_CHECKED = 1217; public static final int SQUARE_CHECK_BOX_HOVERED = 1218; public static final int SQUARE_CHECK_BOX_CROSSED_HOVERED = 1219; public static final int SQUARE_CHECK_BOX_CHECKED_HOVERED = 1220; public static final int DEADMAN_BANK_KEYS_4 = 1221; public static final int DEADMAN_BANK_KEYS_3 = 1222; public static final int DEADMAN_BANK_KEYS_2 = 1223; public static final int DEADMAN_BANK_KEYS_1 = 1224; /* Unmapped: 1225 */ public static final int BANK_RAID_SEND_TO_INVENTORY = 1226; public static final int BANK_RAID_SEND_TO_BANK = 1227; public static final int LOGIN_SCREEN_DEADMAN_MODE_LOGO = 1228; public static final int NARROW_BUTTON_EDGE_LEFT = 1229; public static final int NARROW_BUTTON_MIDDLE = 1230; public static final int NARROW_BUTTON_EDGE_RIGHT = 1231; public static final int NARROW_BUTTON_EDGE_LEFT_SELECTED = 1232; public static final int NARROW_BUTTON_MIDDLE_SELECTED = 1233; public static final int NARROW_BUTTON_EDGE_RIGHT_SELECTED = 1234; public static final int BANK_RAID_SEND_TO_TRASH = 1235; public static final int UNKNOWN_INFORMATION_I = 1236; public static final int WORLD_SWITCHER_WORLD_STAR_PVP = 1237; public static final int WORLD_SWITCHER_WORLD_STAR_DEADMAN = 1238; public static final int DEADMAN_EXCLAMATION_MARK_SKULLED_WARNING = 1239; public static final int KOUREND_FAVOUR_OPEN_TASK_LIST = 1240; public static final int KOUREND_FAVOUR_OPEN_TASK_LIST_HOVERED = 1241; public static final int KOUREND_FAVOUR_ARCEUUS_ICON = 1242; public static final int KOUREND_FAVOUR_HOSIDIUS_ICON = 1243; public static final int KOUREND_FAVOUR_LOVAKENGJ_ICON = 1244; public static final int KOUREND_FAVOUR_PISCARILIUS_ICON = 1245; public static final int KOUREND_FAVOUR_SHAYZIEN_ICON = 1246; public static final int SPELL_REANIMATE_GOBLIN = 1247; public static final int SPELL_REANIMATE_DEMON = 1248; public static final int SPELL_REANIMATE_DRAGON = 1249; public static final int SPELL_REANIMATE_ELF = 1250; public static final int SPELL_REANIMATE_CHAOS_DRUID = 1251; public static final int SPELL_REANIMATE_TROLL = 1252; public static final int SPELL_REANIMATE_DAGANNOTH = 1253; public static final int SPELL_REANIMATE_OGRE = 1254; public static final int SPELL_REANIMATE_GIANT = 1255; public static final int SPELL_REANIMATE_BEAR = 1256; public static final int SPELL_REANIMATE_SCORPION = 1257; public static final int SPELL_REANIMATE_IMP = 1258; public static final int SPELL_REANIMATE_MINOTAUR = 1259; public static final int SPELL_REANIMATE_UNICORN = 1260; public static final int SPELL_REANIMATE_KALPHITE = 1261; public static final int SPELL_REANIMATE_TZHAAR = 1262; public static final int SPELL_REANIMATE_AVIANSIE = 1263; public static final int SPELL_REANIMATE_MONKEY = 1264; public static final int SPELL_REANIMATE_ABYSSAL_CREATURE = 1265; public static final int SPELL_REANIMATE_HORROR = 1266; public static final int SPELL_REANIMATE_BLOODVELD = 1267; public static final int SPELL_REANIMATE_DOG = 1268; public static final int SPELL_LUMBRIDGE_GRAVEYARD_TELEPORT = 1269; public static final int SPELL_DRAYNOR_MANOR_TELEPORT = 1270; public static final int SPELL_MIND_ALTAR_TELEPORT = 1271; public static final int SPELL_REANIMATE_GOBLIN_DISABLED = 1272; public static final int SPELL_REANIMATE_DEMON_DISABLED = 1273; public static final int SPELL_REANIMATE_DRAGON_DISABLED = 1274; public static final int SPELL_REANIMATE_ELF_DISABLED = 1275; public static final int SPELL_REANIMATE_CHAOS_DRUID_DISABLED = 1276; public static final int SPELL_REANIMATE_TROLL_DISABLED = 1277; public static final int SPELL_REANIMATE_DAGANNOTH_DISABLED = 1278; public static final int SPELL_REANIMATE_OGRE_DISABLED = 1279; public static final int SPELL_REANIMATE_GIANT_DISABLED = 1280; public static final int SPELL_REANIMATE_BEAR_DISABLED = 1281; public static final int SPELL_REANIMATE_SCORPION_DISABLED = 1282; public static final int SPELL_REANIMATE_IMP_DISABLED = 1283; public static final int SPELL_REANIMATE_MINOTAUR_DISABLED = 1284; public static final int SPELL_REANIMATE_UNICORN_DISABLED = 1285; public static final int SPELL_REANIMATE_KALPHITE_DISABLED = 1286; public static final int SPELL_REANIMATE_TZHAAR_DISABLED = 1287; public static final int SPELL_REANIMATE_AVIANSIE_DISABLED = 1288; public static final int SPELL_REANIMATE_MONKEY_DISABLED = 1289; public static final int SPELL_REANIMATE_ABYSSAL_CREATURE_DISABLED = 1290; public static final int SPELL_REANIMATE_HORROR_DISABLED = 1291; public static final int SPELL_REANIMATE_BLOODVELD_DISABLED = 1292; public static final int SPELL_REANIMATE_DOG_DISABLED = 1293; public static final int SPELL_LUMBRIDGE_GRAVEYARD_TELEPORT_DISABLED = 1294; public static final int SPELL_DRAYNOR_MANOR_TELEPORT_DISABLED = 1295; public static final int SPELL_MIND_ALTAR_TELEPORT_DISABLED = 1296; public static final int QUESTS_PAGE_ICON_PURPLE_KOUREND = 1297; public static final int UNUSED_TAB_QUESTS_GREEN_ACHIEVEMENT_DIARIES = 1298; public static final int TAB_QUESTS_GREEN_ACHIEVEMENT_DIARIES = 1299; public static final int SPELL_RESPAWN_TELEPORT = 1300; public static final int SPELL_SALVE_GRAVEYARD_TELEPORT = 1301; public static final int SPELL_FENKENSTRAINS_CASTLE_TELEPORT = 1302; public static final int SPELL_WEST_ARDOUGNE_TELEPORT = 1303; public static final int SPELL_HARMONY_ISLAND_TELEPORT = 1304; public static final int SPELL_CEMETARY_TELEPORT = 1305; public static final int SPELL_BARROWS_TELEPORT = 1306; public static final int SPELL_APE_ATOLL_TELEPORT = 1307; public static final int SPELL_REANIMATE_CROPS = 1308; /* Unmapped: 1309~1318 */ public static final int SPELL_RESPAWN_TELEPORT_DISABLED = 1319; public static final int SPELL_SALVE_GRAVEYARD_TELEPORT_DISABLED = 1320; public static final int SPELL_FENKENSTRAINS_CASTLE_TELEPORT_DISABLED = 1321; public static final int SPELL_WEST_ARDOUGNE_TELEPORT_DISABLED = 1322; public static final int SPELL_HARMONY_ISLAND_TELEPORT_DISABLED = 1323; public static final int SPELL_CEMETARY_TELEPORT_DISABLED = 1324; public static final int SPELL_BARROWS_TELEPORT_DISABLED = 1325; public static final int SPELL_APE_ATOLL_TELEPORT_DISABLED = 1326; public static final int SPELL_REANIMATE_CROPS_DISABLED = 1327; /* Unmapped: 1328~1337 */ public static final int WORLD_SWITCHER_WORLD_STAR_BLUE = 1338; public static final int HITSPLAT_DARK_GREEN_VENOM = 1339; public static final int FAIRY_RING_REMOVE_FAVOURITE = 1340; public static final int FAIRY_RING_ADD_FAVOURITE = 1341; public static final int BANK_PLACEHOLDERS_LOCK = 1342; public static final int EQUIPMENT_CALL_FOLLOWER = 1343; public static final int UNKNOWN_BUTTON_HALF_TOP = 1344; public static final int UNKNOWN_BUTTON_HALF_TOP_1345 = 1345; public static final int DEADMAN_TAB_ITEMS_LOST_ON_DEATH_TO_PVM = 1346; public static final int DEADMAN_TAB_ITEMS_LOST_ON_DEATH_TO_PVP = 1347; public static final int DEADMAN_TAB_ITEMS_LOST_ON_DEATH_WHILE_SKULLED = 1348; public static final int DEADMAN_TAB_ITEMS_LOST_ON_DEATH_WHILE_SKULLED_IN_SAFE_ZONE = 1349; public static final int EMOTE_URI_TRANSFORM = 1350; public static final int EMOTE_SMOOTH_DANCE = 1351; public static final int EMOTE_CRAZY_DANCE = 1352; public static final int EMOTE_PREMIER_SHIELD = 1353; public static final int EMOTE_URI_TRANSFORM_LOCKED = 1354; public static final int EMOTE_SMOOTH_DANCE_LOCKED = 1355; public static final int EMOTE_CRAZY_DANCE_LOCKED = 1356; public static final int EMOTE_PREMIER_SHIELD_LOCKED = 1357; public static final int HITSPLAT_BLUE_NO_DAMAGE = 1358; public static final int HITSPLAT_RED_DAMAGE = 1359; public static final int HITSPLAT_GREEN_POISON = 1360; public static final int HITSPLAT_ORANGE = 1361; public static final int HITSPLAT_ORANGE_DISEASE = 1362; public static final int HITSPLAT_GREY = 1363; public static final int BOUNTY_HUNTER_SKIP_TARGET = 1364; public static final int BOUNTY_HUNTER_SKIP_TARGET_HOVERED = 1365; public static final int HOUSE_VIEWER_ROTATE_CLOCKWISE = 1366; public static final int HOUSE_VIEWER_ROTATE_ANTICLOCKWISE = 1367; public static final int HOUSE_VIEWER_PARLOUR = 1368; public static final int HOUSE_VIEWER_GARDEN = 1369; public static final int HOUSE_VIEWER_KITCHEN = 1370; public static final int HOUSE_VIEWER_DINING_ROOM = 1371; public static final int HOUSE_VIEWER_BEDROOM = 1372; public static final int HOUSE_VIEWER_GAMES_ROOM = 1373; public static final int HOUSE_VIEWER_SKILL_HALL = 1374; public static final int HOUSE_VIEWER_QUEST_HALL = 1375; public static final int HOUSE_VIEWER_CHAPEL = 1376; public static final int HOUSE_VIEWER_WORKSHOP = 1377; public static final int HOUSE_VIEWER_STUDY = 1378; public static final int HOUSE_VIEWER_PORTAL_CHAMBER = 1379; public static final int HOUSE_VIEWER_THRONE_ROOM = 1380; public static final int HOUSE_VIEWER_OUBLIETTE = 1381; public static final int HOUSE_VIEWER_DUNGEON_CORRIDOR = 1382; public static final int HOUSE_VIEWER_DUNGEON_JUNCTION = 1383; public static final int HOUSE_VIEWER_DUNGEON_STAIRS_ROOM = 1384; public static final int HOUSE_VIEWER_TREASURE_ROOM = 1385; public static final int HOUSE_VIEWER_FORMAL_GARDEN = 1386; public static final int HOUSE_VIEWER_COMBAT_ROOM = 1387; public static final int HOUSE_VIEWER_COSTUME_ROOM = 1388; public static final int HOUSE_VIEWER_MENAGERIE_INDOORS = 1389; public static final int HOUSE_VIEWER_MENAGERIE_OUTDOORS = 1390; public static final int HOUSE_VIEWER_SUPERIOR_GARDEN = 1391; public static final int HOUSE_VIEWER_ACHIEVEMENT_GALLERY = 1392; /* Unmapped: 1393, 1394, 1395 */ public static final int UNUSED_TEXTURE_LEAVES_WITH_RED_X = 1396; public static final int SKILL_CRAFTING_1397 = 1397; public static final int SKILL_FIREMAKING_LOGS = 1398; public static final int SKILL_FIREMAKING_1399 = 1399; public static final int SKILL_MAGIC_RED = 1400; public static final int SKILL_ATTACK_SQUASHED = 1401; public static final int SKILL_STRENGTH_SQUASHED = 1402; public static final int SKILL_DEFENCE_SQUASHED = 1403; public static final int SKILL_RANGED_SQUASHED = 1404; public static final int SKILL_PRAYER_SQUASHED = 1405; public static final int SKILL_MAGIC_SQUASHED = 1406; public static final int SKILL_HITPOINTS_SQUASHED = 1407; public static final int PREMIER_CLUB_BRONZE = 1408; public static final int PREMIER_CLUB_SILVER = 1409; public static final int PREMIER_CLUB_GOLD = 1410; public static final int UNKNOWN_DIAGONAL_COMING_SOON_TEXT = 1411; public static final int UNKNOWN_WHITE_REFRESH_ARROWS = 1412; public static final int TAB_QUESTS_PURPLE_KOUREND_UNUSED = 1413; public static final int TAB_QUESTS_PURPLE_KOUREND = 1414; public static final int UNKNOWN_GREEN_BAR = 1415; public static final int UNKNOWN_BLUE_BAR = 1416; public static final int UNKNOWN_YELLOW_BAR = 1417; public static final int UNKNOWN_RED_BAR = 1418; public static final int HITSPLAT_MAGENTA_ENEMY_HEALING = 1419; public static final int PRAYER_RIGOUR = 1420; public static final int PRAYER_AUGURY = 1421; /* Unmapped: 1422, 1423 */ public static final int PRAYER_RIGOUR_DISABLED = 1424; public static final int PRAYER_AUGURY_DISABLED = 1425; /* Unmapped: 1426, 1427 */ public static final int UNKNOWN_BLACK_ANTICLOCKWISE_ARROW_SHADOWED = 1428; public static final int UNKNOWN_BLACK_ANTICLOCKWISE_ARROW = 1429; public static final int YELLOW_CLICK_ANIMATION_1_1430 = 1430; public static final int YELLOW_CLICK_ANIMATION_2_1431 = 1431; public static final int YELLOW_CLICK_ANIMATION_3_1432 = 1432; public static final int YELLOW_CLICK_ANIMATION_4_1433 = 1433; public static final int RED_CLICK_ANIMATION_1_1434 = 1434; public static final int RED_CLICK_ANIMATION_2_1435 = 1435; public static final int RED_CLICK_ANIMATION_3_1436 = 1436; public static final int RED_CLICK_ANIMATION_4_1437 = 1437; public static final int MINIMAP_ORB_WORLD_MAP_FRAME = 1438; public static final int MINIMAP_ORB_WORLD_MAP_PLANET = 1439; public static final int MINIMAP_ORB_WORLD_MAP_PLANET_HOVERED = 1440; public static final int FIXED_MODE_TOP_RIGHT_CORNER = 1441; /* Unmapped: 1442~1447 */ public static final int MAP_ICON_GENERAL_STORE = 1448; public static final int MAP_ICON_SWORD_SHOP = 1449; public static final int MAP_ICON_MAGIC_SHOP = 1450; public static final int MAP_ICON_AXE_SHOP = 1451; public static final int MAP_ICON_HELMET_SHOP = 1452; public static final int MAP_ICON_BANK = 1453; public static final int MAP_ICON_QUEST_START = 1454; public static final int MAP_ICON_AMULET_SHOP = 1455; public static final int MAP_ICON_MINING_SITE = 1456; public static final int MAP_ICON_FURNACE = 1457; public static final int MAP_ICON_ANVIL = 1458; public static final int MAP_ICON_COMBAT_TRAINING = 1459; public static final int MAP_ICON_DUNGEON = 1460; public static final int MAP_ICON_STAFF_SHOP = 1461; public static final int MAP_ICON_PLATEBODY_SHOP = 1462; public static final int MAP_ICON_PLATELEGS_SHOP = 1463; public static final int MAP_ICON_SCIMITAR_SHOP = 1464; public static final int MAP_ICON_ARCHERY_SHOP = 1465; public static final int MAP_ICON_SHIELD_SHOP = 1466; public static final int MAP_ICON_ALTAR = 1467; public static final int MAP_ICON_HERBALIST = 1468; public static final int MAP_ICON_JEWELLERY_SHOP = 1469; public static final int MAP_ICON_GEM_SHOP = 1470; public static final int MAP_ICON_CRAFTING_SHOP = 1471; public static final int MAP_ICON_CANDLE_SHOP = 1472; public static final int MAP_ICON_FISHING_SHOP = 1473; public static final int MAP_ICON_FISHING_SPOT = 1474; public static final int MAP_ICON_CLOTHES_SHOP = 1475; public static final int MAP_ICON_APOTHECARY = 1476; public static final int MAP_ICON_SILK_TRADER = 1477; public static final int MAP_ICON_FOOD_SHOP_KEBAB = 1478; public static final int MAP_ICON_PUB = 1479; public static final int MAP_ICON_MACE_SHOP = 1480; public static final int MAP_ICON_TANNERY = 1481; public static final int MAP_ICON_RARE_TREES = 1482; public static final int MAP_ICON_SPINNING_WHEEL = 1483; public static final int MAP_ICON_FOOD_SHOP = 1484; public static final int MAP_ICON_FOOD_SHOP_CUTLERY = 1485; public static final int MAP_ICON_MINIGAME = 1486; public static final int MAP_ICON_WATER_SOURCE = 1487; public static final int MAP_ICON_COOKING_RANGE = 1488; public static final int MAP_ICON_PLATESKIRT_SHOP = 1489; public static final int MAP_ICON_POTTERY_WHEEL = 1490; public static final int MAP_ICON_WINDMILL = 1491; public static final int MAP_ICON_MINING_SHOP = 1492; public static final int MAP_ICON_CHAINMAIL_SHOP = 1493; public static final int MAP_ICON_SILVER_SHOP = 1494; public static final int MAP_ICON_FUR_TRADER = 1495; public static final int MAP_ICON_SPICE_SHOP = 1496; public static final int MAP_ICON_AGILITY_TRAINING = 1497; public static final int MAP_ICON_FOOD_SHOP_FRUIT = 1498; public static final int MAP_ICON_SLAYER_MASTER = 1499; public static final int MAP_ICON_HAIRDRESSER = 1500; public static final int MAP_ICON_FARMING_PATCH = 1501; public static final int MAP_ICON_MAKEOVER_MAGE = 1502; public static final int MAP_ICON_GUIDE = 1503; public static final int MAP_ICON_TRANSPORTATION = 1504; public static final int MAP_ICON_HOUSE_PORTAL = 1505; public static final int MAP_ICON_FARMING_SHOP = 1506; public static final int MAP_ICON_LOOM = 1507; public static final int MAP_ICON_BREWERY = 1508; public static final int MAP_ICON_DAIRY_CHURN = 1509; public static final int MAP_ICON_STAGNANT_WATER_SOURCE = 1510; public static final int MAP_ICON_HUNTER_TRAINING = 1511; public static final int MAP_ICON_POLL_BOOTH = 1512; public static final int MAP_ICON_HUNTER_SHOP = 1513; public static final int UNKNOWN_MAP_ICON_INFORMATION_I_1514 = 1514; public static final int MAP_ICON_ESTATE_AGENT = 1515; public static final int MAP_ICON_SAWMILL = 1516; public static final int MAP_ICON_STONEMASON = 1517; public static final int MAP_ICON_AGILITY_SHORT_CUT = 1518; public static final int MAP_ICON_WOODCUTTING_STUMP = 1519; public static final int MAP_ICON_HOLIDAY_EVENT = 1520; public static final int MAP_ICON_SANDPIT = 1521; public static final int MAP_ICON_TASK_MASTER = 1522; public static final int MAP_ICON_PET_SHOP = 1523; public static final int MAP_ICON_BOUNTY_HUNTER_TRADER = 1524; public static final int MAP_ICON_IRON_MAN_TUTORS = 1525; public static final int MAP_ICON_PRICING_EXPERT_WEAPONS_AND_ARMOUR = 1526; public static final int MAP_ICON_PRICING_EXPERT_LOGS = 1527; public static final int MAP_ICON_PRICING_EXPERT_HERBS = 1528; public static final int MAP_ICON_PRICING_EXPERT_RUNES = 1529; public static final int MAP_ICON_PRICING_EXPERT_ORES_AND_BARS = 1530; public static final int MAP_ICON_GRAND_EXCHANGE = 1531; public static final int MAP_ICON_KOUREND_TASK = 1532; public static final int MAP_ICON_RAIDS_LOBBY = 1533; public static final int MAP_ICON_MAP_LINK_DOWNSTAIRS = 1534; public static final int MAP_ICON_MAP_LINK_UPSTAIRS = 1535; /* Unmapped: 1536, 1537, 1538 */ public static final int WORLD_MAP_YOU_ARE_HERE = 1539; public static final int WORLD_MAP_OFFSCREEN_FOCUS_ARROW = 1540; public static final int WORLD_MAP_OFFSCREEN_FOCUS_ARROW_DIAGONAL = 1541; public static final int UNKNOWN_BROWN_ARROW_UP = 1542; public static final int UNKNOWN_YELLOW_ARROW_UP = 1543; public static final int DEADMAN_SPECIAL_LOGO = 1544; public static final int UNKNOWN_BACKGROUND_BEIGE = 1545; public static final int BUTTON_METAL_CORNER_TOP_LEFT_HOVERED = 1546; public static final int BUTTON_METAL_CORNER_TOP_RIGHT_HOVERED = 1547; public static final int BUTTON_METAL_CORNER_BOTTOM_LEFT_HOVERED = 1548; public static final int BUTTON_METAL_CORNER_BOTTOM_RIGHT_HOVERED = 1549; public static final int BUTTON_METAL_EDGE_LEFT_HOVERED = 1550; public static final int BUTTON_METAL_EDGE_TOP_HOVERED = 1551; public static final int BUTTON_METAL_EDGE_RIGHT_HOVERED = 1552; public static final int BUTTON_METAL_EDGE_BOTTOM_HOVERED = 1553; public static final int BUTTON_METAL_CORNER_TOP_LEFT = 1554; public static final int BUTTON_METAL_CORNER_TOP_RIGHT = 1555; public static final int BUTTON_METAL_CORNER_BOTTOM_LEFT = 1556; public static final int BUTTON_METAL_CORNER_BOTTOM_RIGHT = 1557; public static final int BUTTON_METAL_EDGE_LEFT = 1558; public static final int BUTTON_METAL_EDGE_TOP = 1559; public static final int BUTTON_METAL_EDGE_RIGHT = 1560; public static final int BUTTON_METAL_EDGE_BOTTOM = 1561; public static final int OPTIONS_FINGER_POINTING_AT_MENU = 1562; public static final int OPTIONS_DISPLAY_ICON_VERTICAL = 1563; public static final int OPTIONS_F1_BUTTON_DISABLED = 1564; public static final int OPTIONS_TWO_FINGERS_POINTING_AT_MAGNIFYING_GLASS = 1565; public static final int OPTIONS_SHIFT_KEY_DISABLED = 1566; public static final int OPTIONS_FINGER_POINTING_AT_PET = 1567; public static final int OPTIONS_SCROLL = 1568; /* Unmapped: 1569, 1570, 1571 */ public static final int OPTIONS_FIXED_MODE_ENABLED = 1572; public static final int OPTIONS_RESIZEABLE_MODE_ENABLED = 1573; public static final int OPTIONS_FIXED_MODE_ENABLED_VERTICAL = 1574; public static final int OPTIONS_RESIZEABLE_MODE_ENABLED_VERTICAL = 1575; public static final int OPTIONS_HOUSE_DOORS_CLOSED = 1576; public static final int OPTIONS_HOUSE_DOORS_OPEN = 1577; public static final int OPTIONS_HOUSE_DOORS_INVISIBLE = 1578; public static final int TAB_QUESTS_BROWN_RAIDING_PARTY_UNUSED = 1579; public static final int TAB_MAGIC_SPELLBOOK_ANCIENT_MAGICKS_UNUSED = 1580; public static final int TAB_MAGIC_SPELLBOOK_LUNAR_UNUSED = 1581; public static final int TAB_QUESTS_BROWN_RAIDING_PARTY = 1582; public static final int TAB_MAGIC_SPELLBOOK_ANCIENT_MAGICKS = 1583; public static final int TAB_MAGIC_SPELLBOOK_LUNAR = 1584; public static final int UNKNOWN_BUTTON_HALF_LEFT_1585 = 1585; public static final int UNKNOWN_BUTTON_HALF_LEFT_GREEN = 1586; public static final int UNKNOWN_BUTTON_HALF_LEFT_FADED_GREEN = 1587; public static final int UNKNOWN_BUTTON_HALF_LEFT_RED = 1588; public static final int UNKNOWN_BUTTON_HALF_LEFT_FADED_RED = 1589; public static final int UNKNOWN_BUTTON_HALF_RIGHT_1590 = 1590; public static final int UNKNOWN_BUTTON_HALF_RIGHT_GREEN = 1591; public static final int UNKNOWN_BUTTON_HALF_RIGHT_FADED_GREEN = 1592; public static final int UNKNOWN_BUTTON_HALF_RIGHT_RED = 1593; public static final int UNKNOWN_BUTTON_HALF_RIGHT_FADED_RED = 1594; public static final int UNKNOWN_SLIM_BUTTON = 1595; public static final int UNKNOWN_SLIM_BUTTON_SELECTED = 1596; /* Unmapped: 1597, 1598, 1599 */ public static final int LOGOUT_THUMB_UP = 1600; public static final int LOGOUT_THUMB_DOWN = 1601; public static final int LOGOUT_THUMB_UP_HOVERED = 1602; public static final int LOGOUT_THUMB_DOWN_HOVERED = 1603; public static final int UNKNOWN_SMALL_HITPOINTS_ICON = 1604; public static final int UNKNOWN_SMALL_PRAYER_ICON = 1605; public static final int UNKNOWN_SMALL_SPECIAL_ICON = 1606; public static final int MINIMAP_ORB_SPECIAL = 1607; public static final int MINIMAP_ORB_SPECIAL_ACTIVATED = 1608; /* Unmapped: 1609 */ public static final int MINIMAP_ORB_SPECIAL_ICON = 1610; public static final int FIXED_MODE_MINIMAP_FRAME_BOTTOM = 1611; /* Unmapped: 1612, 1613, 1614 */ public static final int MOBILE_TUTORIAL_FUNCTION_MODE_BUTTON = 1615; public static final int MOBILE_TUTORIAL_CAMERA_MOVEMENT = 1616; public static final int MOBILE_CONCEPT_SKETCH_UI = 1617; public static final int MOBILE_TUTORIAL_NPC_GESTURE_PRESS = 1618; public static final int MOBILE_TUTORIAL_MINIMISE_WORLD_MAP = 1619; public static final int MOBILE_TUTORIAL_NPC_GESTURE_TAP = 1620; public static final int MOBILE_TUTORIAL_GESTURES_TAP_AND_PRESS = 1621; public static final int MOBILE_CONCEPT_SKETCH_DEVICE = 1622; public static final int MOBILE_FUNCTION_MODE_ENABLED = 1623; public static final int MOBILE_FUNCTION_MODE_DISABLED = 1624; public static final int MOBILE_YELLOW_TOUCH_ANIMATION_1 = 1625; public static final int MOBILE_YELLOW_TOUCH_ANIMATION_2 = 1626; public static final int MOBILE_FINGER_ON_INTERFACE = 1653; /* Unmapped: 1627~1701 */ public static final int BUTTON_FRIENDS = 1702; public static final int BUTTON_IGNORES = 1703; /* Unmapped: 1704~1707 */ public static final int TAB_MAGIC_SPELLBOOK_ARCEUUS_UNUSED = 1708; /* Unmapped: 1709, 1710 */ public static final int TAB_MAGIC_SPELLBOOK_ARCEUUS = 1711; /* Unmapped: 1712~2175 */ public static final int HEALTHBAR_DEFAULT_FRONT_30PX = 2176; public static final int HEALTHBAR_DEFAULT_BACK_30PX = 2177; public static final int HEALTHBAR_DEFAULT_FRONT_50PX = 2178; public static final int HEALTHBAR_DEFAULT_BACK_50PX = 2179; public static final int HEALTHBAR_DEFAULT_FRONT_60PX = 2180; public static final int HEALTHBAR_DEFAULT_BACK_60PX = 2181; public static final int HEALTHBAR_DEFAULT_FRONT_80PX = 2182; public static final int HEALTHBAR_DEFAULT_BACK_80PX = 2183; public static final int HEALTHBAR_DEFAULT_FRONT_100PX = 2184; public static final int HEALTHBAR_DEFAULT_BACK_100PX = 2185; public static final int HEALTHBAR_DEFAULT_FRONT_120PX = 2186; public static final int HEALTHBAR_DEFAULT_BACK_120PX = 2187; public static final int HEALTHBAR_DEFAULT_FRONT_140PX = 2188; public static final int HEALTHBAR_DEFAULT_BACK_140PX = 2189; public static final int HEALTHBAR_DEFAULT_FRONT_160PX = 2190; public static final int HEALTHBAR_DEFAULT_BACK_160PX = 2191; public static final int WIKI_DESELECTED = 2420; public static final int WIKI_SELECTED = 2421; public static final int FRIENDS_CHAT_RANK_SMILEY_FRIEND = 2825; public static final int FRIENDS_CHAT_RANK_CROWN_JAGEX_MODERATOR = 2826; public static final int FRIENDS_CHAT_RANK_KEY_CHANNEL_OWNER = 2827; public static final int FRIENDS_CHAT_RANK_GOLD_STAR_GENERAL = 2828; public static final int FRIENDS_CHAT_RANK_SILVER_STAR_CAPTAIN = 2829; public static final int FRIENDS_CHAT_RANK_BRONZE_STAR_LIEUTENANT = 2830; public static final int FRIENDS_CHAT_RANK_TRIPLE_CHEVRON_SERGEANT = 2831; public static final int FRIENDS_CHAT_RANK_DOUBLE_CHEVRON_CORPORAL = 2832; public static final int FRIENDS_CHAT_RANK_SINGLE_CHEVRON_RECRUIT = 2833; }
package com.exedio.cope.pattern; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import com.exedio.cope.Field; import com.exedio.cope.Cope; import com.exedio.cope.Feature; import com.exedio.cope.FunctionField; import com.exedio.cope.Item; import com.exedio.cope.ItemField; import com.exedio.cope.Pattern; import com.exedio.cope.SetValue; import com.exedio.cope.Type; import com.exedio.cope.UniqueConstraint; public final class Qualifier extends Pattern { private final ItemField<Item> parent; private final FunctionField<?>[] keys; private final List<FunctionField<?>> keyList; private final UniqueConstraint uniqueConstraint; public Qualifier(final UniqueConstraint uniqueConstraint) { if(uniqueConstraint==null) throw new RuntimeException( "argument of qualifier constructor is null, " + "may happen due to bad class initialization order."); final List<FunctionField<?>> uniqueFields = uniqueConstraint.getFields(); if(uniqueFields.size()<2) throw new RuntimeException(uniqueFields.toString()); this.parent = castItemField(uniqueFields.get(0)); this.keys = new FunctionField<?>[uniqueFields.size()-1]; for(int i = 0; i<this.keys.length; i++) this.keys[i] = uniqueFields.get(i+1); this.keyList = Collections.unmodifiableList(Arrays.asList(this.keys)); this.uniqueConstraint = uniqueConstraint; for(final FunctionField field : uniqueFields) registerSource(field); } @SuppressWarnings("unchecked") // OK: UniqueConstraint looses type information private static final ItemField<Item> castItemField(final Field f) { return (ItemField<Item>)f; } // TODO implicit external source: new Qualifier(QualifiedStringQualifier.key)) // TODO internal source: new Qualifier(new StringField(OPTIONAL)) public ItemField<Item> getParent() { return parent; } public List<FunctionField<?>> getKeys() { return keyList; } public UniqueConstraint getUniqueConstraint() { return uniqueConstraint; } private List<Feature> features; public List<Feature> getFeatures() { if(this.features==null) { final Type<?> type = getType(); final Type.This<?> typeThis = type.getThis(); final List<Feature> typeFeatures = type.getFeatures(); final ArrayList<Feature> result = new ArrayList<Feature>(typeFeatures.size()); for(final Feature f : typeFeatures) { if(f!=typeThis && f!=this && f!=parent && !keyList.contains(f) && f!=uniqueConstraint) result.add(f); } result.trimToSize(); this.features = Collections.unmodifiableList(result); } return features; } private List<Field> fields; public List<Field> getAttributes() { if(this.fields==null) { final List<Feature> features = getFeatures(); final ArrayList<Field> result = new ArrayList<Field>(features.size()); for(final Feature f : features) { if(f instanceof Field) result.add((Field)f); } result.trimToSize(); this.fields = Collections.unmodifiableList(result); } return fields; } public Item getQualifier(final Object... keys) { return uniqueConstraint.searchUnique(keys); } public <X> X get(final FunctionField<X> field, final Object... keys) { final Item item = uniqueConstraint.searchUnique(keys); if(item!=null) return field.get(item); else return null; } public Item getForSet(final Object... keys) { Item item = uniqueConstraint.searchUnique(keys); if(item==null) { final SetValue[] keySetValues = new SetValue[keys.length]; int j = 0; for(final FunctionField<?> field : uniqueConstraint.getFields()) keySetValues[j] = Cope.mapAndCast(field, keys[j++]); item = uniqueConstraint.getType().newItem(keySetValues); } return item; } public <X> void set(final FunctionField<X> field, final X value, final Object... keys) { final Item item = getForSet(keys); field.set(item, value); } public Item set(final Object[] keys, final SetValue[] values) { Item item = uniqueConstraint.searchUnique(keys); if(item==null) { final SetValue[] keyValues = new SetValue[values.length + keys.length]; System.arraycopy(values, 0, keyValues, 0, values.length); int j = 0; for(final FunctionField<?> field : uniqueConstraint.getFields()) keyValues[j + values.length] = Cope.mapAndCast(field, keys[j++]); item = uniqueConstraint.getType().newItem(keyValues); } else { item.set(values); } return item; } private static final HashMap<Type<?>, List<Qualifier>> cacheForGetQualifiers = new HashMap<Type<?>, List<Qualifier>>(); /** * Returns all qualifiers where <tt>type</tt> is * the parent type {@link #getParent()}.{@link ItemField#getValueType() getValueType()}. * * @see Relation#getRelations(Type) * @see VectorRelation#getRelations(Type) */ public static final List<Qualifier> getQualifiers(final Type<?> type) { synchronized(cacheForGetQualifiers) { { final List<Qualifier> cachedResult = cacheForGetQualifiers.get(type); if(cachedResult!=null) return cachedResult; } final ArrayList<Qualifier> resultModifiable = new ArrayList<Qualifier>(); for(final ItemField<?> ia : type.getReferences()) for(final Pattern pattern : ia.getPatterns()) { if(pattern instanceof Qualifier) { final Qualifier qualifier = (Qualifier)pattern; if(ia==qualifier.parent) resultModifiable.add(qualifier); } } resultModifiable.trimToSize(); final List<Qualifier> result = !resultModifiable.isEmpty() ? Collections.unmodifiableList(resultModifiable) : Collections.<Qualifier>emptyList(); cacheForGetQualifiers.put(type, result); return result; } } }
package org.openecard.sal; import iso.std.iso_iec._24727.tech.schema.ACLList; import iso.std.iso_iec._24727.tech.schema.ACLListResponse; import iso.std.iso_iec._24727.tech.schema.ACLModify; import iso.std.iso_iec._24727.tech.schema.ACLModifyResponse; import iso.std.iso_iec._24727.tech.schema.AlgorithmInfoType; import iso.std.iso_iec._24727.tech.schema.AuthorizationServiceActionName; import iso.std.iso_iec._24727.tech.schema.CardApplicationConnect; import iso.std.iso_iec._24727.tech.schema.CardApplicationConnectResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationCreate; import iso.std.iso_iec._24727.tech.schema.CardApplicationCreateResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationDelete; import iso.std.iso_iec._24727.tech.schema.CardApplicationDeleteResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationDisconnect; import iso.std.iso_iec._24727.tech.schema.CardApplicationDisconnectResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationEndSession; import iso.std.iso_iec._24727.tech.schema.CardApplicationEndSessionResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationList; import iso.std.iso_iec._24727.tech.schema.CardApplicationListResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationListResponse.CardApplicationNameList; import iso.std.iso_iec._24727.tech.schema.CardApplicationPath; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse.CardAppPathResultSet; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathType; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceActionName; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceCreate; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceCreateResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDelete; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDeleteResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDescribe; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDescribeResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceList; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceListResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceLoad; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceLoadResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationStartSession; import iso.std.iso_iec._24727.tech.schema.CardApplicationStartSessionResponse; import iso.std.iso_iec._24727.tech.schema.Connect; import iso.std.iso_iec._24727.tech.schema.ConnectResponse; import iso.std.iso_iec._24727.tech.schema.ConnectionHandleType; import iso.std.iso_iec._24727.tech.schema.ConnectionServiceActionName; import iso.std.iso_iec._24727.tech.schema.DIDAuthenticate; import iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse; import iso.std.iso_iec._24727.tech.schema.DIDAuthenticationDataType; import iso.std.iso_iec._24727.tech.schema.DIDCreate; import iso.std.iso_iec._24727.tech.schema.DIDCreateResponse; import iso.std.iso_iec._24727.tech.schema.DIDDelete; import iso.std.iso_iec._24727.tech.schema.DIDDeleteResponse; import iso.std.iso_iec._24727.tech.schema.DIDGet; import iso.std.iso_iec._24727.tech.schema.DIDGetResponse; import iso.std.iso_iec._24727.tech.schema.DIDInfoType; import iso.std.iso_iec._24727.tech.schema.DIDList; import iso.std.iso_iec._24727.tech.schema.DIDListResponse; import iso.std.iso_iec._24727.tech.schema.DIDNameListType; import iso.std.iso_iec._24727.tech.schema.DIDQualifierType; import iso.std.iso_iec._24727.tech.schema.DIDStructureType; import iso.std.iso_iec._24727.tech.schema.DIDUpdate; import iso.std.iso_iec._24727.tech.schema.DIDUpdateResponse; import iso.std.iso_iec._24727.tech.schema.DSICreate; import iso.std.iso_iec._24727.tech.schema.DSICreateResponse; import iso.std.iso_iec._24727.tech.schema.DSIDelete; import iso.std.iso_iec._24727.tech.schema.DSIDeleteResponse; import iso.std.iso_iec._24727.tech.schema.DSIList; import iso.std.iso_iec._24727.tech.schema.DSIListResponse; import iso.std.iso_iec._24727.tech.schema.DSIRead; import iso.std.iso_iec._24727.tech.schema.DSIReadResponse; import iso.std.iso_iec._24727.tech.schema.DSIWrite; import iso.std.iso_iec._24727.tech.schema.DSIWriteResponse; import iso.std.iso_iec._24727.tech.schema.DataSetCreate; import iso.std.iso_iec._24727.tech.schema.DataSetCreateResponse; import iso.std.iso_iec._24727.tech.schema.DataSetDelete; import iso.std.iso_iec._24727.tech.schema.DataSetDeleteResponse; import iso.std.iso_iec._24727.tech.schema.DataSetInfoType; import iso.std.iso_iec._24727.tech.schema.DataSetList; import iso.std.iso_iec._24727.tech.schema.DataSetListResponse; import iso.std.iso_iec._24727.tech.schema.DataSetNameListType; import iso.std.iso_iec._24727.tech.schema.DataSetSelect; import iso.std.iso_iec._24727.tech.schema.DataSetSelectResponse; import iso.std.iso_iec._24727.tech.schema.Decipher; import iso.std.iso_iec._24727.tech.schema.DecipherResponse; import iso.std.iso_iec._24727.tech.schema.DifferentialIdentityServiceActionName; import iso.std.iso_iec._24727.tech.schema.Disconnect; import iso.std.iso_iec._24727.tech.schema.DisconnectResponse; import iso.std.iso_iec._24727.tech.schema.Encipher; import iso.std.iso_iec._24727.tech.schema.EncipherResponse; import iso.std.iso_iec._24727.tech.schema.ExecuteAction; import iso.std.iso_iec._24727.tech.schema.ExecuteActionResponse; import iso.std.iso_iec._24727.tech.schema.GetRandom; import iso.std.iso_iec._24727.tech.schema.GetRandomResponse; import iso.std.iso_iec._24727.tech.schema.Hash; import iso.std.iso_iec._24727.tech.schema.HashResponse; import iso.std.iso_iec._24727.tech.schema.Initialize; import iso.std.iso_iec._24727.tech.schema.InitializeResponse; import iso.std.iso_iec._24727.tech.schema.NamedDataServiceActionName; import iso.std.iso_iec._24727.tech.schema.Sign; import iso.std.iso_iec._24727.tech.schema.SignResponse; import iso.std.iso_iec._24727.tech.schema.TargetNameType; import iso.std.iso_iec._24727.tech.schema.Terminate; import iso.std.iso_iec._24727.tech.schema.TerminateResponse; import iso.std.iso_iec._24727.tech.schema.VerifyCertificate; import iso.std.iso_iec._24727.tech.schema.VerifyCertificateResponse; import iso.std.iso_iec._24727.tech.schema.VerifySignature; import iso.std.iso_iec._24727.tech.schema.VerifySignatureResponse; import java.util.Arrays; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import org.openecard.addon.AddonManager; import org.openecard.addon.AddonNotFoundException; import org.openecard.addon.AddonSelector; import org.openecard.addon.HighestVersionSelector; import org.openecard.addon.sal.FunctionType; import org.openecard.addon.sal.SALProtocol; import org.openecard.common.ECardConstants; import org.openecard.common.ECardException; import org.openecard.common.WSHelper; import org.openecard.common.apdu.EraseBinary; import org.openecard.common.apdu.EraseRecord; import org.openecard.common.apdu.Select; import org.openecard.common.apdu.UpdateBinary; import org.openecard.common.apdu.UpdateRecord; import org.openecard.common.apdu.WriteBinary; import org.openecard.common.apdu.WriteRecord; import org.openecard.common.apdu.common.CardCommandAPDU; import org.openecard.common.apdu.common.CardResponseAPDU; import org.openecard.common.apdu.utils.CardUtils; import org.openecard.common.interfaces.Environment; import org.openecard.common.sal.Assert; import org.openecard.common.sal.anytype.CryptoMarkerType; import org.openecard.common.sal.exception.InappropriateProtocolForActionException; import org.openecard.common.sal.exception.IncorrectParameterException; import org.openecard.common.sal.exception.NameExistsException; import org.openecard.common.sal.exception.PrerequisitesNotSatisfiedException; import org.openecard.common.sal.exception.UnknownConnectionHandleException; import org.openecard.common.sal.exception.UnknownProtocolException; import org.openecard.common.sal.state.CardStateEntry; import org.openecard.common.sal.state.CardStateMap; import org.openecard.common.sal.state.cif.CardApplicationWrapper; import org.openecard.common.sal.state.cif.CardInfoWrapper; import org.openecard.common.sal.util.SALUtils; import org.openecard.common.tlv.iso7816.DataElements; import org.openecard.common.tlv.iso7816.FCP; import org.openecard.gui.UserConsent; import org.openecard.ws.SAL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TinySAL implements SAL { private static final Logger logger = LoggerFactory.getLogger(TinySAL.class); private final Environment env; private final CardStateMap states; private AddonSelector protocolSelector; private UserConsent userConsent; /** * Creates a new TinySAL. * * @param env Environment * @param states CardStateMap */ public TinySAL(Environment env, CardStateMap states) { this.env = env; this.states = states; } public void setAddonManager(AddonManager manager) { protocolSelector = new AddonSelector(manager); protocolSelector.setStrategy(new HighestVersionSelector()); } /** * The Initialize function is executed when the ISO24727-3-Interface is invoked for the first time. * The interface is initialised with this function. * See BSI-TR-03112-4, version 1.1.2, section 3.1.1. * * @param request Initialize * @return InitializeResponse */ @Override public InitializeResponse initialize(Initialize request) { return WSHelper.makeResponse(InitializeResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The Terminate function is executed when the ISO24727-3-Interface is terminated. * This function closes all established connections and open sessions. * See BSI-TR-03112-4, version 1.1.2, section 3.1.2. * * @param request Terminate * @return TerminateResponse */ @Override public TerminateResponse terminate(Terminate request) { return WSHelper.makeResponse(TerminateResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The CardApplicationPath function determines a path between the client application and a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.1.3. * * @param request CardApplicationPath * @return CardApplicationPathResponse */ @Override public CardApplicationPathResponse cardApplicationPath(CardApplicationPath request) { CardApplicationPathResponse response = WSHelper.makeResponse(CardApplicationPathResponse.class, WSHelper.makeResultOK()); try { CardApplicationPathType cardAppPath = request.getCardAppPathRequest(); Assert.assertIncorrectParameter(cardAppPath, "The parameter CardAppPathRequest is empty."); Set<CardStateEntry> entries = states.getMatchingEntries(cardAppPath); // Copy entries to result set CardAppPathResultSet resultSet = new CardAppPathResultSet(); List<CardApplicationPathType> resultPaths = resultSet.getCardApplicationPathResult(); for (CardStateEntry entry : entries) { CardApplicationPathType pathCopy = entry.pathCopy(); if (cardAppPath.getCardApplication() != null) { pathCopy.setCardApplication(cardAppPath.getCardApplication()); } else { pathCopy.setCardApplication(entry.getImplicitlySelectedApplicationIdentifier()); } resultPaths.add(pathCopy); } response.setCardAppPathResultSet(resultSet); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationConnect function establishes an unauthenticated connection between the client * application and the card application. * See BSI-TR-03112-4, version 1.1.2, section 3.2.1. * * @param request CardApplicationConnect * @return CardApplicationConnectResponse */ @Override public CardApplicationConnectResponse cardApplicationConnect(CardApplicationConnect request) { CardApplicationConnectResponse response = WSHelper.makeResponse(CardApplicationConnectResponse.class, WSHelper.makeResultOK()); try { CardApplicationPathType cardAppPath = request.getCardApplicationPath(); Assert.assertIncorrectParameter(cardAppPath, "The parameter CardAppPathRequest is empty."); Set<CardStateEntry> cardStateEntrySet = states.getMatchingEntries(cardAppPath, false); Assert.assertIncorrectParameter(cardStateEntrySet, "The given ConnectionHandle is invalid."); /* * [TR-03112-4] If the provided path fragments are valid for more than one card application * the eCard-API-Framework SHALL return any of the possible choices. */ CardStateEntry cardStateEntry = cardStateEntrySet.iterator().next(); byte[] applicationID = cardAppPath.getCardApplication(); if (applicationID == null) { applicationID = cardStateEntry.getImplicitlySelectedApplicationIdentifier(); } Assert.securityConditionApplication(cardStateEntry, applicationID, ConnectionServiceActionName.CARD_APPLICATION_CONNECT); // Connect to the card CardApplicationPathType cardApplicationPath = cardStateEntry.pathCopy(); Connect connect = new Connect(); connect.setContextHandle(cardApplicationPath.getContextHandle()); connect.setIFDName(cardApplicationPath.getIFDName()); connect.setSlot(cardApplicationPath.getSlotIndex()); ConnectResponse connectResponse = (ConnectResponse) env.getDispatcher().deliver(connect); WSHelper.checkResult(connectResponse); // Select the card application CardCommandAPDU select; // TODO: proper determination of path, file and app id if (applicationID.length == 2) { select = new Select.File(applicationID); } else { select = new Select.Application(applicationID); } select.transmit(env.getDispatcher(), connectResponse.getSlotHandle()); cardStateEntry.setCurrentCardApplication(applicationID); cardStateEntry.setSlotHandle(connectResponse.getSlotHandle()); // reset the ef FCP cardStateEntry.unsetFCPOfSelectedEF(); states.addEntry(cardStateEntry); response.setConnectionHandle(cardStateEntry.handleCopy()); response.getConnectionHandle().setCardApplication(applicationID); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationDisconnect function terminates the connection to a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.2.2. * * @param request CardApplicationDisconnect * @return CardApplicationDisconnectResponse */ @Override public CardApplicationDisconnectResponse cardApplicationDisconnect(CardApplicationDisconnect request) { CardApplicationDisconnectResponse response = WSHelper.makeResponse(CardApplicationDisconnectResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] slotHandle = connectionHandle.getSlotHandle(); // check existence of required parameters if (slotHandle == null) { return WSHelper.makeResponse(CardApplicationDisconnectResponse.class, WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, "ConnectionHandle is null")); } Disconnect disconnect = new Disconnect(); disconnect.setSlotHandle(slotHandle); DisconnectResponse disconnectResponse = (DisconnectResponse) env.getDispatcher().deliver(disconnect); // remove entries associated with this handle states.removeSlotHandleEntry(slotHandle); response.setResult(disconnectResponse.getResult()); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * This CardApplicationStartSession function starts a session between the client application and the card application. * See BSI-TR-03112-4, version 1.1.2, section 3.2.3. * * @param request CardApplicationStartSession * @return CardApplicationStartSessionResponse */ @Override public CardApplicationStartSessionResponse cardApplicationStartSession(CardApplicationStartSession request) { CardApplicationStartSessionResponse response = WSHelper.makeResponse(CardApplicationStartSessionResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); Assert.assertIncorrectParameter(didName, "The parameter didName is empty."); DIDAuthenticationDataType didAuthenticationProtocolData = request.getAuthenticationProtocolData(); Assert.assertIncorrectParameter(didAuthenticationProtocolData, "The parameter didAuthenticationProtocolData is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); DIDScopeType didScope = request.getDIDScope(); Assert.assertIncorrectParameter(didScope, "The parameter DIDScope is empty."); ConnectionHandleType samConnectionHandle = request.getSAMConnectionHandle(); Assert.assertIncorrectParameter(samConnectionHandle, "The parameter SAMConnectionHandle is empty."); Assert.securityConditionApplication(cardStateEntry, cardApplicationID, ConnectionServiceActionName.CARD_APPLICATION_START_SESSION); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.CardApplicationStartSession)) { response = protocol.cardApplicationStartSession(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("CardApplicationStartSession", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationEndSession function closes the session between the client application and the card application. * See BSI-TR-03112-4, version 1.1.2, section 3.2.4. * * @param request CardApplicationEndSession * @return CardApplicationEndSessionResponse */ @Override public CardApplicationEndSessionResponse cardApplicationEndSession(CardApplicationEndSession request) { CardApplicationEndSessionResponse response = WSHelper.makeResponse(CardApplicationEndSessionResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); /* DIDName is required for accesing the DID structure. However, this parameter does not appears at ISO-24727-3.xsd. I've added it. */ String didName = SALUtils.getDIDName(request); Assert.assertIncorrectParameter(didName, "The parameter didName is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); Assert.securityConditionApplication(cardStateEntry, cardApplicationID, ConnectionServiceActionName.CARD_APPLICATION_END_SESSION); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.CardApplicationEndSession)) { response = protocol.cardApplicationEndSession(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("CardApplicationEndSession", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationList function returns a list of the available card applications on an eCard. * See BSI-TR-03112-4, version 1.1.2, section 3.3.1. * * @param request CardApplicationList * @return CardApplicationListResponse */ @Override public CardApplicationListResponse cardApplicationList(CardApplicationList request) { CardApplicationListResponse response = WSHelper.makeResponse(CardApplicationListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); Assert.securityConditionApplication(cardStateEntry, cardApplicationID, CardApplicationServiceActionName.CARD_APPLICATION_LIST); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); CardApplicationNameList cardApplicationNameList = new CardApplicationNameList(); cardApplicationNameList.getCardApplicationName().addAll(cardInfoWrapper.getCardApplicationNameList()); response.setCardApplicationNameList(cardApplicationNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } @Override public CardApplicationCreateResponse cardApplicationCreate(CardApplicationCreate request) { CardApplicationCreateResponse response = WSHelper.makeResponse(CardApplicationCreateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = states.getEntry(connectionHandle, false); byte[] cardApplicationName = request.getCardApplicationName(); Assert.assertIncorrectParameter(cardApplicationName, "The parameter CardApplicationName is empty."); AccessControlListType cardApplicationACL = request.getCardApplicationACL(); Assert.assertIncorrectParameter(cardApplicationACL, "The parameter CardApplicationACL is empty."); CardApplicationType cardApplicationType = new CardApplicationType(); cardApplicationType.setApplicationIdentifier(cardApplicationName); cardApplicationType.setCardApplicationACL(cardApplicationACL); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); cardInfoWrapper.getApplicationCapabilities().getCardApplication().add(cardApplicationType); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationDelete function deletes a card application as well as all corresponding * data sets, DSIs, DIDs and services. * See BSI-TR-03112-4, version 1.1.2, section 3.3.3. * * @param request CardApplicationDelete * @return CardApplicationDeleteResponse */ @Override public CardApplicationDeleteResponse cardApplicationDelete(CardApplicationDelete request) { CardApplicationDeleteResponse response = WSHelper.makeResponse(CardApplicationDeleteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationName = request.getCardApplicationName(); Assert.assertIncorrectParameter(cardApplicationName, "The parameter CardApplicationName is empty."); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); Iterator<CardApplicationType> it = cardInfoWrapper.getApplicationCapabilities().getCardApplication().iterator(); while (it.hasNext()) { CardApplicationType next = it.next(); byte[] appNameNext = next.getApplicationIdentifier(); if (Arrays.equals(appNameNext, cardApplicationName)) it.remove(); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationServiceList function returns a list of all avail-able services of a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.3.4. * * @param request CardApplicationServiceList * @return CardApplicationServiceListResponse */ @Override public CardApplicationServiceListResponse cardApplicationServiceList(CardApplicationServiceList request) { CardApplicationServiceListResponse response = WSHelper.makeResponse(CardApplicationServiceListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); //Assert.securityConditionApplication(cardStateEntry, cardApplicationID, CardApplicationServiceActionName.CARD_APPLICATION_SERVICE_LIST); CardApplicationServiceNameList cardApplicationServiceNameList = new CardApplicationServiceNameList(); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); Iterator<CardApplicationType> it = cardInfoWrapper.getApplicationCapabilities().getCardApplication().iterator(); while (it.hasNext()) { CardApplicationType next = it.next(); byte[] appName = next.getApplicationIdentifier(); if (Arrays.equals(appName, cardApplicationID)) { Iterator<CardApplicationServiceType> itt = next.getCardApplicationServiceInfo().iterator(); while (itt.hasNext()) { CardApplicationServiceType nextt = itt.next(); cardApplicationServiceNameList.getCardApplicationServiceName().add(nextt.getCardApplicationServiceName()); } } } response.setCardApplicationServiceNameList(cardApplicationServiceNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The CardApplicationServiceCreate function creates a new service in the card application. * See BSI-TR-03112-4, version 1.1.2, section 3.3.5. * * @param request CardApplicationServiceCreate * @return CardApplicationServiceCreateResponse */ @Override public CardApplicationServiceCreateResponse cardApplicationServiceCreate(CardApplicationServiceCreate request) { return WSHelper.makeResponse(CardApplicationServiceCreateResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * Code for a specific card application service was loaded into the card application with the aid * of the CardApplicationServiceLoad function. * See BSI-TR-03112-4, version 1.1.2, section 3.3.6. * * @param request CardApplicationServiceLoad * @return CardApplicationServiceLoadResponse */ @Override public CardApplicationServiceLoadResponse cardApplicationServiceLoad(CardApplicationServiceLoad request) { return WSHelper.makeResponse(CardApplicationServiceLoadResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The CardApplicationServiceDelete function deletes a card application service in a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.3.7. * * @param request CardApplicationServiceDelete * @return CardApplicationServiceDeleteResponse */ @Override public CardApplicationServiceDeleteResponse cardApplicationServiceDelete(CardApplicationServiceDelete request) { return WSHelper.makeResponse(CardApplicationServiceDeleteResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The CardApplicationServiceDescribe function can be used to request an URI, an URL or a detailed description * of the selected card application service. * See BSI-TR-03112-4, version 1.1.2, section 3.3.8. * * @param request CardApplicationServiceDescribe * @return CardApplicationServiceDescribeResponse */ @Override public CardApplicationServiceDescribeResponse cardApplicationServiceDescribe(CardApplicationServiceDescribe request) { CardApplicationServiceDescribeResponse response = WSHelper.makeResponse(CardApplicationServiceDescribeResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); String cardApplicationServiceName = request.getCardApplicationServiceName(); Assert.assertIncorrectParameter(cardApplicationServiceName, "The parameter CardApplicationServiceName is empty."); //Assert.securityConditionApplication(cardStateEntry, cardApplicationID, CardApplicationServiceActionName.CARD_APPLICATION_SERVICE_DESCRIBE); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); Iterator<CardApplicationType> it = cardInfoWrapper.getApplicationCapabilities().getCardApplication().iterator(); while (it.hasNext()) { CardApplicationType next = it.next(); byte[] appName = next.getApplicationIdentifier(); if (Arrays.equals(appName, cardApplicationID)){ Iterator<CardApplicationServiceType> itt = next.getCardApplicationServiceInfo().iterator(); while (itt.hasNext()) { CardApplicationServiceType nextt = itt.next(); if (nextt.getCardApplicationServiceName().equals(cardApplicationServiceName)) { response.setServiceDescription(nextt.getCardApplicationServiceDescription()); } } } } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The ExecuteAction function permits use of additional card application services by the client application * which are not explicitly specified in [ISO24727-3] but which can be implemented by the eCard with additional code. * See BSI-TR-03112-4, version 1.1.2, section 3.3.9. * * @param request ExecuteAction * @return ExecuteActionResponse */ @Override public ExecuteActionResponse executeAction(ExecuteAction request) { return WSHelper.makeResponse(ExecuteActionResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * The DataSetList function returns the list of the data sets in the card application addressed with the ConnectionHandle. * See BSI-TR-03112-4, version 1.1.2, section 3.4.1. * * @param request DataSetList * @return DataSetListResponse */ @Override public DataSetListResponse dataSetList(DataSetList request) { DataSetListResponse response = WSHelper.makeResponse(DataSetListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); Assert.securityConditionApplication(cardStateEntry, cardApplicationID, NamedDataServiceActionName.DATA_SET_LIST); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); DataSetNameListType dataSetNameList = cardInfoWrapper.getDataSetNameList(cardApplicationID); response.setDataSetNameList(dataSetNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DataSetCreate function creates a new data set in the card application addressed with the * ConnectionHandle (or otherwise in a previously selected data set if this is implemented as a DF). * See BSI-TR-03112-4, version 1.1.2, section 3.4.2. * * @param request DataSetCreate * @return DataSetCreateResponse */ @Override public DataSetCreateResponse dataSetCreate(DataSetCreate request) { DataSetCreateResponse response = WSHelper.makeResponse(DataSetCreateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); AccessControlListType accessControlList = request.getDataSetACL(); Assert.assertIncorrectParameter(accessControlList, "The parameter AccessControlListType is empty."); String dataSetName = request.getDataSetName(); Assert.assertIncorrectParameter(dataSetName, "The parameter DataSetName is empty."); //Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSetName, NamedDataServiceActionName.DATA_SET_CREATE); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); cardInfoWrapper.getDataSetNameList(cardApplicationID).getDataSetName().add(dataSetName); DataSetInfoType dataSetInfo = new DataSetInfoType(); dataSetInfo.setDataSetName(dataSetName); dataSetInfo.setDataSetACL(accessControlList); cardInfoWrapper.getCardApplication(cardApplicationID).getDataSetInfoList().add(dataSetInfo); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DataSetSelect function selects a data set in a card application. * See BSI-TR-03112-4, version 1.1.2, section 3.4.3. * * @param request DataSetSelect * @return DataSetSelectResponse */ @Override public DataSetSelectResponse dataSetSelect(DataSetSelect request) { DataSetSelectResponse response = WSHelper.makeResponse(DataSetSelectResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String dataSetName = request.getDataSetName(); Assert.assertIncorrectParameter(dataSetName, "The parameter DataSetName is empty."); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(dataSetName, applicationID); Assert.assertNamedEntityNotFound(dataSetInfo, "The given DataSet cannot be found."); Assert.securityConditionDataSet(cardStateEntry, applicationID, dataSetName, NamedDataServiceActionName.DATA_SET_SELECT); byte[] fileID = dataSetInfo.getDataSetPath().getEfIdOrPath(); byte[] slotHandle = connectionHandle.getSlotHandle(); CardResponseAPDU result = CardUtils.selectFileWithOptions(env.getDispatcher(), slotHandle, fileID, null, CardUtils.FCP_RESPONSE_DATA); if (result != null) { cardStateEntry.setFCPOfSelectedEF(new FCP(result.getData())); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DataSetDelete function deletes a data set of a card application on an eCard. * See BSI-TR-03112-4, version 1.1.2, section 3.4.4. * * @param request DataSetDelete * @return DataSetDeleteResponse */ @Override public DataSetDeleteResponse dataSetDelete(DataSetDelete request) { DataSetDeleteResponse response = WSHelper.makeResponse(DataSetDeleteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] cardApplicationID = connectionHandle.getCardApplication(); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); String dataSetName = request.getDataSetName(); Assert.assertIncorrectParameter(dataSetName, "The parameter DataSetName is empty."); //Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSetName, NamedDataServiceActionName.DATA_SET_DELETE); cardInfoWrapper.getDataSetNameList(cardApplicationID).getDataSetName().remove(dataSetName); Iterator<DataSetInfoType> it = cardInfoWrapper.getCardApplication(cardApplicationID).getDataSetInfoList().iterator(); while (it.hasNext()) { DataSetInfoType next = it.next(); if (next.getDataSetName().equals(dataSetName)) { it.remove(); } } // XXXX: We should delete the list of DSIs under this dataSet when the Delete command/APDU is implemented. } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The function DSIList supplies the list of the DSI (Data Structure for Interoperability) which exist in the * selected data set. * See BSI-TR-03112-4, version 1.1.2, section 3.4.5. <br> * <br> * Prerequisites: <br> * - a connection to a card application has been established <br> * - a data set has been selected <br> * * @param request DSIList * @return DSIListResponse */ @Override public DSIListResponse dsiList(DSIList request) { DSIListResponse response = WSHelper.makeResponse(DSIListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); byte[] cardApplicationID = connectionHandle.getCardApplication(); if (cardStateEntry.getFCPOfSelectedEF() == null) { throw new PrerequisitesNotSatisfiedException("No EF selected."); } DataSetInfoType dataSet = cardInfoWrapper.getDataSetByFid( cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0)); Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSet.getDataSetName(), NamedDataServiceActionName.DSI_LIST); DSINameListType dsiNameList = new DSINameListType(); for (DSIType dsi : dataSet.getDSI()) { dsiNameList.getDSIName().add(dsi.getDSIName()); } response.setDSINameList(dsiNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DSICreate function creates a DSI (Data Structure for Interoperability) in the currently selected data set. * See BSI-TR-03112-4, version 1.1.2, section 3.4.6. * <br> * <br> * Preconditions: <br> * - Connection to a card application established via CardApplicationConnect <br> * - A data set has been selected with DataSetSelect <br> * - The DSI does not exist in the data set. <br> * * @param request DSICreate * @return DSICreateResponse */ @Override public DSICreateResponse dsiCreate(DSICreate request) { DSICreateResponse response = WSHelper.makeResponse(DSICreateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); byte[] cardApplicationID = connectionHandle.getCardApplication(); byte[] dsiContent = request.getDSIContent(); Assert.assertIncorrectParameter(dsiContent, "The parameter DSIContent is empty."); String dsiName = request.getDSIName(); Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty."); DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName); if (dsi != null) { throw new NameExistsException("There is already an DSI with the name " + dsiName + " in the current EF."); } byte[] slotHandle = connectionHandle.getSlotHandle(); if (cardStateEntry.getFCPOfSelectedEF() == null) { throw new PrerequisitesNotSatisfiedException("No data set for writing selected."); } else { DataSetInfoType dataSet = cardInfoWrapper.getDataSetByFid( cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0)); Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSet.getDataSetName(), NamedDataServiceActionName.DSI_CREATE); DataElements dElements = cardStateEntry.getFCPOfSelectedEF().getDataElements(); if (dElements.isTransparent()) { WriteBinary writeBin = new WriteBinary(WriteBinary.INS_WRITE_BINARY_DATA, (byte) 0x00, (byte) 0x00, dsiContent); writeBin.transmit(env.getDispatcher(), slotHandle); } else if (dElements.isCyclic()) { WriteRecord writeRec = new WriteRecord((byte) 0x00, WriteRecord.WRITE_PREVIOUS, dsiContent); writeRec.transmit(env.getDispatcher(), slotHandle); } else { WriteRecord writeRec = new WriteRecord((byte) 0x00, WriteRecord.WRITE_LAST, dsiContent); writeRec.transmit(env.getDispatcher(), slotHandle); } } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DSIDelete function deletes a DSI (Data Structure for Interoperability) in the currently selected data set. * See BSI-TR-03112-4, version 1.1.2, section 3.4.7. * * @param request DSIDelete * @return DSIDeleteResponse */ @Override public DSIDeleteResponse dsiDelete(DSIDelete request) { DSIDeleteResponse response = WSHelper.makeResponse(DSIDeleteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); String dsiName = request.getDSIName(); Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty."); // TODO check security conditions for dsiDelete //Assert.securityConditionDataSet(cardStateEntry, cardApplicationID, dataSetName, NamedDataServiceActionName.DSI_DELETE); DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName); ArrayList<byte[]> responses = new ArrayList<byte[]>() { { add(new byte[] {(byte) 0x90, (byte) 0x00}); add(new byte[] {(byte) 0x63, (byte) 0xC1}); add(new byte[] {(byte) 0x63, (byte) 0xC2}); add(new byte[] {(byte) 0x63, (byte) 0xC3}); add(new byte[] {(byte) 0x63, (byte) 0xC4}); add(new byte[] {(byte) 0x63, (byte) 0xC5}); add(new byte[] {(byte) 0x63, (byte) 0xC6}); add(new byte[] {(byte) 0x63, (byte) 0xC7}); add(new byte[] {(byte) 0x63, (byte) 0xC8}); add(new byte[] {(byte) 0x63, (byte) 0xC9}); add(new byte[] {(byte) 0x63, (byte) 0xCA}); add(new byte[] {(byte) 0x63, (byte) 0xCB}); add(new byte[] {(byte) 0x63, (byte) 0xCC}); add(new byte[] {(byte) 0x63, (byte) 0xCD}); add(new byte[] {(byte) 0x63, (byte) 0xCE}); add(new byte[] {(byte) 0x63, (byte) 0xCF}); } }; if (cardStateEntry.getFCPOfSelectedEF().getDataElements().isLinear()) { EraseRecord rmRecord = new EraseRecord(dsi.getDSIPath().getIndex()[0], EraseRecord.ERASE_JUST_P1); rmRecord.transmit(env.getDispatcher(), connectionHandle.getSlotHandle(), responses); } else { // NOTE: Erase binary allows to erase only every after the offset or everything in front of the offset. // currently erasing everything after the offset is used. EraseBinary rmBinary = new EraseBinary((byte) 0x00, (byte) 0x00, dsi.getDSIPath().getIndex()); rmBinary.transmit(env.getDispatcher(), connectionHandle.getSlotHandle(), responses); } } catch (ECardException e) { logger.error(e.getMessage(), e); response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DSIWrite function changes the content of a DSI (Data Structure for Interoperability). * See BSI-TR-03112-4, version 1.1.2, section 3.4.8. * For clarification this method updates an existing DSI and does not create a new one. * * The precondition for this method is that a connection to a card application was established and a data set was * selected. Furthermore the DSI exists already. * * @param request DSIWrite * @return DSIWriteResponse */ @Override public DSIWriteResponse dsiWrite(DSIWrite request) { DSIWriteResponse response = WSHelper.makeResponse(DSIWriteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String dsiName = request.getDSIName(); byte[] updateData = request.getDSIContent(); Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty."); Assert.assertIncorrectParameter(updateData, "The parameter DSIContent is empty."); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(dsiName, applicationID); DSIType dsi = cardInfoWrapper.getDSIbyName(dsiName); Assert.assertNamedEntityNotFound(dataSetInfo, "The given DSIName cannot be found."); Assert.securityConditionDataSet(cardStateEntry, applicationID, dsiName, NamedDataServiceActionName.DSI_WRITE); if (! Arrays.equals(dataSetInfo.getDataSetPath().getEfIdOrPath(), cardStateEntry.getFCPOfSelectedEF().getFileIdentifiers().get(0))) { throw new PrerequisitesNotSatisfiedException("The currently selected data set does not contain the DSI " + "to be updated."); } byte[] slotHandle = connectionHandle.getSlotHandle(); if (cardStateEntry.getFCPOfSelectedEF() == null) { throw new PrerequisitesNotSatisfiedException("No EF with DSI selected."); } else if (cardStateEntry.getFCPOfSelectedEF().getDataElements().isTransparent()) { // currently assuming that the index encodes the offset byte[] index = dsi.getDSIPath().getIndex(); UpdateBinary updateBin = new UpdateBinary(index[0], index[1], updateData); updateBin.transmit(env.getDispatcher(), slotHandle); } else { // currently assuming that the index encodes the record number byte index = dsi.getDSIPath().getIndex()[0]; UpdateRecord updateRec = new UpdateRecord(index, updateData); updateRec.transmit(env.getDispatcher(), slotHandle); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DSIRead function reads out the content of a specific DSI (Data Structure for Interoperability). * See BSI-TR-03112-4, version 1.1.2, section 3.4.9. * * @param request DSIRead * @return DSIReadResponse */ @Override public DSIReadResponse dsiRead(DSIRead request) { DSIReadResponse response = WSHelper.makeResponse(DSIReadResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String dsiName = request.getDSIName(); Assert.assertIncorrectParameter(dsiName, "The parameter DSIName is empty."); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(dsiName, applicationID); Assert.assertNamedEntityNotFound(dataSetInfo, "The given DSIName cannot be found."); Assert.securityConditionDataSet(cardStateEntry, applicationID, dsiName, NamedDataServiceActionName.DSI_READ); byte[] slotHandle = connectionHandle.getSlotHandle(); // throws a null pointer if no ef is selected byte[] fileContent = CardUtils.readFile(cardStateEntry.getFCPOfSelectedEF(), env.getDispatcher(), slotHandle); response.setDSIContent(fileContent); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The Encipher function encrypts a transmitted plain text. The detailed behaviour of this function depends on * the protocol of the DID. * See BSI-TR-03112-4, version 1.1.2, section 3.5.1. * * @param request Encipher * @return EncipherResponse */ @Override public EncipherResponse encipher(Encipher request) { EncipherResponse response = WSHelper.makeResponse(EncipherResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] plainText = request.getPlainText(); Assert.assertIncorrectParameter(plainText, "The parameter PlainText is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.Encipher)) { response = protocol.encipher(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("Encipher", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The Decipher function decrypts a given cipher text. The detailed behaviour of this function depends on * the protocol of the DID. * See BSI-TR-03112-4, version 1.1.2, section 3.5.2. * * @param request Decipher * @return DecipherResponse */ @Override public DecipherResponse decipher(Decipher request) { DecipherResponse response = WSHelper.makeResponse(DecipherResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] cipherText = request.getCipherText(); Assert.assertIncorrectParameter(cipherText, "The parameter CipherText is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.Decipher)) { response = protocol.decipher(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("Decipher", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The GetRandom function returns a random number which is suitable for authentication with the DID addressed with DIDName. * See BSI-TR-03112-4, version 1.1.2, section 3.5.3. * * @param request GetRandom * @return GetRandomResponse */ @Override public GetRandomResponse getRandom(GetRandom request) { GetRandomResponse response = WSHelper.makeResponse(GetRandomResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.GetRandom)) { response = protocol.getRandom(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("GetRandom", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The Hash function calculates the hash value of a transmitted message. * See BSI-TR-03112-4, version 1.1.2, section 3.5.4. * * @param request Hash * @return HashResponse */ @Override public HashResponse hash(Hash request) { HashResponse response = WSHelper.makeResponse(HashResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] message = request.getMessage(); Assert.assertIncorrectParameter(message, "The parameter Message is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.Hash)) { response = protocol.hash(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("Hash", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The Sign function signs a transmitted message. * See BSI-TR-03112-4, version 1.1.2, section 3.5.5. * * @param request Sign * @return SignResponse */ @Override public SignResponse sign(Sign request) { SignResponse response = WSHelper.makeResponse(SignResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] message = request.getMessage(); Assert.assertIncorrectParameter(message, "The parameter Message is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.Sign)) { response = protocol.sign(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("Sign", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The VerifySignature function verifies a digital signature. * See BSI-TR-03112-4, version 1.1.2, section 3.5.6. * * @param request VerifySignature * @return VerifySignatureResponse */ @Override public VerifySignatureResponse verifySignature(VerifySignature request) { VerifySignatureResponse response = WSHelper.makeResponse(VerifySignatureResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] signature = request.getSignature(); Assert.assertIncorrectParameter(signature, "The parameter Signature is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.VerifySignature)) { response = protocol.verifySignature(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("VerifySignature", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The VerifyCertificate function validates a given certificate. * See BSI-TR-03112-4, version 1.1.2, section 3.5.7. * * @param request VerifyCertificate * @return VerifyCertificateResponse */ @Override public VerifyCertificateResponse verifyCertificate(VerifyCertificate request) { VerifyCertificateResponse response = WSHelper.makeResponse(VerifyCertificateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle); byte[] applicationID = connectionHandle.getCardApplication(); String didName = SALUtils.getDIDName(request); byte[] certificate = request.getCertificate(); Assert.assertIncorrectParameter(certificate, "The parameter Certificate is empty."); String certificateType = request.getCertificateType(); Assert.assertIncorrectParameter(certificateType, "The parameter CertificateType is empty."); String rootCert = request.getRootCert(); Assert.assertIncorrectParameter(rootCert, "The parameter RootCert is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, applicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.VerifyCertificate)) { response = protocol.verifyCertificate(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("VerifyCertificate", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDList function returns a list of the existing DIDs in the card application addressed by the * ConnectionHandle or the ApplicationIdentifier element within the Filter. * See BSI-TR-03112-4, version 1.1.2, section 3.6.1. * * @param request DIDList * @return DIDListResponse */ @Override public DIDListResponse didList(DIDList request) { DIDListResponse response = WSHelper.makeResponse(DIDListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] appId = connectionHandle.getCardApplication(); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); Assert.securityConditionApplication(cardStateEntry, appId, DifferentialIdentityServiceActionName.DID_LIST); byte[] applicationIDFilter = null; String objectIDFilter = null; String applicationFunctionFilter = null; DIDQualifierType didQualifier = request.getFilter(); if (didQualifier != null) { applicationIDFilter = didQualifier.getApplicationIdentifier(); objectIDFilter = didQualifier.getObjectIdentifier(); applicationFunctionFilter = didQualifier.getApplicationFunction(); } /* * Filter by ApplicationIdentifier. * [TR-03112-4] Allows specifying an application identifier. If this element is present all * DIDs within the specified card application are returned no matter which card application * is currently selected. */ CardApplicationWrapper cardApplication; if (applicationIDFilter != null) { cardApplication = cardStateEntry.getInfo().getCardApplication(applicationIDFilter); Assert.assertIncorrectParameter(cardApplication, "The given CardApplication cannot be found."); } else { cardApplication = cardStateEntry.getCurrentCardApplication(); } List<DIDInfoType> didInfos = new ArrayList<DIDInfoType>(cardApplication.getDIDInfoList()); /* * Filter by ObjectIdentifier. * [TR-03112-4] Allows specifying a protocol OID (cf. [TR-03112-7]) such that only DIDs * which support a given protocol are listed. */ if (objectIDFilter != null) { Iterator<DIDInfoType> it = didInfos.iterator(); while (it.hasNext()) { DIDInfoType next = it.next(); if (!next.getDifferentialIdentity().getDIDProtocol().equals(objectIDFilter)) { it.remove(); } } } /* * Filter by ApplicationFunction. * [TR-03112-4] Allows filtering for DIDs, which support a specific cryptographic operation. * The bit string is coded as the SupportedOperations-element in [ISO7816-15]. */ if (applicationFunctionFilter != null) { Iterator<DIDInfoType> it = didInfos.iterator(); while (it.hasNext()) { DIDInfoType next = it.next(); if (next.getDifferentialIdentity().getDIDMarker().getCryptoMarker() == null) { it.remove(); } else { iso.std.iso_iec._24727.tech.schema.CryptoMarkerType rawMarker; rawMarker = next.getDifferentialIdentity().getDIDMarker().getCryptoMarker(); CryptoMarkerType cryptoMarker = new CryptoMarkerType(rawMarker); AlgorithmInfoType algInfo = cryptoMarker.getAlgorithmInfo(); if (! algInfo.getSupportedOperations().contains(applicationFunctionFilter)) { it.remove(); } } } } DIDNameListType didNameList = new DIDNameListType(); for (DIDInfoType didInfo : didInfos) { didNameList.getDIDName().add(didInfo.getDifferentialIdentity().getDIDName()); } response.setDIDNameList(didNameList); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDCreate function creates a new differential identity in the card application addressed with ConnectionHandle. * See BSI-TR-03112-4, version 1.1.2, section 3.6.2. * * @param request DIDCreate * @return DIDCreateResponse */ @Override public DIDCreateResponse didCreate(DIDCreate request) { DIDCreateResponse response = WSHelper.makeResponse(DIDCreateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] cardApplicationID = connectionHandle.getCardApplication(); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); String didName = request.getDIDName(); Assert.assertIncorrectParameter(didName, "The parameter DIDName is empty."); DIDCreateDataType didCreateData = request.getDIDCreateData(); Assert.assertIncorrectParameter(didCreateData, "The parameter DIDCreateData is empty."); AccessControlListType DidAcl = request.getDIDACL(); Assert.assertIncorrectParameter(DidAcl, "The parameter DIDCreateData is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); Assert.securityConditionDID(cardStateEntry, cardApplicationID, didName, DifferentialIdentityServiceActionName.DID_CREATE); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.DIDCreate)) { response = protocol.didCreate(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("DIDCreate", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The public information for a DID is read with the DIDGet function. * See BSI-TR-03112-4, version 1.1.2, section 3.6.3. * * @param request DIDGet * @return DIDGetResponse */ @Override public DIDGetResponse didGet(DIDGet request) { DIDGetResponse response = WSHelper.makeResponse(DIDGetResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] cardApplicationID = connectionHandle.getCardApplication(); // handle must be requested without application, as it is irrelevant for this call CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); String didName = SALUtils.getDIDName(request); Assert.assertIncorrectParameter(didName, "The parameter DIDName is empty."); DIDScopeType didScope = request.getDIDScope(); Assert.assertIncorrectParameter(didScope, "The parameter DIDScope is empty."); Assert.securityConditionDID(cardStateEntry, cardApplicationID, didName, DifferentialIdentityServiceActionName.DID_GET); DIDStructureType didStructure = SALUtils.getDIDStructure(request, didName, cardStateEntry, connectionHandle); response.setDIDStructure(didStructure); } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDUpdate function creates a new key (marker) for the DID addressed with DIDName. * See BSI-TR-03112-4, version 1.1.2, section 3.6.4. * * @param request DIDUpdate * @return DIDUpdateResponse */ @Override public DIDUpdateResponse didUpdate(DIDUpdate request) { DIDUpdateResponse response = WSHelper.makeResponse(DIDUpdateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] cardApplicationID = connectionHandle.getCardApplication(); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); String didName = request.getDIDName(); Assert.assertIncorrectParameter(didName, "The parameter DIDName is empty."); DIDUpdateDataType didUpdateData = request.getDIDUpdateData(); Assert.assertIncorrectParameter(didUpdateData, "The parameter DIDUpdateData is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); Assert.securityConditionDID(cardStateEntry, cardApplicationID, didName, DifferentialIdentityServiceActionName.DID_UPDATE); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.DIDUpdate)) { response = protocol.didUpdate(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("DIDUpdate", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDDelete function deletes the DID addressed with DIDName. * See BSI-TR-03112-4, version 1.1.2, section 3.6.5. * * @param request DIDDelete * @return DIDDeleteResponse */ @Override public DIDDeleteResponse didDelete(DIDDelete request) { DIDDeleteResponse response = WSHelper.makeResponse(DIDDeleteResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] cardApplicationID = connectionHandle.getCardApplication(); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); String didName = request.getDIDName(); Assert.assertIncorrectParameter(didName, "The parameter DIDName is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); Assert.securityConditionDID(cardStateEntry, cardApplicationID, didName, DifferentialIdentityServiceActionName.DID_DELETE); String protocolURI = didStructure.getDIDMarker().getProtocol(); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.DIDDelete)) { response = protocol.didDelete(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("DIDDelete", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The DIDAuthenticate function can be used to execute an authentication protocol using a DID addressed by DIDName. * See BSI-TR-03112-4, version 1.1.2, section 3.6.6. * * @param request DIDAuthenticate * @return DIDAuthenticateResponse */ @Override public DIDAuthenticateResponse didAuthenticate(DIDAuthenticate request) { DIDAuthenticateResponse response = WSHelper.makeResponse(DIDAuthenticateResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); byte[] cardApplicationID = connectionHandle.getCardApplication(); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); DIDAuthenticationDataType didAuthenticationData = request.getAuthenticationProtocolData(); Assert.assertIncorrectParameter(didAuthenticationData, "The parameter AuthenticationProtocolData is empty."); String protocolURI = didAuthenticationData.getProtocol(); // FIXME: workaround for missing protocol URI from eID-Servers if (protocolURI == null) { logger.warn("ProtocolURI was null"); protocolURI = ECardConstants.Protocol.EAC_GENERIC; } else if (protocolURI.equals("urn:oid:1.0.24727.3.0.0.7.2")) { logger.warn("ProtocolURI was urn:oid:1.0.24727.3.0.0.7.2"); protocolURI = ECardConstants.Protocol.EAC_GENERIC; } didAuthenticationData.setProtocol(protocolURI); String didName = SALUtils.getDIDName(request); Assert.assertIncorrectParameter(didName, "The parameter didName is empty."); DIDStructureType didStructure = cardStateEntry.getDIDStructure(didName, cardApplicationID); Assert.assertNamedEntityNotFound(didStructure, "The given DIDName cannot be found."); DIDScopeType didScope = request.getDIDScope(); Assert.assertIncorrectParameter(didScope, "The parameter DIDScope is empty."); ConnectionHandleType samConnectionHandle = request.getSAMConnectionHandle(); Assert.assertIncorrectParameter(samConnectionHandle, "The parameter SAMConnectionHandle is empty."); Assert.securityConditionDID(cardStateEntry, cardApplicationID, didName, DifferentialIdentityServiceActionName.DID_AUTHENTICATE); SALProtocol protocol = getProtocol(connectionHandle, protocolURI); if (protocol.hasNextStep(FunctionType.DIDAuthenticate)) { response = protocol.didAuthenticate(request); removeFinishedProtocol(connectionHandle, protocolURI, protocol); } else { throw new InappropriateProtocolForActionException("DIDAuthenticate", protocol.toString()); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * The ACLList function returns the access control list for the stated target object (card application, data set, DID). * See BSI-TR-03112-4, version 1.1.2, section 3.7.1. * * @param request ACLList * @return ACLListResponse */ @Override public ACLListResponse aclList(ACLList request) { ACLListResponse response = WSHelper.makeResponse(ACLListResponse.class, WSHelper.makeResultOK()); try { ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request); CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(states, connectionHandle, false); TargetNameType targetName = request.getTargetName(); Assert.assertIncorrectParameter(targetName, "The parameter TargetName is empty."); // get the target values, according to the schema only one must exist, we pick the first existing ;-) byte[] targetAppId = targetName.getCardApplicationName(); String targetDataSet = targetName.getDataSetName(); String targetDid = targetName.getDIDName(); CardInfoWrapper cardInfoWrapper = cardStateEntry.getInfo(); byte[] handleAppId = connectionHandle.getCardApplication(); if (targetDataSet != null) { DataSetInfoType dataSetInfo = cardInfoWrapper.getDataSet(targetDataSet, handleAppId); Assert.assertNamedEntityNotFound(dataSetInfo, "The given DataSet cannot be found."); response.setTargetACL(cardInfoWrapper.getDataSet(targetDataSet, handleAppId).getDataSetACL()); } else if (targetDid != null) { DIDInfoType didInfo = cardInfoWrapper.getDIDInfo(targetDid, handleAppId); Assert.assertNamedEntityNotFound(didInfo, "The given DIDInfo cannot be found."); //TODO Check security condition ? response.setTargetACL(cardInfoWrapper.getDIDInfo(targetDid, handleAppId).getDIDACL()); } else if (targetAppId != null) { CardApplicationWrapper cardApplication = cardInfoWrapper.getCardApplication(targetAppId); Assert.assertNamedEntityNotFound(cardApplication, "The given CardApplication cannot be found."); Assert.securityConditionApplication(cardStateEntry, targetAppId, AuthorizationServiceActionName.ACL_LIST); response.setTargetACL(cardInfoWrapper.getCardApplication(targetAppId).getCardApplicationACL()); } else { throw new IncorrectParameterException("The given TargetName is invalid."); } } catch (ECardException e) { response.setResult(e.getResult()); } catch (Exception e) { logger.error(e.getMessage(), e); response.setResult(WSHelper.makeResult(e)); } return response; } /** * An access rule in the access control list is modified with the ACLModify function. * See BSI-TR-03112-4, version 1.1.2, section 3.7.2. * * @param request ACLModify * @return ACLModifyResponse */ @Override public ACLModifyResponse aclModify(ACLModify request) { return WSHelper.makeResponse(ACLModifyResponse.class, WSHelper.makeResultUnknownError("Not supported yet.")); } /** * Sets the GUI. * * @param uc User consent */ public void setGUI(UserConsent uc) { this.userConsent = uc; } /** * Returns a list of ConnectionHandles. * * @return List of ConnectionHandles */ public List<ConnectionHandleType> getConnectionHandles() { ConnectionHandleType handle = new ConnectionHandleType(); Set<CardStateEntry> entries = states.getMatchingEntries(handle); ArrayList<ConnectionHandleType> result = new ArrayList<ConnectionHandleType>(entries.size()); for (CardStateEntry entry : entries) { result.add(entry.handleCopy()); } return result; } /** * Removes a finished protocol from the SAL instance. * * @param handle Connection Handle * @param protocolURI Protocol URI * @param protocol Protocol * @throws UnknownConnectionHandleException */ public void removeFinishedProtocol(ConnectionHandleType handle, String protocolURI, SALProtocol protocol) throws UnknownConnectionHandleException { if (protocol.isFinished()) { CardStateEntry entry = SALUtils.getCardStateEntry(states, handle); entry.removeProtocol(protocolURI); } } private SALProtocol getProtocol(ConnectionHandleType handle, String protocolURI) throws UnknownProtocolException, UnknownConnectionHandleException { CardStateEntry entry = SALUtils.getCardStateEntry(states, handle); SALProtocol protocol = entry.getProtocol(protocolURI); if (protocol == null) { try { protocol = protocolSelector.getSALProtocol(protocolURI); entry.setProtocol(protocolURI, protocol); } catch (AddonNotFoundException ex) { throw new UnknownProtocolException("The protocol URI '" + protocolURI + "' is not available."); } } protocol.getInternalData().put("cardState", entry); return protocol; } }
package ru.stqa.pft.sandbox; import org.testng.Assert; import org.testng.annotations.Test; public class PointTests { @Test(priority = 0) public void testDistance() { Point p1 = new Point(1, 1); Point p2 = new Point(1, 2); Assert.assertEquals(p1.distance(p2), 1.0); } @Test(priority = 1) public void testDistance2() { Point p1 = new Point(1, 1); Point p2 = new Point(1, 2); Assert.assertNotEquals(p1.distance(p2), 2.0); } }
package com.hal9000.env; import com.hal9000.data.TSPInstance; import com.hal9000.parsers.FileType; import com.hal9000.solver.*; import com.hal9000.time.Timer; import java.util.ArrayList; import java.util.List; /** * Main class */ public class Environment { /** * List of available solvers */ public enum SolverType { GREEDY, STEEPEST, HEURISTIC, RANDOM, TABU, ANNEALING } public final static double eps = 0.00000000001; public List<TSPInstance> instances; private int perInstance; private Report report; public static ArrayList<Long> time; public static long div; /** * @param dict path to directory with instances * @param allowNull allow to parse instances without optimal solution * @param filesDef list of files definitions * @param perInstance number of tests for one instance */ public Environment(String dict, boolean allowNull, List<FileType> filesDef, int perInstance) { this.perInstance = perInstance; report = new FullReport(); instances = new ArrayList<>(); for (FileType ft : filesDef) { instances.addAll(ft.getInstancesFromDict(dict, allowNull)); } time = new ArrayList<>(); for (int i = 0; i < instances.size(); i++) { time.add(0l); } } public Report getReport() { return report; } /** * Creates solver * * @param type solver type * @param instance instance of problem * @return solver created for specific instance * @see SteepestSolver * @see GreedySolver * @see RandomSolver * @see HeuristicSolver */ public Solver createSolver(SolverType type, TSPInstance instance) { switch (type) { case STEEPEST: { return new SteepestSolver(instance); } case GREEDY: { return new GreedySolver(instance); } case HEURISTIC: { return new HeuristicSolver(instance); } case RANDOM: { return new RandomSolver(instance); } case TABU: { return new TabuSearchSolver(instance, 0.4, 0.2, 25, 0.5); } case ANNEALING: { return new SimulatedAnnealingSolver(instance, instance.getDim() * instance.getDim() / 2, 0.95, 10); } } return null; } /** * Runs tests * * @param type solver type * @param timer timer for measurments * @param argument arguments for solver */ public void run(SolverType type, String name, Timer timer, Arg argument) { if (type == SolverType.RANDOM && argument!=null) { for (int i = 0; i < instances.size(); i++) { System.out.println(instances.get(i).getName()); run(type, name, timer, i, new LongArg(((TimeArg)argument).time.get(i)/Environment.div)); } } else { for (int i = 0; i < instances.size(); i++) { System.out.println(instances.get(i).getName()); run(type, name, timer, i, argument); } } } private void run(SolverType type, String name, Timer timer, int instance, Arg argument) { Solution solution = null; for(Integer it : instances.get(instance).getOptimal()){ System.out.print(it + " "); } System.out.println(); for (int i = 0; i < perInstance; i++) { solution = timer.measure(createSolver(type, instances.get(instance)), argument); if(type == SolverType.GREEDY || type == SolverType.STEEPEST) time.set(instance,time.get(instance)+Math.round(solution.getTime()*1000000000)); report.addToReport(name, instances.get(instance), solution); for(Integer it : solution.getSolution()){ System.out.print(it + " "); } System.out.println(); } } }
package org.badvision.outlaweditor.apple; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.List; import javafx.scene.SnapshotParameters; import javafx.scene.canvas.Canvas; import javafx.scene.image.Image; import javafx.scene.image.PixelFormat; import javafx.scene.image.PixelReader; import javafx.scene.image.PixelWriter; import javafx.scene.image.WritableImage; import javafx.scene.paint.Color; import org.badvision.outlaweditor.Platform; import static org.badvision.outlaweditor.apple.AppleNTSCGraphics.hgrToDhgr; public class ImageDitherEngine { int byteRenderWidth; final int errorWindow = 6; final int overlap = 2; final int pixelShift = -3; WritableImage source; byte[] screen; Platform platform; int bufferWidth; int height; int divisor; int[][] coefficients; boolean resetOutput = true; public ImageDitherEngine(Platform platform) { this.platform = platform; byteRenderWidth = platform == Platform.AppleII_DHGR ? 7 : 14; } public void setSourceImage(Image img) { source = getScaledImage(img, bufferWidth * byteRenderWidth, height); resetOutput = true; } private static WritableImage getScaledImage(Image img, int width, int height) { Canvas c = new Canvas(width, height); c.getGraphicsContext2D().drawImage(img, 0, 0, width, height); WritableImage newImg = new WritableImage(width, height); SnapshotParameters sp = new SnapshotParameters(); c.snapshot(sp, newImg); return newImg; } public WritableImage getPreviewImage() { return new WritableImage(bufferWidth * byteRenderWidth, height * 2); } public void setOutputDimensions(int width, int height) { this.bufferWidth = width; this.height = height; screen = platform.imageRenderer.createImageBuffer(width, height); resetOutput = true; } public void setDivisor(int divisor) { this.divisor = divisor; } public void setCoefficients(int[][] coefficients) { this.coefficients = coefficients; } int startX; int startY; public void setTargetCoordinates(int x, int y) { startX = x; startY = y; } WritableImage keepScaled; WritableImage tmpScaled1; WritableImage tmpScaled2; int[] scanline; List<Integer> pixels; public byte[] restartDither(int value) { keepScaled = new WritableImage(source.getPixelReader(), 560, 192); tmpScaled1 = new WritableImage(source.getPixelReader(), 560, 192); tmpScaled2 = new WritableImage(source.getPixelReader(), 560, 192); for (int i = 0; i < screen.length; i++) { screen[i] = (byte) (value >= 0 ? value : (int) Math.floor(Math.random() * 256.0)); } scanline = new int[3]; pixels = new ArrayList<>(); return screen; } public Image getScratchBuffer() { return keepScaled; } public byte[] dither(boolean propagateError) { if (resetOutput) { restartDither(0); resetOutput = false; } keepScaled.getPixelWriter().setPixels(0, 0, 560, 192, source.getPixelReader(), 0, 0); tmpScaled1.getPixelWriter().setPixels(0, 0, 560, 192, source.getPixelReader(), 0, 0); tmpScaled2.getPixelWriter().setPixels(0, 0, 560, 192, source.getPixelReader(), 0, 0); for (int y = 0; y < height; y++) { for (int x = 0; x < bufferWidth; x += 2) { switch (platform) { case AppleII: hiresDither(y, x, propagateError); break; case AppleII_DHGR: doubleHiresDither(y, x, propagateError); break; } } } return screen; } void hiresDither(int y, int x, boolean propagateError) { int bb1 = screen[(y + startY) * bufferWidth + startX + x] & 255; int bb2 = screen[(y + startY) * bufferWidth + startX + x + 1] & 255; int next = bb2 & 127; // Preserve hi-bit so last pixel stays solid, it is a very minor detail int prev = 0; if ((x + startX) > 0) { prev = screen[(y + startY) * bufferWidth + startX + x - 1] & 255; } if ((x + startX) < (bufferWidth-2)) { next = screen[(y + startY) * bufferWidth + startX + x + 2] & 255; } // First byte, compared with a sliding window encompassing the previous byte, if any. int leastError = Integer.MAX_VALUE; for (int hi = 0; hi < 2; hi++) { tmpScaled2.getPixelWriter().setPixels(0, y, 560, (y < 190) ? 3 : (y < 191) ? 2 : 1, keepScaled.getPixelReader(), 0, y); int b1 = (hi << 7); int totalError = 0; for (int c = 0; c < 7; c++) { // for (int c = 6; c >= 0; c--) { int on = b1 | (1 << c); int off = on ^ (1 << c); // get values for "off" int i = hgrToDhgr[0][prev]; scanline[0] = i; i = hgrToDhgr[(i & 0x010000000) >> 20 | off][bb2]; scanline[1] = i; // scanline[2] = hgrToDhgr[(i & 0x10000000) != 0 ? next | 0x0100 : next][0] & 0x0fffffff; int errorOff = getError(x * 14 - overlap + c * 2, y, 28 + c * 2 - overlap + pixelShift, errorWindow, pixels, tmpScaled2.getPixelReader(), scanline); int off1 = pixels.get(c * 2 + 28 + pixelShift); int off2 = pixels.get(c * 2 + 29 + pixelShift); // get values for "on" i = hgrToDhgr[0][prev]; scanline[0] = i; i = hgrToDhgr[(i & 0x010000000) >> 20 | on][bb2]; scanline[1] = i; // scanline[2] = hgrToDhgr[(i & 0x10000000) != 0 ? next | 0x0100 : next][0] & 0x0fffffff; int errorOn = getError(x * 14 - overlap + c * 2, y, 28 + c * 2 - overlap + pixelShift, errorWindow, pixels, tmpScaled2.getPixelReader(), scanline); int on1 = pixels.get(c * 2 + 28 + pixelShift); int on2 = pixels.get(c * 2 + 29 + pixelShift); int[] col1; int[] col2; if (errorOff < errorOn) { totalError += errorOff; b1 = off; col1 = Palette.parseIntColor(off1); col2 = Palette.parseIntColor(off2); } else { totalError += errorOn; b1 = on; col1 = Palette.parseIntColor(on1); col2 = Palette.parseIntColor(on2); } if (propagateError) { propagateError(x * 14 + c * 2 + pixelShift, y, tmpScaled2, col1); propagateError(x * 14 + c * 2 + pixelShift, y, tmpScaled2, col2); } } if (totalError < leastError) { tmpScaled1.getPixelWriter().setPixels(0, y, 560, (y < 190) ? 3 : (y < 191) ? 2 : 1, tmpScaled2.getPixelReader(), 0, y); leastError = totalError; bb1 = b1; } } keepScaled.getPixelWriter().setPixels(0, y, 560, (y < 190) ? 3 : (y < 191) ? 2 : 1, tmpScaled1.getPixelReader(), 0, y); // Second byte, compared with a sliding window encompassing the next byte, if any. leastError = Integer.MAX_VALUE; for (int hi = 0; hi < 2; hi++) { tmpScaled2.getPixelWriter().setPixels(0, y, 560, (y < 190) ? 3 : (y < 191) ? 2 : 1, keepScaled.getPixelReader(), 0, y); int b2 = (hi << 7); int totalError = 0; for (int c = 0; c < 7; c++) { // for (int c = 6; c >= 0; c--) { int on = b2 | (1 << c); int off = on ^ (1 << c); // get values for "off" int i = hgrToDhgr[bb1][off]; scanline[0] = i; scanline[1] = hgrToDhgr[(i & 0x010000000) >> 20 | next][0]; // int errorOff = getError(x * 14 - overlap + c * 2, y, 28 + c * 2 - overlap + pixelShift, errorWindow, pixels, tmpScaled2.getPixelReader(), scanline); int errorOff = getError(x * 14 + 14 - overlap + c * 2, y, 14 + c * 2 - overlap + pixelShift, errorWindow, pixels, tmpScaled2.getPixelReader(), scanline); int off1 = pixels.get(c * 2 + 14 + pixelShift); int off2 = pixels.get(c * 2 + 15 + pixelShift); // get values for "on" i = hgrToDhgr[bb1][on]; scanline[0] = i; scanline[1] = hgrToDhgr[(i & 0x010000000) >> 20 | next][0]; int errorOn = getError(x * 14 + 14 - overlap + c * 2, y, 14 + c * 2 - overlap + pixelShift, errorWindow, pixels, tmpScaled2.getPixelReader(), scanline); int on1 = pixels.get(c * 2 + 14 + pixelShift); int on2 = pixels.get(c * 2 + 15 + pixelShift); int[] col1; int[] col2; if (errorOff < errorOn) { totalError += errorOff; b2 = off; col1 = Palette.parseIntColor(off1); col2 = Palette.parseIntColor(off2); } else { totalError += errorOn; b2 = on; col1 = Palette.parseIntColor(on1); col2 = Palette.parseIntColor(on2); } if (propagateError) { propagateError(x * 14 + c * 2 + 14 + pixelShift, y, tmpScaled2, col1); propagateError(x * 14 + c * 2 + 15 + pixelShift, y, tmpScaled2, col2); } } if (totalError < leastError) { tmpScaled1.getPixelWriter().setPixels(0, y, 560, (y < 190) ? 3 : (y < 191) ? 2 : 1, tmpScaled2.getPixelReader(), 0, y); leastError = totalError; bb2 = b2; } } keepScaled.getPixelWriter().setPixels(0, y, 560, (y < 190) ? 3 : (y < 191) ? 2 : 1, tmpScaled1.getPixelReader(), 0, y); screen[(y + startY) * bufferWidth + startX + x] = (byte) bb1; screen[(y + startY) * bufferWidth + startX + x + 1] = (byte) bb2; } void doubleHiresDither(int y, int x, boolean propagateError) { if (x % 4 != 0) { return; } scanline[0] = 0; if (x >= 4) { scanline[0] = screen[y * 80 + x - 1] << 21; } scanline[1] = 0; if (x < 76) { scanline[2] = screen[y * 80 + x + 4]; } int bytes[] = new int[]{ screen[y * 80 + x] & 255, screen[y * 80 + x + 1] & 255, screen[y * 80 + x + 2] & 255, screen[y * 80 + x + 3] & 255 }; for (int byteOffset = 0; byteOffset < 4; byteOffset++) { // First byte, compared with a sliding window encompassing the previous byte, if any. int leastError = Integer.MAX_VALUE; int b1 = (bytes[byteOffset] & 0x07f); for (int bit = 0; bit < 7; bit++) { int on = b1 | (1 << bit); int off = on ^ (1 << bit); // get values for "off" int i = (byteOffset == 3) ? off : bytes[3] & 255; i <<= 7; i |= (byteOffset == 2) ? off : bytes[2] & 255; i <<= 7; i |= (byteOffset == 1) ? off : bytes[1] & 255; i <<= 7; i |= (byteOffset == 0) ? off : bytes[0] & 255; scanline[1] = i; int errorOff = getError((x + byteOffset) * 7 - overlap + bit, y, 28 + (byteOffset * 7) + bit - overlap + pixelShift, errorWindow, pixels, tmpScaled1.getPixelReader(), scanline); int off1 = pixels.get(byteOffset * 7 + bit + 28 + pixelShift); // get values for "on" i = (byteOffset == 3) ? on : bytes[3] & 255; i <<= 7; i |= (byteOffset == 2) ? on : bytes[2] & 255; i <<= 7; i |= (byteOffset == 1) ? on : bytes[1] & 255; i <<= 7; i |= (byteOffset == 0) ? on : bytes[0] & 255; scanline[1] = i; int errorOn = getError((x + byteOffset) * 7 - overlap + bit, y, 28 + (byteOffset * 7) + bit - overlap + pixelShift, errorWindow, pixels, tmpScaled1.getPixelReader(), scanline); int on1 = pixels.get(byteOffset * 7 + bit + 28 + pixelShift); int[] col1; if (errorOff < errorOn) { b1 = off; col1 = Palette.parseIntColor(off1); } else { b1 = on; col1 = Palette.parseIntColor(on1); } if (propagateError) { propagateError((x + byteOffset) * 7 + bit, y, tmpScaled1, col1); } } keepScaled.getPixelWriter().setPixels(0, y, 560, (y < 190) ? 3 : (y < 191) ? 2 : 1, tmpScaled1.getPixelReader(), 0, y); bytes[byteOffset] = b1; screen[(y + startY) * bufferWidth + startX + x] = (byte) bytes[0]; screen[(y + startY) * bufferWidth + startX + x + 1] = (byte) bytes[1]; screen[(y + startY) * bufferWidth + startX + x + 2] = (byte) bytes[2]; screen[(y + startY) * bufferWidth + startX + x + 3] = (byte) bytes[3]; } } public static int ALPHA_SOLID = 255 << 24; private void propagateError(int x, int y, WritableImage img, int[] newColor) { if (x < 0 || y < 0) return; int pixel = img.getPixelReader().getArgb(x, y); for (int i = 0; i < 3; i++) { int error = Palette.getComponent(pixel, i) - newColor[i]; for (int yy = 0; yy < 3 && y + yy < img.getHeight(); yy++) { for (int xx = -2; xx < 3 && x + xx < img.getWidth(); xx++) { if (x + xx < 0 || coefficients[xx + 2][yy] == 0) { continue; } int c = img.getPixelReader().getArgb(x + xx, y + yy); int errorAmount = ((error * coefficients[xx + 2][yy]) / divisor); img.getPixelWriter().setArgb(x + xx, y + yy, ALPHA_SOLID | Palette.addError(c, i, errorAmount)); } } } } private static int getError(int imageXStart, int y, int scanlineXStart, int window, final List<Integer> pixels, PixelReader source, int[] scanline) { pixels.clear(); PixelWriter fakeWriter = new PixelWriter() { @Override public PixelFormat getPixelFormat() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setArgb(int x, int y, int c) { pixels.add(c); } @Override public void setColor(int i, int i1, Color color) { } @Override public <T extends Buffer> void setPixels(int i, int i1, int i2, int i3, PixelFormat<T> pf, T t, int i4) { } @Override public void setPixels(int i, int i1, int i2, int i3, PixelFormat<ByteBuffer> pf, byte[] bytes, int i4, int i5) { } @Override public void setPixels(int i, int i1, int i2, int i3, PixelFormat<IntBuffer> pf, int[] ints, int i4, int i5) { } @Override public void setPixels(int i, int i1, int i2, int i3, PixelReader reader, int i4, int i5) { } }; AppleImageRenderer.renderScanline(fakeWriter, 0, scanline, true, false, 20); // double max = 0; // double min = Double.MAX_VALUE; double total = 0; // List<Double> err = new ArrayList<>(); for (int p = 0; p < window; p++) { if ((imageXStart + p) < 0 || (imageXStart + p) >= 560 || scanlineXStart + p < 0) { continue; } int[] c1 = Palette.parseIntColor(pixels.get(scanlineXStart + p)); int[] c2 = Palette.parseIntColor(source.getArgb(imageXStart + p, y)); double dist = Palette.distance(c1, c2); total += dist; // max = Math.max(dist, max); // min = Math.min(dist, min); // err.add(dist); } // double avg = total/((double) window); // double range = max-min; // double totalDev = 0.0; // for (Double d : err) { // totalDev = Math.pow(d-avg, 2); //// errorTotal += (d-min)/range; // totalDev /= ((double) window); // double stdDev = Math.sqrt(totalDev); // return (int) (min+(avg*(stdDev/range))); return (int) total; } // int currentPixel = source.getRGB(x, y); // for (int i = 0; i < 3; i++) { // int error = Palette.getComponent(currentPixel, i) - Palette.getComponent(closestColor, i); // if (x + 1 < source.getWidth()) { // int c = source.getRGB(x + 1, y); // source.setRGB(x + 1, y, Palette.addError(c, i, (error * 7) >> 4)); // if (y + 1 < source.getHeight()) { // if (x - 1 > 0) { // int c = source.getRGB(x - 1, y + 1); // source.setRGB(x - 1, y + 1, Palette.addError(c, i, (error * 3) >> 4)); // int c = source.getRGB(x, y + 1); // source.setRGB(x, y + 1, Palette.addError(c, i, (error * 5) >> 4)); // if (x + 1 < source.getWidth()) { // int c = source.getRGB(x + 1, y + 1); // source.setRGB(x + 1, y + 1, Palette.addError(c, i, error >> 4)); // return dest; }
package org.vinesrobotics.bot.opmodes.final_16; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import org.vinesrobotics.bot.R; import org.vinesrobotics.bot.hardware.controllers.Controller; import org.vinesrobotics.bot.hardware.controllers.ControllerState; import org.vinesrobotics.bot.hardware.controllers.Controllers; import org.vinesrobotics.bot.hardware.controllers.enums.Button; import org.vinesrobotics.bot.hardware.controllers.enums.Joystick; import org.vinesrobotics.bot.utils.Utils; import org.vinesrobotics.bot.utils.Vec2D; import java.lang.reflect.InvocationTargetException; @TeleOp(name="ViBoT Hackbot", group="Vines") //@Disabled public class VibotControlled extends VibotHardwareBase { /* Declare OpMode members. */ //Hardware robot = new Hardware(); boolean died = false; Controllers controllers; Controller main_ct; Controller turret_ct; //MotorDeviceGroup leftMotors; //MotorDeviceGroup rightMotors; //Servo arm_1; //double a1_pos = 0; //Servo arm_2; //double a2_pos = 0; //DcMotor itk; //Catapult catapult; //final double a1_target = 0; //final double a2_target = 0; //final int catapult_pos = 255; //final int catapult_root = 0; /* * Code to run ONCE when the driver hits INIT */ @Override public void init_m() { controllers = Controllers.getControllerObjects(this); main_ct = controllers.a(); turret_ct = controllers.b(); lastMain = main_ct.getControllerState(); lastTurret = turret_ct.getControllerState(); } /* * Code to run REPEATEDLY after the driver hits INIT, but before they hit PLAY */ @Override public void init_loop_m() { } /* * Code to run ONCE when the driver hits PLAY */ @Override public void start_m() { if (died) return; } boolean catapult_debug = false; ControllerState lastMain = null; ControllerState lastTurret = null; /* * Code to run REPEATEDLY after the driver hits PLAY but before they hit STOP */ @Override public void loop_m() { if (died) return; ControllerState main = this.main_ct.getControllerState(); ControllerState turret = this.turret_ct.getControllerState(); if (main.isPressed(Button.UP) && !lastMain.isPressed(Button.UP)) catapult_debug = !catapult_debug; Vec2D<Double> left; Vec2D<Double> right; //left = main.joy(Joystick.LEFT); //right = main.joy(Joystick.RIGHT); left = main.joy(Joystick.RIGHT); right = main.joy(Joystick.LEFT); leftMotors.setPower(left.y()); rightMotors.setPower(right.y()); if (main.isPressed(Button.RS) && main.isPressed(Button.LS)) main = null; double itkpw = main.btnVal(Button.RT);// * ( ( main.isPressed(Button.RB) ) ? -1 : 1 ); if (main.isPressed(Button.RB)) itkpw = -itkpw; itk.setPower( itkpw ); // itk.getController().setMotorPower(itk.getPortNumber(),itkpw); if (!catapult.isManual()) { if (!main.isPressed(Button.A)) catapult.ready(); // Use LT LB } else if (catapult.isManualReady() && !main.isPressed(Button.X)){ double catpw = main.btnVal(Button.LT);/// * ( ( main.isPressed(Button.LB) ) ? -1 : 1 ); if (main.isPressed(Button.LB)) catpw = -catpw; catapult.catapult().setPower(catpw); } if (main.isPressed(Button.A)) catapult.fire(); if (main.isPressed(Button.DOWN) && !lastMain.isPressed(Button.DOWN)) catapult.toggleManual(); telemetry.addLine( "Values in range of -1 to +1" ); telemetry.addData( "Speed", (-left.y()-right.y())/2 ); telemetry.addData( "Turning Speed", (-left.y()+right.y())/2 ); telemetry.addData( "Intake Speed", itkpw ); telemetry.addData( "Actual intake speed", itk.getPower() ); updateTelemetry(telemetry); lastMain = main_ct.getControllerState().clone(); lastTurret = turret_ct.getControllerState().clone(); } } // cause evry time I touch i get x felling
package io.spine.code.proto; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.protobuf.DescriptorProtos.DescriptorProto; import com.google.protobuf.DescriptorProtos.FileDescriptorProto; import com.google.protobuf.Descriptors.FileDescriptor; import io.spine.annotation.Internal; import io.spine.logging.Logging; import io.spine.type.KnownTypes; import org.slf4j.Logger; import java.io.File; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Maps.newHashMap; import static com.google.common.collect.Maps.newHashMapWithExpectedSize; import static io.spine.code.proto.Linker.link; import static io.spine.util.Exceptions.newIllegalStateException; import static java.lang.System.lineSeparator; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; /** * A set of proto files represented by their {@linkplain FileDescriptor descriptors}. */ @Internal public final class FileSet implements Logging { private static final FileDescriptor[] EMPTY = {}; /** * All the files of this set. * * <p>Each file is identified by its {@linkplain FileDescriptor#getFullName() full name} * (otherwise, the Protobuf imports would not work). */ private final Map<FileName, FileDescriptor> files; private FileSet(Map<FileName, FileDescriptor> files) { this.files = newHashMap(files); } private FileSet() { this.files = newHashMap(); } /** * Creates an empty set. */ static FileSet newInstance() { return new FileSet(); } /** * Creates a new file set by parsing the passed file if it exists. * * <p>If the file does not exist, returns empty set. */ public static FileSet parseOrEmpty(File descriptorSet) { FileSet result = descriptorSet.exists() ? parse(descriptorSet) : newInstance(); return result; } /** * Creates a new file set by parsing the passed descriptor set file. */ public static FileSet parse(File descriptorSet) { checkNotNull(descriptorSet); checkState(descriptorSet.exists(), "File %s does not exist.", descriptorSet); return doParse(descriptorSet); } public static FileSet parseAsKnownFiles(File descriptorSet) { Set<FileName> fileNames = FileDescriptors.parse(descriptorSet) .stream() .map(FileName::from) .collect(toSet()); Map<FileName, FileDescriptor> knownFiles = KnownTypes.instance() .getAllTypes() .types() .stream() .map(type -> type.descriptor().getFile()) .filter(descriptor -> fileNames.contains(FileName.from(descriptor.getFile()))) .collect(toMap(FileName::from, // File name as the key. file -> file, // File descriptor as the value. (left, right) -> left // On duplicates, take the first option. )); if (knownFiles.size() != fileNames.size()) { return onUnknownFile(knownFiles.keySet(), fileNames); } FileSet result = new FileSet(knownFiles); return result; } private static FileSet onUnknownFile(Set<FileName> knownFiles, Set<FileName> requestedFiles) { Logger log = Logging.get(FileSet.class); log.debug("Failed to find files in the known types set. Looked for {}{}", lineSeparator(), requestedFiles); log.debug("Could not find files: {}", requestedFiles .stream() .filter(fileName -> !knownFiles.contains(fileName)) .map(FileName::toString) .collect(joining(", "))); throw newIllegalStateException("Some files are not known."); } /** * Creates a new file set by parsing the passed descriptor set file. */ private static FileSet doParse(File descriptorSetFile) { Collection<FileDescriptorProto> files = FileDescriptors.parse(descriptorSetFile); return link(files); } /** * Loads main file set from resources. */ public static FileSet load() { Collection<FileDescriptorProto> files = FileDescriptors.load(); return link(files); } /** * Constructs a new {@code FileSet} out of the given file descriptors. * * <p>The file descriptors are linked in order to obtain normal {@code FileDescriptor}s out * of {@code FileDescriptorProto}s. * * @param protoDescriptors * file descriptors to include in the set * @return new file set */ public static FileSet ofFiles(ImmutableSet<FileDescriptorProto> protoDescriptors) { checkNotNull(protoDescriptors); return link(protoDescriptors); } /** * Obtains message declarations, that match the specified {@link java.util.function.Predicate}. * * @param predicate the predicate to test a message * @return the message declarations */ public List<MessageType> findMessageTypes(Predicate<DescriptorProto> predicate) { ImmutableList.Builder<MessageType> result = ImmutableList.builder(); for (FileDescriptor file : files()) { SourceFile sourceFile = SourceFile.from(file); Collection<MessageType> declarations = sourceFile.allThat(predicate); result.addAll(declarations); } return result.build(); } /** * Creates a new set which is a union of this and the passed one. */ public FileSet union(FileSet another) { if (another.isEmpty()) { return this; } if (this.isEmpty()) { return another; } int expectedSize = this.files.size() + another.files.size(); Map<FileName, FileDescriptor> files = newHashMapWithExpectedSize(expectedSize); files.putAll(this.files); files.putAll(another.files); FileSet result = new FileSet(files); return result; } /** * Obtains immutable view of the files in this set. */ public ImmutableSet<FileDescriptor> files() { return ImmutableSet.copyOf(files.values()); } /** * Obtains array with the files of this set. */ FileDescriptor[] toArray() { return files.values() .toArray(EMPTY); } /** * Returns {@code true} if the set contains a file with the passed name, * {@code false} otherwise. */ public boolean contains(FileName fileName) { Optional<FileDescriptor> found = tryFind(fileName); return found.isPresent(); } /** * Returns {@code true} if the set contains all the files with the passed names, * {@code false} otherwise. */ public boolean containsAll(Collection<FileName> fileNames) { FileSet found = find(fileNames); boolean result = found.size() == fileNames.size(); return result; } /** * Obtains the set of the files that match passed names. */ public FileSet find(Collection<FileName> fileNames) { Map<FileName, FileDescriptor> found = newHashMapWithExpectedSize(fileNames.size()); for (FileName name : fileNames) { Optional<FileDescriptor> file = tryFind(name); file.ifPresent(descriptor -> found.put(name, descriptor)); } return new FileSet(found); } /** * Returns an Optional containing the first file that matches the name, if such an file exists. */ public Optional<FileDescriptor> tryFind(FileName fileName) { if (files.containsKey(fileName)) { return Optional.of(files.get(fileName)); } else { return Optional.empty(); } } /** * Adds file to the set. */ @CanIgnoreReturnValue public boolean add(FileDescriptor file) { FileName name = FileName.from(file); Object previous = files.put(name, file); boolean isNew = previous == null; return isNew; } /** * Obtains the size of the set. */ public int size() { int result = files.size(); return result; } /** * Verifies if the set is empty. */ public boolean isEmpty() { boolean result = files.isEmpty(); return result; } /** * Returns a string with alphabetically sorted list of files of this set. */ @Override public String toString() { return MoreObjects.toStringHelper(this) .add("files", files.keySet() .stream() .sorted() .collect(toList())) .toString(); } @Override public int hashCode() { return Objects.hash(files); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } FileSet other = (FileSet) obj; return Objects.equals(this.files, other.files); } }
package com.microsoft.azure.cosmosdb; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.databind.node.ObjectNode; import com.microsoft.azure.cosmosdb.internal.Constants; /** * Represents the offer for a resource in the Azure Cosmos DB database service. */ @SuppressWarnings("serial") public class Offer extends Resource { /** * Initialize an offer object. */ public Offer() { super(); this.setOfferVersion(Constants.Properties.OFFER_VERSION_V1); } /** * Initialize an offer object and copy all properties from the other offer. * * @param otherOffer the Offer object whose properties to copy over. */ public Offer(Offer otherOffer) { super(); String serializedString = otherOffer.toJson(); this.propertyBag = new Offer(serializedString).propertyBag; } /** * Initialize an offer object from json string. * * @param jsonString the json string that represents the offer. */ public Offer(String jsonString) { super(jsonString); } /** * Initialize an offer object from json object. * * @param jsonObject the json object that represents the offer. */ public Offer(ObjectNode jsonObject) { super(jsonObject); } /** * Gets the self-link of a resource to which the resource offer applies. * * @return the resource link. */ public String getResourceLink() { return super.getString(Constants.Properties.RESOURCE_LINK); } /** * Sets the self-link of a resource to which the resource offer applies. * * @param resourceLink the resource link. */ void setResourceLink(String resourceLink) { super.set(Constants.Properties.RESOURCE_LINK, resourceLink); } /** * Sets the target resource id of a resource to which this offer applies. * * @return the resource id. */ public String getOfferResourceId() { return super.getString(Constants.Properties.OFFER_RESOURCE_ID); } /** * Sets the target resource id of a resource to which this offer applies. * * @param resourceId the resource id. */ void setOfferResourceId(String resourceId) { super.set(Constants.Properties.OFFER_RESOURCE_ID, resourceId); } /** * Gets the OfferType for the resource offer. * * @return the offer type. */ public String getOfferType() { return super.getString(Constants.Properties.OFFER_TYPE); } /** * Sets the OfferType for the resource offer. * * @param offerType the offer type. */ public void setOfferType(String offerType) { super.set(Constants.Properties.OFFER_TYPE, offerType); if (StringUtils.isNotEmpty(offerType)) { // OfferType is only supported for V2 offers. this.setOfferVersion(Constants.Properties.OFFER_VERSION_V1); } } /** * Gets the version of the current offer. * * @return the offer version. */ public String getOfferVersion() { return super.getString(Constants.Properties.OFFER_VERSION); } /** * Sets the offer version. * * @param offerVersion the version of the offer. */ public void setOfferVersion(String offerVersion) { super.set(Constants.Properties.OFFER_VERSION, offerVersion); } /** * Gets the content object that contains the details of the offer. * * @return the offer content. */ public ObjectNode getContent() { return super.getObject(Constants.Properties.OFFER_CONTENT); } /** * Sets the offer content that contains the details of the offer. * * @param offerContent the content object. */ public void setContent(ObjectNode offerContent) { super.set(Constants.Properties.OFFER_CONTENT, offerContent); } }
package org.opencps.pki; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.Security; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.PKCS8EncodedKeySpec; import java.util.ArrayList; import java.util.List; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.pkcs.PKCSException; import org.bouncycastle.util.io.pem.PemObject; import org.bouncycastle.util.io.pem.PemReader; import com.itextpdf.text.pdf.AcroFields; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.security.PdfPKCS7; import com.itextpdf.text.pdf.security.PrivateKeySignature; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * @author Nguyen Van Nguyen <nguyennv@iwayvietnam.com> */ public class PdfVerifierTest extends TestCase { private static final String certPath = "./src/test/java/resources/cert.pem"; private static final String keyPath = "./src/test/java/resources/key.pem"; private static final String pdfPath = "./src/test/java/resources/opencps.pdf"; private static final String signImagePath = "./src/test/java/resources/signature.png"; X509Certificate cert; CertificateFactory cf; PdfVerifier verifier; PdfSigner signer; /** * Create the test case */ public PdfVerifierTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(PdfVerifierTest.class); } protected void setUp() throws IOException, OperatorCreationException, PKCSException, GeneralSecurityException { cf = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) cf.generateCertificate(new FileInputStream(new File(certPath))); signer = new PdfSigner(pdfPath, cert); verifier = new PdfVerifier(); signer.setSignatureGraphic(signImagePath); signer.setHashAlgorithm(HashAlgorithm.SHA1); byte[] hash = signer.computeHash(); Security.addProvider(new BouncyCastleProvider()); PemReader pemReader = new PemReader(new InputStreamReader(new FileInputStream(keyPath))); PemObject pemObject = pemReader.readPemObject(); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(pemObject.getContent()); KeyFactory factory = KeyFactory.getInstance("RSA", "BC"); PrivateKey privateKey = factory.generatePrivate(privKeySpec); pemReader.close(); PrivateKeySignature signature = new PrivateKeySignature(privateKey, signer.getHashAlgorithm().toString(), "BC"); byte[] extSignature = signature.sign(hash); signer.sign(extSignature); } public void testVerifySignature() throws IOException, GeneralSecurityException { PdfReader reader = new PdfReader(signer.getSignedFilePath()); AcroFields fields = reader.getAcroFields(); ArrayList<String> names = fields.getSignatureNames(); assertTrue(names.size() > 0); assertEquals(names.get(0), signer.getSignatureFieldName()); for (String name : names) { PdfPKCS7 pkcs7 = fields.verifySignature(name); assertTrue(pkcs7.verify()); } assertFalse(verifier.verifySignature(signer.getSignedFilePath())); } public void testGetSignatureInfo() { List<SignatureInfo> infors = verifier.getSignatureInfo(signer.getSignedFilePath()); SignatureInfo infor = infors.size() > 0 ? infors.get(0) : null; assertEquals("OpenCPS PKI", infor.getCertificateInfo().getCommonName()); } }
package de.lmu.ifi.dbs.elki.result; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.batik.util.SVGConstants; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.result.Result; import de.lmu.ifi.dbs.elki.result.ResultHandler; import de.lmu.ifi.dbs.elki.result.ResultHierarchy; import de.lmu.ifi.dbs.elki.utilities.Alias; import de.lmu.ifi.dbs.elki.utilities.datastructures.hierarchy.Hierarchy; import de.lmu.ifi.dbs.elki.utilities.exceptions.AbortException; import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer; import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID; import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.CommonConstraints; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.EnumParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.FileParameter; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.FileParameter.FileType; import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.IntParameter; import de.lmu.ifi.dbs.elki.visualization.VisualizationTask; import de.lmu.ifi.dbs.elki.visualization.VisualizerContext; import de.lmu.ifi.dbs.elki.visualization.VisualizerParameterizer; import de.lmu.ifi.dbs.elki.visualization.gui.VisualizationPlot; import de.lmu.ifi.dbs.elki.visualization.gui.overview.PlotItem; import de.lmu.ifi.dbs.elki.visualization.projector.Projector; import de.lmu.ifi.dbs.elki.visualization.visualizers.Visualization; /** * Class that automatically generates all visualizations and exports them into * SVG files. To configure the export, you <em>will</em> want to configure the * {@link VisualizerParameterizer}, in particular the pattern for choosing which * visualizers to run. * * @author Erich Schubert * @since 0.5.0 * * @apiviz.composedOf VisualizerParameterizer */ @Alias("de.lmu.ifi.dbs.elki.visualization.ExportVisualizations") public class ExportVisualizations implements ResultHandler { /** * Get a logger for this class. */ private static final Logging LOG = Logging.getLogger(ExportVisualizations.class); /** * File format * * @author Erich Schubert */ public static enum Format { SVG, PNG, PDF, PS, EPS, JPEG } /** * Output folder */ File output; /** * Visualization manager. */ VisualizerParameterizer manager; /** * Ratio for canvas */ double ratio; /** * Base result */ Result baseResult = null; /** * Visualizer context */ VisualizerContext context = null; /** * Output counter. */ Map<String, Integer> counter = new HashMap<>(); /** * Output file format. */ Format format; /** * Image width for pixel output. */ int iwidth; /** * Constructor. * * @param output Output folder * @param manager Parameterizer * @param ratio Canvas ratio * @param format Output file format */ public ExportVisualizations(File output, VisualizerParameterizer manager, double ratio, Format format) { this(output, manager, ratio, format, 1000); } /** * Constructor. * * @param output Output folder * @param manager Parameterizer * @param ratio Canvas ratio * @param format Output file format * @param iwidth Image width for pixel formats */ public ExportVisualizations(File output, VisualizerParameterizer manager, double ratio, Format format, int iwidth) { super(); this.output = output; this.manager = manager; this.ratio = ratio; this.format = format; this.iwidth = iwidth; } @Override public void processNewResult(ResultHierarchy hier, Result newResult) { if(output.isFile()) { throw new AbortException("Output folder cannot be an existing file."); } if(!output.exists() && !output.mkdirs()) { throw new AbortException("Could not create output directory."); } if(this.baseResult == null) { this.baseResult = newResult; context = null; counter = new HashMap<>(); LOG.warning("Note: Reusing visualization exporter for more than one result is untested."); } if(context == null) { context = manager.newContext(hier, baseResult); } // Projected visualizations Hierarchy<Object> vistree = context.getVisHierarchy(); for(Hierarchy.Iter<?> iter2 = vistree.iterAll(); iter2.valid(); iter2.advance()) { if(!(iter2.get() instanceof Projector)) { continue; } Projector proj = (Projector) iter2.get(); // TODO: allow selecting individual projections only. Collection<PlotItem> items = proj.arrange(context); for(PlotItem item : items) { processItem(item); } } for(Hierarchy.Iter<?> iter2 = vistree.iterAll(); iter2.valid(); iter2.advance()) { if(!(iter2.get() instanceof VisualizationTask)) { continue; } VisualizationTask task = (VisualizationTask) iter2.get(); boolean isprojected = false; for(Hierarchy.Iter<?> iter = vistree.iterParents(task); iter.valid(); iter.advance()) { if(iter.get() instanceof Projector) { isprojected = true; break; } } if(isprojected) { continue; } PlotItem pi = new PlotItem(ratio, 1.0, null); pi.add(task); processItem(pi); } } private void processItem(PlotItem item) { // Descend into subitems for(Iterator<PlotItem> iter = item.subitems.iterator(); iter.hasNext();) { processItem(iter.next()); } if(item.taskSize() <= 0) { return; } item.sort(); final double width = item.w, height = item.h; VisualizationPlot svgp = new VisualizationPlot(); svgp.getRoot().setAttribute(SVGConstants.SVG_WIDTH_ATTRIBUTE, "20cm"); svgp.getRoot().setAttribute(SVGConstants.SVG_HEIGHT_ATTRIBUTE, (20 * height / width) + "cm"); svgp.getRoot().setAttribute(SVGConstants.SVG_VIEW_BOX_ATTRIBUTE, "0 0 " + width + " " + height); ArrayList<Visualization> layers = new ArrayList<>(); for(Iterator<VisualizationTask> iter = item.tasks.iterator(); iter.hasNext();) { VisualizationTask task = iter.next(); if(task.hasAnyFlags(VisualizationTask.FLAG_NO_DETAIL | VisualizationTask.FLAG_NO_EXPORT) || !task.visible) { continue; } try { Visualization v = task.getFactory().makeVisualization(task, svgp, width, height, item.proj); layers.add(v); } catch(Exception e) { if(Logging.getLogger(task.getFactory().getClass()).isDebugging()) { LOG.exception("Visualization failed.", e); } else { LOG.warning("Visualizer " + task.getFactory().getClass().getName() + " failed - enable debugging to see details."); } } } if(layers.isEmpty()) { return; } for(Visualization layer : layers) { if(layer.getLayer() == null) { LOG.warning("NULL layer seen."); continue; } svgp.getRoot().appendChild(layer.getLayer()); } svgp.updateStyleElement(); String prefix = null; prefix = (prefix == null && item.proj != null) ? item.proj.getMenuName() : prefix; prefix = (prefix == null && item.tasks.size() > 0) ? item.tasks.get(0).getMenuName() : prefix; prefix = (prefix != null ? prefix : "plot"); // TODO: generate names... Integer count = counter.get(prefix); counter.put(prefix, count = count == null ? 1 : (count + 1)); try { switch(format){ case SVG: { File outname = new File(output, prefix + "-" + count + ".svg"); svgp.saveAsSVG(outname); break; } case PNG: { File outname = new File(output, prefix + "-" + count + ".png"); svgp.saveAsPNG(outname, (int) (iwidth * ratio), iwidth); break; } case PDF: { File outname = new File(output, prefix + "-" + count + ".pdf"); svgp.saveAsPDF(outname); break; } case PS: { File outname = new File(output, prefix + "-" + count + ".ps"); svgp.saveAsPS(outname); break; } case EPS: { File outname = new File(output, prefix + "-" + count + ".eps"); svgp.saveAsEPS(outname); break; } case JPEG: { File outname = new File(output, prefix + "-" + count + ".jpg"); svgp.saveAsJPEG(outname, (int) (iwidth * ratio), iwidth); break; } } } catch(Exception e) { LOG.warning("Export of visualization failed.", e); } for(Visualization layer : layers) { layer.destroy(); } } /** * Parameterization class * * @author Erich Schubert * * @apiviz.exclude */ public static class Parameterizer extends AbstractParameterizer { /** * Parameter to specify the canvas ratio * <p> * Key: {@code -vis.ratio} * </p> * <p> * Default value: 1.33 * </p> */ public static final OptionID RATIO_ID = new OptionID("vis.ratio", "The width/heigh ratio of the output."); /** * Parameter to specify the output folder * <p> * Key: {@code -vis.output} * </p> */ public static final OptionID FOLDER_ID = new OptionID("vis.output", "The output folder."); /** * Parameter to specify the output format * <p> * Key: {@code -vis.format} * </p> */ public static final OptionID FORMAT_ID = new OptionID("vis.format", "File format. Note that some formats requrie additional libraries, only SVG and PNG are default."); /** * Parameter to specify the image width of pixel formats * <p> * Key: {@code -vis.width} * </p> */ public static final OptionID IWIDTH_ID = new OptionID("vis.width", "Image width for pixel formats."); /** * Visualization manager. */ VisualizerParameterizer manager; /** * Output folder */ File output; /** * Ratio for canvas */ double ratio; /** * Output file format. */ Format format; /** * Width of pixel output formats. */ int iwidth = 1000; @Override protected void makeOptions(Parameterization config) { super.makeOptions(config); FileParameter outputP = new FileParameter(FOLDER_ID, FileType.OUTPUT_FILE); if(config.grab(outputP)) { output = outputP.getValue(); } DoubleParameter ratioP = new DoubleParameter(RATIO_ID, 1.33); ratioP.addConstraint(CommonConstraints.GREATER_THAN_ZERO_DOUBLE); if(config.grab(ratioP)) { ratio = ratioP.doubleValue(); } EnumParameter<Format> formatP = new EnumParameter<>(FORMAT_ID, Format.class, Format.SVG); if(config.grab(formatP)) { format = formatP.getValue(); } if(format == Format.PNG || format == Format.JPEG) { IntParameter iwidthP = new IntParameter(IWIDTH_ID, 1000); if(config.grab(iwidthP)) { iwidth = iwidthP.intValue(); } } manager = config.tryInstantiate(VisualizerParameterizer.class); } @Override protected ExportVisualizations makeInstance() { return new ExportVisualizations(output, manager, ratio, format, iwidth); } } }
import android.test.AndroidTestCase; import android.test.RenamingDelegatingContext; import junit.framework.Assert; /** * @author Andrew Fontaine * @version 1.0 * @since 31/10/13 */ public class StoryDBTest extends AndroidTestCase { private StoryDB database; @Override public void setUp() throws Exception { super.setUp(); //TODO Implement RenamingDelegatingContext context = new RenamingDelegatingContext(getContext(), "test_"); database = new StoryDB(context); } public void testSetStoryFragment() throws Exception { Choice choice = new Choice("test", 5); StoryFragment frag = new StoryFragment(3, "testing", choice); Assert.assertTrue("Error inserting fragment", database.setStoryFragment(frag)); } @Override public void tearDown() throws Exception { super.tearDown(); //TODO Implement } }
// -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // This file is part of the LibreOffice project. // This Source Code Form is subject to the terms of the Mozilla Public // This is just a testbed for ideas and implementations. (Still, it might turn // out to be somewhat useful as such while waiting for "real" apps.) package org.libreoffice.experimental.desktop; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.os.Bundle; import android.text.InputType; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.inputmethod.BaseInputConnection; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import com.sun.star.awt.Key; import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.uno.XComponentContext; import org.libreoffice.android.Bootstrap; public class Desktop extends Activity { private static final String TAG = "LODesktop"; /* implementend by desktop */ private static native void spawnMain(); /* implementend by vcl */ public static native void renderVCL(Bitmap bitmap); public static native void setViewSize(int width, int height); public static native void key(char c, short timestamp); public static native void touch(int action, int x, int y, short timestamp); /** * This class contains the state that is initialized once and never changes * (not specific to a document or a view). */ class BootstrapContext { public long timingOverhead; public XComponentContext componentContext; public XMultiComponentFactory mcf; } BootstrapContext bootstrapContext; Bundle extras; // FIXME: we should prolly manage a bitmap buffer here and give it to // VCL to render into ... and pull the WM/stacking pieces up into the Java ... // [ perhaps ;-] // how can we get an event to "create a window" - need a JNI callback I guess ... private void initBootstrapContext() { try { bootstrapContext = new BootstrapContext(); long t0 = System.currentTimeMillis(); long t1 = System.currentTimeMillis(); bootstrapContext.timingOverhead = t1 - t0; Bootstrap.setup(this); // Avoid all the old style OSL_TRACE calls especially in vcl Bootstrap.putenv("SAL_LOG=+WARN+INFO"); bootstrapContext.componentContext = com.sun.star.comp.helper.Bootstrap.defaultBootstrap_InitialComponentContext(); Log.i(TAG, "context is" + (bootstrapContext.componentContext!=null ? " not" : "") + " null"); bootstrapContext.mcf = bootstrapContext.componentContext.getServiceManager(); Log.i(TAG, "mcf is" + (bootstrapContext.mcf!=null ? " not" : "") + " null"); } catch (Exception e) { e.printStackTrace(System.err); finish(); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, "onCreate"); try { String input; // input = getIntent().getStringExtra("input"); // if (input == null) // input = "/assets/test1.odt"; input = "--writer"; // We need to fake up an argv, and the argv[0] even needs to // point to some file name that we can pretend is the "program". // setCommandArgs() will prefix argv[0] with the app's data // directory. String[] argv = { "lo-document-loader", input }; Bootstrap.setCommandArgs(argv); // To enable the sleep below, do: "adb shell setprop // log.tag.LODesktopSleepOnCreate VERBOSE". Yeah, has // nothing to do with logging as such. // This should be after at least one call to something in // the Bootstrap class as it is the static initialiser // that loads the lo-native-code library, and presumably // in ndk-gdb you want to set a breapoint in some native // code... if (Log.isLoggable("LODesktopSleepOnCreate", Log.VERBOSE)) { Log.i(TAG, "Sleeping, start ndk-gdb NOW if you intend to debug"); Thread.sleep(20000); } if (bootstrapContext == null) initBootstrapContext(); Log.i(TAG, "onCreate - set content view"); setContentView(new BitmapView()); spawnMain(); } catch (Exception e) { e.printStackTrace(System.err); finish(); } } static short getTimestamp() { return (short) (System.currentTimeMillis() % Short.MAX_VALUE); } class BitmapView extends View { Bitmap mBitmap; boolean renderedOnce; ScaleGestureDetector gestureDetector; public BitmapView() { super(Desktop.this); setFocusableInTouchMode(true); gestureDetector = new ScaleGestureDetector(Desktop.this, new ScaleGestureDetector.SimpleOnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { Log.i(TAG, "onScale: " + detector.getScaleFactor()); return true; } }); } @Override protected void onDraw(Canvas canvas) { // canvas.drawColor(0xFF1ABCDD); if (mBitmap == null) { Log.i(TAG, "calling Bitmap.createBitmap(" + getWidth() + ", " + getHeight() + ", Bitmap.Config.ARGB_8888)"); mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); setViewSize(getWidth(), getHeight()); } renderVCL(mBitmap); canvas.drawBitmap(mBitmap, 0, 0, null); renderedOnce = true; // re-call ourselves a bit later ... invalidate(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_0: case KeyEvent.KEYCODE_1: case KeyEvent.KEYCODE_2: case KeyEvent.KEYCODE_3: case KeyEvent.KEYCODE_4: case KeyEvent.KEYCODE_5: case KeyEvent.KEYCODE_6: case KeyEvent.KEYCODE_7: case KeyEvent.KEYCODE_8: case KeyEvent.KEYCODE_9: Desktop.key((char) ('0' + keyCode - KeyEvent.KEYCODE_0), Desktop.getTimestamp()); return true; case KeyEvent.KEYCODE_DEL: Desktop.key((char) Key.BACKSPACE, Desktop.getTimestamp()); return true; case KeyEvent.KEYCODE_ENTER: Desktop.key((char) Key.RETURN, Desktop.getTimestamp()); return true; case KeyEvent.KEYCODE_TAB: Desktop.key((char) Key.TAB, Desktop.getTimestamp()); return true; default: return false; } } @Override public boolean onTouchEvent(MotionEvent event) { if (!renderedOnce) return super.onTouchEvent(event); super.onTouchEvent(event); Log.d(TAG, "onTouch (" + event.getX() + "," + event.getY() + ")"); // Just temporary hack. We should not show the keyboard // unconditionally on a ACTION_UP event here. The LO level // should callback to us requesting showing the keyboard // if the user taps in a text area. Also, if the device // has a hardware keyboard, we probably should not show // the soft one unconditionally? But what if the user // wants to input in another script than what the hardware // keyboard covers? if (event.getActionMasked() == MotionEvent.ACTION_UP) { // show the keyboard so we can enter text InputMethodManager imm = (InputMethodManager) getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(this, InputMethodManager.SHOW_FORCED); } switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_UP: case MotionEvent.ACTION_MOVE: Desktop.touch(event.getActionMasked(), (int) event.getX(), (int) event.getY(), Desktop.getTimestamp()); break; } return true; } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { Log.d(TAG, "onCreateInputConnection"); BaseInputConnection fic = new LOInputConnection(this, true); outAttrs.actionLabel = null; outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS; outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE; return fic; } @Override public boolean onCheckIsTextEditor() { Log.d(TAG, "onCheckIsTextEditor"); return renderedOnce; } } class LOInputConnection extends BaseInputConnection { public LOInputConnection(View targetView, boolean fullEditor) { super(targetView, fullEditor); } @Override public boolean commitText(CharSequence text, int newCursorPosition) { Log.i(TAG, "commitText(" + text + ", " + newCursorPosition + ")"); for (int i = 0; i < text.length(); i++) { Desktop.key(text.charAt(i), Desktop.getTimestamp()); } return true; } } } // vim:set shiftwidth=4 softtabstop=4 expandtab:
package com.chiralbehaviors.CoRE.phantasm.model; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import com.chiralbehaviors.CoRE.ExistentialRuleform; import com.chiralbehaviors.CoRE.Ruleform; import com.chiralbehaviors.CoRE.agency.Agency; import com.chiralbehaviors.CoRE.attribute.Attribute; import com.chiralbehaviors.CoRE.attribute.AttributeAuthorization; import com.chiralbehaviors.CoRE.attribute.AttributeValue; import com.chiralbehaviors.CoRE.location.Location; import com.chiralbehaviors.CoRE.meta.Aspect; import com.chiralbehaviors.CoRE.meta.Model; import com.chiralbehaviors.CoRE.meta.NetworkedModel; import com.chiralbehaviors.CoRE.network.NetworkAuthorization; import com.chiralbehaviors.CoRE.network.NetworkRuleform; import com.chiralbehaviors.CoRE.network.XDomainNetworkAuthorization; import com.chiralbehaviors.CoRE.product.Product; import com.chiralbehaviors.CoRE.relationship.Relationship; import com.google.common.base.Function; /** * CRUD for Phantasms. This class is the animation procedure that maintains and * mediates the Phantasm/Facet constructs in Ultrastructure. It's a bit * unwieldy, because of the type signatures required for erasure. Provides a * centralized implementation of Phantasm CRUD and the security model for such. * * @author hhildebrand * */ public class PhantasmCRUD<RuleForm extends ExistentialRuleform<RuleForm, Network>, Network extends NetworkRuleform<RuleForm>> { private final Relationship apply; private final Relationship create; private final Relationship delete; private final Relationship invoke; private final Relationship read; private final Relationship remove; private final Relationship update; protected final Model model; public PhantasmCRUD(Model model) { this.model = model; create = model.getKernel() .getCREATE(); delete = model.getKernel() .getDELETE(); invoke = model.getKernel() .getINVOKE(); read = model.getKernel() .getREAD(); remove = model.getKernel() .getREMOVE(); update = model.getKernel() .getUPDATE(); apply = model.getKernel() .getAPPLY(); } /** * Add the child to the list of children of the instance * * @param facet * @param instance * @param auth * @param child */ public RuleForm addChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth, RuleForm child) { if (instance == null) { return null; } cast(child, auth); NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } networkedModel.link(instance, model.getEntityManager() .getReference(Relationship.class, auth.getChildRelationship() .getId()), child, model.getCurrentPrincipal() .getPrincipal()); return instance; } public RuleForm addChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth, ExistentialRuleform<?, ?> child) { if (instance == null) { return null; } cast(child, auth); NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } ExistentialRuleform<?, ?> childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); if (childAuthClassification instanceof Agency) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Agency) child); } else if (childAuthClassification instanceof Location) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Location) child); } else if (childAuthClassification instanceof Product) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Product) child); } else if (childAuthClassification instanceof Relationship) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Relationship) child); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } return instance; } /** * Add the list of children to the instance * * @param facet * @param instance * @param auth * @param children */ public RuleForm addChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth, List<RuleForm> children) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } children.stream() .filter(child -> checkREAD(child, networkedModel)) .filter(child -> { cast(child, auth); return true; }) .forEach(child -> networkedModel.link(instance, model.getEntityManager() .getReference(Relationship.class, auth.getChildRelationship() .getId()), child, model.getCurrentPrincipal() .getPrincipal())); return instance; } public RuleForm addChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth, List<ExistentialRuleform<?, ?>> children) { if (instance == null) { return null; } NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } ExistentialRuleform<?, ?> childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); children.stream() .filter(child -> checkREAD(child, model.getUnknownNetworkedModel(child))) .filter(child -> { cast(child, auth); return true; }) .forEach(child -> { if (childAuthClassification instanceof Agency) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Agency) child); } else if (childAuthClassification instanceof Location) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Location) child); } else if (childAuthClassification instanceof Product) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Product) child); } else if (childAuthClassification instanceof Relationship) { networkedModel.authorize(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Relationship) child); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } }); return instance; } /** * Apply the facet to the instance * * @param facet * @param instance * @return * @throws SecurityException */ @SuppressWarnings("unchecked") public RuleForm apply(NetworkAuthorization<RuleForm> facet, RuleForm instance, Function<RuleForm, RuleForm> constructor) throws SecurityException { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(facet.getClassification()); if (!networkedModel.checkFacetCapability(model.getCurrentPrincipal() .getPrincipal(), facet, getAPPLY())) { return instance; } networkedModel.initialize(instance, model.getEntityManager() .getReference(facet.getClass(), facet.getId()), model.getCurrentPrincipal() .getPrincipal()); if (!checkInvoke(facet, instance)) { return null; } return constructor.apply(instance); } @SuppressWarnings({ "rawtypes", "unchecked" }) /** * Throws ClassCastException if not an instance of the authorized facet type * * @param ruleform * @param facet */ public void cast(ExistentialRuleform ruleform, NetworkAuthorization authorization) { NetworkedModel networkedModel = model.getUnknownNetworkedModel(ruleform); if (!networkedModel.isAccessible(ruleform, authorization.getAuthorizedRelationship(), authorization.getAuthorizedParent())) { throw new ClassCastException(String.format("%s not of facet type %s:%s", ruleform, authorization.getAuthorizedRelationship() .getName(), authorization.getAuthorizedParent() .getName())); } } @SuppressWarnings({ "rawtypes", "unchecked" }) /** * Throws ClassCastException if not an instance of the to/from facet type, * depending on directionality * * @param ruleform * @param facet */ public void cast(ExistentialRuleform ruleform, XDomainNetworkAuthorization authorization) { NetworkedModel networkedModel = model.getUnknownNetworkedModel(ruleform); Relationship classifier = authorization.isForward() ? authorization.getToRelationship() : authorization.getFromRelationship(); ExistentialRuleform classification = authorization.isForward() ? authorization.getToParent() : authorization.getFromParent(); if (!networkedModel.isAccessible(ruleform, classifier, classification)) { throw new ClassCastException(String.format("%s not of facet type %s:%s", ruleform, classifier.getName(), classification.getName())); } } public boolean checkInvoke(NetworkAuthorization<RuleForm> facet, RuleForm instance) { Agency principal = model.getCurrentPrincipal() .getPrincipal(); NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); Relationship invoke = getINVOKE(); return networkedModel.checkCapability(principal, instance, invoke) && networkedModel.checkFacetCapability(principal, facet, invoke); } /** * Create a new instance of the facet * * @param facet * @param name * @param description * @return * @throws InstantiationException * @throws NoSuchMethodException * @throws SecurityException */ @SuppressWarnings("unchecked") public RuleForm createInstance(NetworkAuthorization<RuleForm> facet, String name, String description, Function<RuleForm, RuleForm> constructor) { NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(facet.getClassification()); if (!networkedModel.checkFacetCapability(model.getCurrentPrincipal() .getPrincipal(), facet, getCREATE())) { return null; } RuleForm instance; try { instance = (RuleForm) Ruleform.initializeAndUnproxy(facet.getClassification()) .getClass() .getConstructor(String.class, String.class, Agency.class) .newInstance(name, description, model.getCurrentPrincipal() .getPrincipal()); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException | NoSuchMethodException e) { throw new IllegalStateException(String.format("Cannot construct instance of existential ruleform for %s", new Aspect<RuleForm>(facet.getClassifier(), facet.getClassification())), e); } networkedModel.initialize(instance, model.getEntityManager() .getReference(facet.getClass(), facet.getId()), model.getCurrentPrincipal() .getPrincipal()); if (!checkInvoke(facet, instance)) { return null; } return constructor.apply(instance); } public Relationship getAPPLY() { return apply; } /** * Answer the attribute value of the instance * * @param facet * @param instance * @param stateAuth * * @return */ public Object getAttributeValue(NetworkAuthorization<RuleForm> facet, RuleForm instance, AttributeAuthorization<RuleForm, Network> stateAuth) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(stateAuth.getNetworkAuthorization() .getClassification()); if (!checkREAD(facet, networkedModel) || !checkREAD(stateAuth, networkedModel)) { return null; } Attribute authorizedAttribute = stateAuth.getAuthorizedAttribute(); if (authorizedAttribute.getIndexed()) { return getIndexedAttributeValue(instance, authorizedAttribute, networkedModel); } else if (authorizedAttribute.getKeyed()) { return getMappedAttributeValue(instance, authorizedAttribute, networkedModel); } Object value = networkedModel.getAttributeValue(instance, authorizedAttribute) .getValue(); return value; } /** * Answer the inferred and immediate network children of the instance * * @param facet * @param instance * @param auth * * @return */ public List<RuleForm> getChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth) { if (instance == null) { return Collections.emptyList(); } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkREAD(facet, networkedModel) || !checkREAD(auth, networkedModel)) { return Collections.emptyList(); } return networkedModel.getChildren(instance, auth.getChildRelationship()) .stream() .filter(child -> networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD())) .collect(Collectors.toList()); } /*** * Answer the xd children of the instance * * @param facet * @param instance * @param auth * * @return */ public List<ExistentialRuleform<?, ?>> getChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth) { if (instance == null) { return Collections.emptyList(); } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkREAD(facet, networkedModel) || !checkREAD(auth, networkedModel)) { return Collections.emptyList(); } ExistentialRuleform<?, ?> childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); List<? extends ExistentialRuleform<?, ?>> result; if (childAuthClassification instanceof Agency) { result = networkedModel.getAuthorizedAgencies(instance, auth.getConnection()); } else if (childAuthClassification instanceof Location) { result = networkedModel.getAuthorizedLocations(instance, auth.getConnection()); } else if (childAuthClassification instanceof Product) { result = networkedModel.getAuthorizedProducts(instance, auth.getConnection()); } else if (childAuthClassification instanceof Relationship) { result = networkedModel.getAuthorizedRelationships(instance, auth.getConnection()); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } NetworkedModel<?, ?, ?, ?> childNetworkModel = model.getUnknownNetworkedModel(childAuthClassification); return result.stream() .filter(child -> childNetworkModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD())) .collect(Collectors.toList()); } public Relationship getCREATE() { return create; } public Relationship getDELETE() { return delete; } /** * Answer the immediate, non inferred children of the instance * * @param facet * @param instance * @param auth * * @return */ public List<RuleForm> getImmediateChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth) { if (instance == null) { return Collections.emptyList(); } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkREAD(facet, networkedModel) || !checkREAD(auth, networkedModel)) { return Collections.emptyList(); } return networkedModel.getImmediateChildren(instance, auth.getChildRelationship()) .stream() .filter(child -> networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD())) .collect(Collectors.toList()); } /** * Answer the list of instances of this facet. * * @param facet * @return */ public List<RuleForm> getInstances(NetworkAuthorization<RuleForm> facet) { NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(facet.getClassification()); if (!networkedModel.checkFacetCapability(model.getCurrentPrincipal() .getPrincipal(), facet, getREAD())) { return Collections.emptyList(); } return networkedModel.getChildren(facet.getClassification(), facet.getClassifier() .getInverse()) .stream() .filter(instance -> checkREAD(networkedModel, instance)) .collect(Collectors.toList()); } public Relationship getINVOKE() { return invoke; } public Model getModel() { return model; } public Relationship getREAD() { return read; } public Relationship getREMOVE() { return remove; } /** * Answer the singular network child of the instance * * @param facet * @param instance * @param auth * * @return */ public RuleForm getSingularChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkREAD(facet, networkedModel) || !checkREAD(auth, networkedModel)) { return null; } RuleForm child = networkedModel.getImmediateChild(instance, auth.getChildRelationship()); return checkREAD(child, networkedModel) ? child : null; } /** * Answer the singular xd child of the instance * * @param facet * @param instance * @param auth * * @return */ public ExistentialRuleform<?, ?> getSingularChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkREAD(facet, networkedModel) || !checkREAD(auth, networkedModel)) { return null; } @SuppressWarnings("rawtypes") ExistentialRuleform childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); @SuppressWarnings("rawtypes") ExistentialRuleform child; if (childAuthClassification instanceof Agency) { child = networkedModel.getAuthorizedAgency(instance, auth.getConnection()); } else if (childAuthClassification instanceof Location) { child = networkedModel.getAuthorizedLocation(instance, auth.getConnection()); } else if (childAuthClassification instanceof Product) { child = networkedModel.getAuthorizedProduct(instance, auth.getConnection()); } else if (childAuthClassification instanceof Relationship) { child = networkedModel.getAuthorizedRelationship(instance, auth.getConnection()); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } return checkREAD(child, model.getUnknownNetworkedModel(childAuthClassification)) ? child : null; } public Relationship getUPDATE() { return update; } public List<ExistentialRuleform<?, ?>> lookup(NetworkAuthorization<?> auth, List<String> ids) { NetworkedModel<?, ?, ?, ?> networkedModel = model.getUnknownNetworkedModel(auth.getClassification()); return ids.stream() .map(id -> networkedModel.find(UUID.fromString(id))) .filter(rf -> rf != null) .filter(child -> networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD())) .collect(Collectors.toList()); } public ExistentialRuleform<?, ?> lookup(NetworkAuthorization<?> auth, String id) { NetworkedModel<?, ?, ?, ?> networkedModel = model.getUnknownNetworkedModel(auth.getClassification()); return Optional.of(networkedModel.find(UUID.fromString(id))) .filter(rf -> rf != null) .filter(child -> networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD())) .get(); } public List<RuleForm> lookupRuleForm(NetworkAuthorization<RuleForm> auth, List<String> ids) { NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); return ids.stream() .map(id -> networkedModel.find(UUID.fromString(id))) .filter(rf -> rf != null) .filter(child -> networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD())) .collect(Collectors.toList()); } /** * Remove the facet from the instance * * @param facet * @param instance * @return * @throws SecurityException */ public RuleForm remove(NetworkAuthorization<RuleForm> facet, RuleForm instance, boolean deleteAttributes) throws SecurityException { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(facet.getClassification()); if (!networkedModel.checkFacetCapability(model.getCurrentPrincipal() .getPrincipal(), facet, getREMOVE())) { return instance; } networkedModel.initialize(instance, facet, model.getCurrentPrincipal() .getPrincipal()); return instance; } /** * Remove a child from the instance * * @param facet * @param instance * @param auth * @param child */ public RuleForm removeChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth, RuleForm child) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } networkedModel.unlink(instance, auth.getChildRelationship(), child); return instance; } public RuleForm removeChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth, ExistentialRuleform<?, ?> child) { if (instance == null) { return null; } NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } @SuppressWarnings("rawtypes") ExistentialRuleform childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); if (childAuthClassification instanceof Agency) { networkedModel.deauthorize(instance, auth.getConnection(), (Agency) child); } else if (childAuthClassification instanceof Location) { networkedModel.deauthorize(instance, auth.getConnection(), (Location) child); } else if (childAuthClassification instanceof Product) { networkedModel.deauthorize(instance, auth.getConnection(), (Product) child); } else if (childAuthClassification instanceof Relationship) { networkedModel.deauthorize(instance, auth.getConnection(), (Relationship) child); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } return instance; } /** * Remove the immediate child links from the instance * * @param facet * @param instance * @param auth * @param children */ public RuleForm removeChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth, List<RuleForm> children) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } for (RuleForm child : children) { networkedModel.unlink(instance, auth.getChildRelationship(), child); } return instance; } public RuleForm removeChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth, List<ExistentialRuleform<?, ?>> children) { if (instance == null) { return null; } NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } ExistentialRuleform<?, ?> childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); for (ExistentialRuleform<?, ?> child : children) { if (childAuthClassification instanceof Agency) { networkedModel.deauthorize(instance, auth.getConnection(), (Agency) child); } else if (childAuthClassification instanceof Location) { networkedModel.deauthorize(instance, auth.getConnection(), (Location) child); } else if (childAuthClassification instanceof Product) { networkedModel.deauthorize(instance, auth.getConnection(), (Product) child); } else if (childAuthClassification instanceof Relationship) { networkedModel.deauthorize(instance, auth.getConnection(), (Relationship) child); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } } return instance; } public RuleForm setAttributeValue(NetworkAuthorization<RuleForm> facet, RuleForm instance, AttributeAuthorization<RuleForm, Network> stateAuth, List<Object> value) { return setAttributeValue(facet, instance, stateAuth, value.toArray()); } public RuleForm setAttributeValue(NetworkAuthorization<RuleForm> facet, RuleForm instance, AttributeAuthorization<RuleForm, Network> stateAuth, Map<String, Object> value) { NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(stateAuth, networkedModel)) { return instance; } setAttributeMap(instance, stateAuth.getAuthorizedAttribute(), value, networkedModel); return instance; } public RuleForm setAttributeValue(NetworkAuthorization<RuleForm> facet, RuleForm instance, AttributeAuthorization<RuleForm, Network> stateAuth, Object value) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(stateAuth.getNetworkAuthorization() .getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(stateAuth, networkedModel)) { return instance; } networkedModel.getAttributeValue(instance, model.getEntityManager() .getReference(Attribute.class, stateAuth.getAuthorizedAttribute() .getId())) .setValue(value); return instance; } public RuleForm setAttributeValue(NetworkAuthorization<RuleForm> facet, RuleForm instance, AttributeAuthorization<RuleForm, Network> stateAuth, Object[] value) { NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(stateAuth, networkedModel)) { return instance; } setAttributeArray(instance, stateAuth.getAuthorizedAttribute(), value, networkedModel); return instance; } /** * Set the immediate children of the instance to be the list of supplied * children. No inferred links will be explicitly added or deleted. * * @param facet * @param instance * @param auth * @param children */ public RuleForm setChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth, List<RuleForm> children) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } for (NetworkRuleform<RuleForm> childLink : networkedModel.getImmediateChildrenLinks(instance, auth.getChildRelationship())) { model.getEntityManager() .remove(childLink); } Relationship reference = model.getEntityManager() .getReference(Relationship.class, auth.getChildRelationship() .getId()); children.stream() .filter(child -> checkREAD(child, networkedModel)) .filter(child -> { cast(child, auth); return true; }) .forEach(child -> networkedModel.link(instance, reference, child, model.getCurrentPrincipal() .getPrincipal())); return instance; } /** * Set the xd children of the instance. * * @param facet * @param instance * @param auth * @param children */ @SuppressWarnings({ "unchecked", "rawtypes" }) public RuleForm setChildren(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth, List<?> children) { if (instance == null) { return null; } NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } children.stream() .forEach(child -> cast((ExistentialRuleform) child, auth)); ExistentialRuleform childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); if (childAuthClassification instanceof Agency) { networkedModel.setAuthorizedAgencies(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (List<Agency>) children); } else if (childAuthClassification instanceof Location) { networkedModel.setAuthorizedLocations(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (List<Location>) children); } else if (childAuthClassification instanceof Product) { networkedModel.setAuthorizedProducts(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (List<Product>) children); } else if (childAuthClassification instanceof Relationship) { networkedModel.setAuthorizedRelationships(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (List<Relationship>) children); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } return instance; } /** * @param description * @param id * @return */ public RuleForm setDescription(RuleForm instance, String description) { if (instance == null) { return null; } NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(instance, networkedModel)) { return instance; } instance.setDescription(description); return instance; } public RuleForm setName(RuleForm instance, String name) { if (instance == null) { return null; } NetworkedModel<RuleForm, Network, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(instance, networkedModel)) { return instance; } instance.setName(name); return instance; } /** * Set the singular child of the instance. * * @param facet * @param instance * @param auth * @param child */ public RuleForm setSingularChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, NetworkAuthorization<RuleForm> auth, RuleForm child) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(auth.getClassification()); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } if (child == null) { networkedModel.unlinkImmediate(child, auth.getChildRelationship()); } else { cast(child, auth); networkedModel.setImmediateChild(instance, model.getEntityManager() .getReference(Relationship.class, auth.getChildRelationship() .getId()), child, model.getCurrentPrincipal() .getPrincipal()); } return instance; } /** * Set the singular xd child of the instance * * @param facet * @param instance * @param auth * @param child * * @return */ public RuleForm setSingularChild(NetworkAuthorization<RuleForm> facet, RuleForm instance, XDomainNetworkAuthorization<?, ?> auth, ExistentialRuleform<?, ?> child) { if (instance == null) { return null; } NetworkedModel<RuleForm, ?, ?, ?> networkedModel = model.getNetworkedModel(instance); if (!checkUPDATE(facet, networkedModel) || !checkUPDATE(auth, networkedModel)) { return instance; } cast(child, auth); ExistentialRuleform<?, ?> childAuthClassification = auth.isForward() ? auth.getToParent() : auth.getFromParent(); if (childAuthClassification instanceof Agency) { networkedModel.authorizeSingular(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Agency) child); } else if (childAuthClassification instanceof Location) { networkedModel.authorizeSingular(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Location) child); } else if (childAuthClassification instanceof Product) { networkedModel.authorizeSingular(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Product) child); } else if (childAuthClassification instanceof Relationship) { networkedModel.authorizeSingular(instance, model.getEntityManager() .getReference(Relationship.class, auth.getConnection() .getId()), (Relationship) child); } else { throw new IllegalArgumentException(String.format("Invalid XdAuth %s -> %s", instance.getClass() .getSimpleName(), childAuthClassification.getClass() .getSimpleName())); } return instance; } private boolean checkREAD(AttributeAuthorization<RuleForm, Network> stateAuth, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), stateAuth, getREAD()); } private boolean checkREAD(@SuppressWarnings("rawtypes") ExistentialRuleform child, NetworkedModel<?, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getREAD()); } private boolean checkREAD(NetworkAuthorization<RuleForm> auth, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { return networkedModel.checkFacetCapability(model.getCurrentPrincipal() .getPrincipal(), auth, getREAD()); } private boolean checkREAD(NetworkedModel<RuleForm, ?, ?, ?> networkedModel, RuleForm instance) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), instance, getREAD()); } private boolean checkREAD(XDomainNetworkAuthorization<?, ?> auth, NetworkedModel<?, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), auth, getREAD()); } private boolean checkUPDATE(AttributeAuthorization<RuleForm, Network> stateAuth, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), stateAuth, getUPDATE()); } private boolean checkUPDATE(@SuppressWarnings("rawtypes") ExistentialRuleform child, NetworkedModel<?, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), child, getUPDATE()); } private boolean checkUPDATE(NetworkAuthorization<RuleForm> auth, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), auth, getUPDATE()); } private boolean checkUPDATE(XDomainNetworkAuthorization<?, ?> auth, NetworkedModel<?, ?, ?, ?> networkedModel) { return networkedModel.checkCapability(model.getCurrentPrincipal() .getPrincipal(), auth, getUPDATE()); } private Object[] getIndexedAttributeValue(RuleForm instance, Attribute authorizedAttribute, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { AttributeValue<RuleForm>[] attributeValues = getValueArray(instance, authorizedAttribute, networkedModel); Object[] values = (Object[]) Array.newInstance(authorizedAttribute.valueClass(), attributeValues.length); for (AttributeValue<RuleForm> value : attributeValues) { values[value.getSequenceNumber()] = value.getValue(); } return values; } private Map<String, Object> getMappedAttributeValue(RuleForm instance, Attribute authorizedAttribute, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { Map<String, Object> map = new HashMap<>(); for (Map.Entry<String, AttributeValue<RuleForm>> entry : getValueMap(instance, authorizedAttribute, networkedModel).entrySet()) { map.put(entry.getKey(), entry.getValue() .getValue()); } return map; } private AttributeValue<RuleForm>[] getValueArray(RuleForm instance, Attribute attribute, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { List<? extends AttributeValue<RuleForm>> values = networkedModel.getAttributeValues(instance, attribute); int max = 0; for (AttributeValue<RuleForm> value : values) { max = Math.max(max, value.getSequenceNumber() + 1); } @SuppressWarnings("unchecked") AttributeValue<RuleForm>[] returnValue = new AttributeValue[max]; for (AttributeValue<RuleForm> form : values) { returnValue[form.getSequenceNumber()] = form; } return returnValue; } private Map<String, AttributeValue<RuleForm>> getValueMap(RuleForm instance, Attribute attribute, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { Map<String, AttributeValue<RuleForm>> map = new HashMap<>(); for (AttributeValue<RuleForm> value : networkedModel.getAttributeValues(instance, attribute)) { map.put(value.getKey(), value); } return map; } private AttributeValue<RuleForm> newAttributeValue(RuleForm instance, Attribute attribute, int i, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { AttributeValue<RuleForm> value = networkedModel.create(instance, attribute, model.getCurrentPrincipal() .getPrincipal()); value.setSequenceNumber(i); return value; } private void setAttributeArray(RuleForm instance, Attribute authorizedAttribute, Object[] values, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { AttributeValue<RuleForm>[] old = getValueArray(instance, authorizedAttribute, networkedModel); authorizedAttribute = model.getEntityManager() .getReference(Attribute.class, authorizedAttribute.getId()); if (values == null) { if (old != null) { for (AttributeValue<RuleForm> value : old) { model.getEntityManager() .remove(value); } } } else if (old == null) { for (int i = 0; i < values.length; i++) { setValue(instance, authorizedAttribute, i, null, values[i], networkedModel); } } else if (old.length == values.length) { for (int i = 0; i < values.length; i++) { setValue(instance, authorizedAttribute, i, old[i], values[i], networkedModel); } } else if (old.length < values.length) { int i; for (i = 0; i < old.length; i++) { setValue(instance, authorizedAttribute, i, old[i], values[i], networkedModel); } for (; i < values.length; i++) { setValue(instance, authorizedAttribute, i, null, values[i], networkedModel); } } else if (old.length > values.length) { int i; for (i = 0; i < values.length; i++) { setValue(instance, authorizedAttribute, i, old[i], values[i], networkedModel); } for (; i < old.length; i++) { model.getEntityManager() .remove(old[i]); } } } private void setAttributeMap(RuleForm instance, Attribute authorizedAttribute, Map<String, Object> values, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { Map<String, AttributeValue<RuleForm>> valueMap = getValueMap(instance, authorizedAttribute, networkedModel); values.keySet() .stream() .filter(keyName -> !valueMap.containsKey(keyName)) .forEach(keyName -> valueMap.remove(keyName)); int maxSeq = 0; for (AttributeValue<RuleForm> value : valueMap.values()) { maxSeq = Math.max(maxSeq, value.getSequenceNumber()); } authorizedAttribute = model.getEntityManager() .getReference(Attribute.class, authorizedAttribute.getId()); for (Map.Entry<String, Object> entry : values.entrySet()) { AttributeValue<RuleForm> value = valueMap.get(entry.getKey()); if (value == null) { value = newAttributeValue(instance, authorizedAttribute, ++maxSeq, networkedModel); model.getEntityManager() .persist(value); value.setKey(entry.getKey()); } value.setValue(entry.getValue()); } } private void setValue(RuleForm instance, Attribute attribute, int i, AttributeValue<RuleForm> existing, Object newValue, NetworkedModel<RuleForm, ?, ?, ?> networkedModel) { if (existing == null) { existing = newAttributeValue(instance, attribute, i, networkedModel); model.getEntityManager() .persist(existing); } existing.setValue(newValue); } }
package org.elasterix.sip; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONNECTION; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; import org.apache.log4j.Logger; import org.elasterix.sip.codec.SipMethod; import org.elasterix.sip.codec.SipRequest; import org.elasterix.sip.codec.SipResponse; import org.elasterix.sip.codec.SipResponseImpl; import org.elasterix.sip.codec.SipResponseStatus; import org.elasterix.sip.codec.SipVersion; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.springframework.beans.factory.annotation.Autowired; /** * Sip Server Handler<br> * <br> * This handler takes care of all incoming SIP messages and sent back corresponding * SIP responses<br> * * @author Leonard Wolters */ public class SipServerHandler extends SimpleChannelUpstreamHandler { private static final Logger log = Logger.getLogger(SipServerHandler.class); private SipMessageHandler messageHandler; public void setMessageHandler(SipMessageHandler messageHandler) { this.messageHandler = messageHandler; } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { SipRequest request = (SipRequest) e.getMessage(); if(log.isDebugEnabled()) { log.debug(String.format("messageReceived[%s]", request)); } // delegate action to handler switch(request.getMethod()) { case ACK: messageHandler.onAck(request); break; case BYE: messageHandler.onBye(request); break; case CANCEL: messageHandler.onCancel(request); break; case INVITE: messageHandler.onInvite(request); break; case OPTIONS: messageHandler.onInvite(request); break; case REGISTER: messageHandler.onRegister(request); break; default: log.error(String.format("Unrecognized method[%s]", request.getMethod().name())); writeResponse(request, e, SipResponseStatus.NOT_IMPLEMENTED); return; } // writing reponse (indicating message is received accordingly!) writeResponse(request, e, SipResponseStatus.OK); } private void writeResponse(SipRequest request, MessageEvent e, SipResponseStatus status) { // Decide whether to close the connection or not. //boolean keepAlive = SipHeaders.isKeepAlive(request); boolean keepAlive = true; // Build the response object. SipResponse response = new SipResponseImpl(SipVersion.SIP_2_0, SipResponseStatus.OK); //response.setContent(ChannelBuffers.copiedBuffer(buf.toString(), CharsetUtil.UTF_8)); response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.setHeader(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the response. ChannelFuture future = e.getChannel().write(response); // Close the non-keep-alive connection after the write operation is done. if (!keepAlive) { future.addListener(ChannelFutureListener.CLOSE); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { log.error(e.getCause().getMessage(), e.getCause().getCause()); e.getChannel().close(); } // Getters / Setters }
package edu.berkeley.cs.amplab.carat.android.sampling; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.RandomAccessFile; import java.lang.ref.WeakReference; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.android.internal.os.PowerProfile; import com.flurry.android.FlurryAgent; import edu.berkeley.cs.amplab.carat.android.CaratApplication; import edu.berkeley.cs.amplab.carat.thrift.BatteryDetails; import edu.berkeley.cs.amplab.carat.thrift.CallMonth; import edu.berkeley.cs.amplab.carat.thrift.CellInfo; import edu.berkeley.cs.amplab.carat.thrift.CpuStatus; import edu.berkeley.cs.amplab.carat.thrift.NetworkDetails; import edu.berkeley.cs.amplab.carat.thrift.ProcessInfo; import edu.berkeley.cs.amplab.carat.thrift.Sample; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; import android.app.ActivityManager.RunningServiceInfo; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.preference.PreferenceManager; import android.provider.Settings; import android.provider.Settings.Secure; import android.provider.Settings.SettingNotFoundException; import android.telephony.CellLocation; import android.telephony.TelephonyManager; import android.telephony.cdma.CdmaCellLocation; import android.telephony.gsm.GsmCellLocation; import android.util.Log; import android.location.Criteria; import android.location.GpsStatus; import android.location.Location; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.BatteryManager; import android.os.SystemClock; /** * Library class for methods that obtain information about the phone that is * running Carat. * * @author Eemil Lagerspetz * */ public final class SamplingLibrary { private static final int READ_BUFFER_SIZE = 2 * 1024; // Network status constants public static String NETWORKSTATUS_DISCONNECTED = "disconnected"; public static String NETWORKSTATUS_DISCONNECTING = "disconnecting"; public static String NETWORKSTATUS_CONNECTED = "connected"; public static String NETWORKSTATUS_CONNECTING = "connecting"; // Network type constants public static String TYPE_UNKNOWN = "unknown"; // Data State constants public static String DATA_DISCONNECTED = NETWORKSTATUS_DISCONNECTED; public static String DATA_CONNECTING = NETWORKSTATUS_CONNECTING; public static String DATA_CONNECTED = NETWORKSTATUS_CONNECTED; public static String DATA_SUSPENDED = "suspended"; // Data Activity constants public static String DATA_ACTIVITY_NONE = "none"; public static String DATA_ACTIVITY_IN = "in"; public static String DATA_ACTIVITY_OUT = "out"; public static String DATA_ACTIVITY_INOUT = "inout"; public static String DATA_ACTIVITY_DORMANT = "dormant"; // Wifi State constants public static String WIFI_STATE_DISABLING = "disabling"; public static String WIFI_STATE_DISABLED = "disabled"; public static String WIFI_STATE_ENABLING = "enabling"; public static String WIFI_STATE_ENABLED = "enabled"; public static String WIFI_STATE_UNKNOWN = "unknown"; // Call state constants public static String CALL_STATE_IDLE = "idle"; public static String CALL_STATE_OFFHOOK = "offhook"; public static String CALL_STATE_RINGING = "ringing"; // Mobile network constants /* * we cannot find network types:EVDO_B,LTE,EHRPD,HSPAP from TelephonyManager * now */ public static String NETWORK_TYPE_UNKNOWN = "unknown"; public static String NETWORK_TYPE_GPRS = "gprs"; public static String NETWORK_TYPE_EDGE = "edge"; public static String NETWORK_TYPE_UMTS = "utms"; public static String NETWORK_TYPE_CDMA = "cdma"; public static String NETWORK_TYPE_EVDO_0 = "evdo_0"; public static String NETWORK_TYPE_EVDO_A = "evdo_a"; // public static String NETWORK_TYPE_EVDO_B="evdo_b"; public static String NETWORK_TYPE_1xRTT = "1xrtt"; public static String NETWORK_TYPE_HSDPA = "hsdpa"; public static String NETWORK_TYPE_HSUPA = "hsupa"; public static String NETWORK_TYPE_HSPA = "hspa"; public static String NETWORK_TYPE_IDEN = "iden"; // public static String NETWORK_TYPE_LTE="lte"; // public static String NETWORK_TYPE_EHRPD="ehrpd"; // public static String NETWORK_TYPE_HSPAP="hspap"; // Phone type constants public static String PHONE_TYPE_CDMA = "cdma"; public static String PHONE_TYPE_GSM = "gsm"; // public static String PHONE_TYPE_SIP="sip"; public static String PHONE_TYPE_NONE = "none"; public static double startLatitude = 0; public static double startLongitude = 0; public static double distance = 0; private static final String STAG = "getSample"; private static final String TAG="FeaturesPowerConsumption"; public static final int UUID_LENGTH = 16; /** Library class, prevent instantiation */ private SamplingLibrary() { } /** * Returns a randomly generated unique identifier that stays constant for * the lifetime of the device. (May change if wiped). This is probably our * best choice for a UUID across the Android landscape, since it is present * on both phones and non-phones. * * @return a String that uniquely identifies this device. */ public static String getAndroidId(Context c) { return Secure.getString(c.getContentResolver(), Secure.ANDROID_ID); } public static String getUuid(Context c) { String aID = getAndroidId(c); String wifiMac = getWifiMacAddress(c); String devid = getDeviceId(c); String concat = ""; if (aID != null) concat = aID; else concat = "0000000000000000"; if (wifiMac != null) concat += wifiMac; else concat += "00:00:00:00:00:00"; // IMEI is 15 characters, decimal, while MEID is 14 characters, hex. Add a space if length is less than 15: if (devid != null) { concat += devid; if (devid.length() < 15) concat += " "; } else concat += "000000000000000"; //Log.d(STAG, "AID="+aID+" wifiMac="+wifiMac+" devid="+devid+" rawUUID=" +concat ); try { MessageDigest md = MessageDigest.getInstance("SHA-512"); md.update(concat.getBytes()); byte[] mdbytes = md.digest(); StringBuilder hexString = new StringBuilder(); for (int i=0;i<mdbytes.length;i++) { String hx = Integer.toHexString(0xFF & mdbytes[i]); if (hx.equals("0")) hexString.append("00"); else hexString.append(hx); } String uuid = hexString.toString().substring(0, UUID_LENGTH); FlurryAgent.logEvent("ANDROID_ID=" + aID +" UUID=" + uuid); return uuid; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return aID; } } /** * Returns the model of the device running Carat, for example "sdk" for the * emulator, Galaxy Nexus for Samsung Galaxy Nexus. * * @return the model of the device running Carat, for example "sdk" for the * emulator, Galaxy Nexus for Samsung Galaxy Nexus. */ public static String getModel() { return android.os.Build.MODEL; } /** * Returns the manufacturer of the device running Carat, for example * "google" or "samsung". * * @return the manufacturer of the device running Carat, for example * "google" or "samsung". */ public static String getManufacturer() { return android.os.Build.MANUFACTURER; } /** * Returns the OS version of the device running Carat, for example 2.3.3 or * 4.0.2. * * @return the OS version of the device running Carat, for example 2.3.3 or * 4.0.2. */ public static String getOsVersion() { return android.os.Build.VERSION.RELEASE; } /** * This may only work for 2.3 and later: * * @return */ public static String getBuildSerial() { // return android.os.Build.Serial; return System.getProperty("ro.serial", TYPE_UNKNOWN); } /** * Return misc system details that we might want to use later. Currently * does nothing. * * @return */ public static Map<String, String> getSystemDetails() { Map<String, String> results = new HashMap<String, String>(); // TODO: Some of this should be added to registration to identify the // device and OS. // Cyanogenmod and others may have different kernels etc that affect // performance. /* * Log.d("SetModel", "board:" + android.os.Build.BOARD); * Log.d("SetModel", "bootloader:" + android.os.Build.BOOTLOADER); * Log.d("SetModel", "brand:" + android.os.Build.BRAND); * Log.d("SetModel", "CPU_ABI 1 and 2:" + android.os.Build.CPU_ABI + * ", " + android.os.Build.CPU_ABI2); Log.d("SetModel", "dev:" + * android.os.Build.DEVICE); Log.d("SetModel", "disp:" + * android.os.Build.DISPLAY); Log.d("SetModel", "FP:" + * android.os.Build.FINGERPRINT); Log.d("SetModel", "HW:" + * android.os.Build.HARDWARE); Log.d("SetModel", "host:" + * android.os.Build.HOST); Log.d("SetModel", "ID:" + * android.os.Build.ID); Log.d("SetModel", "manufacturer:" + * android.os.Build.MANUFACTURER); Log.d("SetModel", "prod:" + * android.os.Build.PRODUCT); Log.d("SetModel", "radio:" + * android.os.Build.RADIO); // FIXME: SERIAL not available on 2.2 // * Log.d("SetModel", "ser:" + android.os.Build.SERIAL); * Log.d("SetModel", "tags:" + android.os.Build.TAGS); Log.d("SetModel", * "time:" + android.os.Build.TIME); Log.d("SetModel", "type:" + * android.os.Build.TYPE); Log.d("SetModel", "unknown:" + * android.os.Build.UNKNOWN); Log.d("SetModel", "user:" + * android.os.Build.USER); Log.d("SetModel", "model:" + * android.os.Build.MODEL); Log.d("SetModel", "codename:" + * android.os.Build.VERSION.CODENAME); Log.d("SetModel", "release:" + * android.os.Build.VERSION.RELEASE); */ return results; } /** * Read memory information from /proc/meminfo. Return used, free, inactive, * and active memory. * * @return an int[] with used, free, inactive, and active memory, in kB, in * that order. */ public static int[] readMeminfo() { try { RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r"); String load = reader.readLine(); String[] toks = load.split("\\s+"); // Log.v("meminfo", "Load: " + load + " 1:" + toks[1]); int total = Integer.parseInt(toks[1]); load = reader.readLine(); toks = load.split("\\s+"); // Log.v("meminfo", "Load: " + load + " 1:" + toks[1]); int free = Integer.parseInt(toks[1]); load = reader.readLine(); load = reader.readLine(); load = reader.readLine(); load = reader.readLine(); toks = load.split("\\s+"); // Log.v("meminfo", "Load: " + load + " 1:" + toks[1]); int act = Integer.parseInt(toks[1]); load = reader.readLine(); toks = load.split("\\s+"); // Log.v("meminfo", "Load: " + load + " 1:" + toks[1]); int inact = Integer.parseInt(toks[1]); reader.close(); return new int[] { total - free, free, inact, act }; } catch (IOException ex) { ex.printStackTrace(); } return new int[] { 0, 0, 0, 0 }; } /** * Read memory usage using the public Android API methods in * ActivityManager, such as MemoryInfo and getProcessMemoryInfo. * * @param c * the Context from the running Activity. * @return int[] with total and used memory, in kB, in that order. */ public static int[] readMemory(Context c) { ActivityManager man = (ActivityManager) c .getSystemService(Activity.ACTIVITY_SERVICE); /* Get available (free) memory */ ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo(); man.getMemoryInfo(info); int totalMem = (int) info.availMem; /* Get memory used by all running processes. */ /* Step 1: gather pids */ List<ActivityManager.RunningAppProcessInfo> procs = man .getRunningAppProcesses(); List<ActivityManager.RunningServiceInfo> servs = man .getRunningServices(Integer.MAX_VALUE); int[] pids = new int[procs.size() + servs.size()]; int i = 0; for (ActivityManager.RunningAppProcessInfo pinfo : procs) { pids[i] = pinfo.pid; i++; } for (ActivityManager.RunningServiceInfo pinfo : servs) { pids[i] = pinfo.pid; i++; } /* * Step 2: Sum up Pss values (weighted memory usage, taking into account * shared page usage) */ android.os.Debug.MemoryInfo[] mems = man.getProcessMemoryInfo(pids); int memUsed = 0; for (android.os.Debug.MemoryInfo mem : mems) { memUsed += mem.getTotalPss(); } Log.v("Mem", "Total mem:" + totalMem); Log.v("Mem", "Mem Used:" + memUsed); return new int[] { totalMem, memUsed }; } // FIXME: Describe this. Why are there so many fields? Why is it divided by // 100? /* * The value of HZ varies across kernel versions and hardware platforms. On * i386 the situation is as follows: on kernels up to and including 2.4.x, * HZ was 100, giving a jiffy value of 0.01 seconds; starting with 2.6.0, HZ * was raised to 1000, giving a jiffy of 0.001 seconds. Since kernel 2.6.13, * the HZ value is a kernel configuration parameter and can be 100, 250 (the * default) or 1000, yielding a jiffies value of, respectively, 0.01, 0.004, * or 0.001 seconds. Since kernel 2.6.20, a further frequency is available: * 300, a number that divides evenly for the common video frame rates (PAL, * 25 HZ; NTSC, 30 HZ). * * I will leave the unit of cpu time as the jiffy and we can discuss later. * * 0 name of cpu 1 space 2 user time 3 nice time 4 sys time 5 idle time(it * is not include in the cpu total time) 6 iowait time 7 irg time 8 softirg * time * * the idleTotal[5] is the idle time which always changes. There are two * spaces between cpu and user time.That is a tricky thing and messed up * splitting.:) */ /** * Read CPU usage from /proc/stat, return a fraction of * usage/(usage+idletime) * * @return a fraction of usage/(usage+idletime) */ public static long[] readUsagePoint() { try { RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r"); String load = reader.readLine(); String[] toks = load.split(" "); long idle1 = Long.parseLong(toks[5]); long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]); return new long[] { idle1, cpu1 }; } catch (IOException ex) { ex.printStackTrace(); } return null; } /** * Calculate CPU usage between the cpu and idle time given at two time * points. * * @param then * @param now * @return */ public static double getUsage(long[] then, long[] now) { if (then == null || now == null || then.length < 2 || now.length < 2) return 0.0; double idleAndCpuDiff = (now[0] + now[1]) - (then[0] + then[1]); return (now[1] - then[1]) / idleAndCpuDiff; } /** * Deprecated: We cannot sleep during sampling, since that freezes the UI. * Read CPU usage from /proc/stat, return a fraction of * usage/(usage+idletime) * * @return a fraction of usage/(usage+idletime) */ @Deprecated public static double readUsage() { try { RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r"); String load = reader.readLine(); String[] toks = load.split(" "); double idle1 = Long.parseLong(toks[5]); double cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]); try { Thread.sleep(360); } catch (Exception e) { } reader.seek(0); load = reader.readLine(); reader.close(); toks = load.split(" "); double idle2 = Long.parseLong(toks[5]); double cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]); return (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1)); } catch (IOException ex) { ex.printStackTrace(); } return 0; } private static WeakReference<List<RunningAppProcessInfo>> runningAppInfo = null; public static List<ProcessInfo> getRunningAppInfo(Context c){ List<RunningAppProcessInfo> runningProcs = getRunningProcessInfo(c); List<RunningServiceInfo> runningServices = getRunningServiceInfo(c); List<ProcessInfo> l = new ArrayList<ProcessInfo>(); if (runningProcs != null) { for (RunningAppProcessInfo pi : runningProcs) { if (pi == null) continue; ProcessInfo item = new ProcessInfo(); item.setImportance(CaratApplication .importanceString(pi.importance)); item.setPId(pi.pid); item.setPName(pi.processName); l.add(item); } } if (runningServices != null) { for (RunningServiceInfo pi : runningServices) { if (pi == null) continue; ProcessInfo item = new ProcessInfo(); item.setImportance(pi.foreground ? "Foreground app" : "Service"); item.setPId(pi.pid); item.setPName(pi.clientPackage); l.add(item); } } return l; } private static List<RunningAppProcessInfo> getRunningProcessInfo( Context context) { if (runningAppInfo == null || runningAppInfo.get() == null) { ActivityManager pActivityManager = (ActivityManager) context .getSystemService(Activity.ACTIVITY_SERVICE); List<RunningAppProcessInfo> runningProcs = pActivityManager .getRunningAppProcesses(); /* * TODO: Is this the right thing to do? Remove part after ":" in * process names */ for (RunningAppProcessInfo i : runningProcs) { if (i != null && i.processName != null) { int idx = i.processName.lastIndexOf(':'); if (idx <= 0) idx = i.processName.length(); i.processName = i.processName.substring(0, idx); } } runningAppInfo = new WeakReference<List<RunningAppProcessInfo>>( runningProcs); } return runningAppInfo.get(); } public static List<RunningServiceInfo> getRunningServiceInfo(Context c){ ActivityManager pActivityManager = (ActivityManager) c .getSystemService(Activity.ACTIVITY_SERVICE); return pActivityManager.getRunningServices(0); } public static boolean isRunning(Context context, String appName) { List<RunningAppProcessInfo> runningProcs = getRunningProcessInfo(context); for (RunningAppProcessInfo i : runningProcs) { if (i.processName.equals(appName) && i.importance != RunningAppProcessInfo.IMPORTANCE_EMPTY) return true; } return false; } public static void resetRunningProcessInfo(){ runningAppInfo = null; } static WeakReference<Map<String, PackageInfo>> packages = null; public static boolean isHidden(Context c, String processName){ boolean isSystem = isSystem(c, processName); boolean blocked = (isSystem && !isWhiteListed(c, processName)); return blocked || isBlacklisted(c, processName); } /** * For debugging always returns true. * @param c * @param processName * @return */ private static boolean isWhiteListed(Context c, String processName) { return !isBlacklisted(c, processName); } /** * For debugging always returns true. * @param c * @param processName * @return */ private static boolean isBlacklisted(Context c, String processName) { /* * Whitelist: * Messaging, Voice Search, Bluetooth Share * * Blacklist: * Key chain, google partner set up, package installer, package access helper * */ if (CaratApplication.s != null) { List<String> blacklist = CaratApplication.s.getBlacklist(); if (blacklist != null && blacklist.size() > 0 && processName != null && blacklist.contains(processName)) { return true; } blacklist = CaratApplication.s.getGloblist(); if (blacklist != null && blacklist.size() > 0 && processName != null){ for (String glob: blacklist){ if (glob == null) continue; // something* if (glob.endsWith("*") && processName.startsWith(glob.substring(0, glob.length()-1))) return true; // *something if (glob.startsWith("*") && processName.endsWith(glob.substring(1))) return true; } } } String label = CaratApplication.labelForApp(c, processName); if (processName != null && label != null && label.equals(processName)){ //Log.v("Hiding uninstalled", processName); return true; } FlurryAgent.logEvent("Whitelisted "+processName + " \""+ label+"\""); return false; } private static boolean isSystem(Context context, String processName) { PackageInfo pak = getPackageInfo(context, processName); if (pak != null) { ApplicationInfo i = pak.applicationInfo; int flags = i.flags; boolean isSystemApp = (flags & ApplicationInfo.FLAG_SYSTEM) > 0; isSystemApp = isSystemApp || (flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) > 0; // Log.v(STAG, processName + " is System app? " + isSystemApp); return isSystemApp; } return false; } public static PackageInfo getPackageInfo(Context context, String processName) { List<android.content.pm.PackageInfo> packagelist = null; if (packages == null || packages.get() == null || packages.get().size() == 0) { Map<String, PackageInfo> mp = new HashMap<String, PackageInfo>(); PackageManager pm = context.getPackageManager(); if (pm == null) return null; try{ packagelist = pm .getInstalledPackages(0); }catch (Throwable th){ // Forget about it... } if (packagelist == null) return null; for (PackageInfo pak : packagelist) { if (pak == null || pak.applicationInfo == null || pak.applicationInfo.processName == null) continue; mp.put(pak.applicationInfo.processName, pak); } packages = new WeakReference<Map<String, PackageInfo>>(mp); if (mp == null || mp.size() == 0) return null; if (!mp.containsKey(processName)) return null; PackageInfo pak = mp.get(processName); return pak; }else{ if (packages == null) return null; Map<String, PackageInfo> p = packages.get(); if (p == null || p.size() == 0) return null; if (!p.containsKey(processName)) return null; PackageInfo pak = p.get(processName); return pak; } } /** * Returns a List of ProcessInfo objects for a Sample object. * * @param context * @return */ public static List<ProcessInfo> getRunningProcessInfoForSample( Context context) { // Reset list for each sample runningAppInfo = null; List<ProcessInfo> list = getRunningAppInfo(context); List<ProcessInfo> result = new ArrayList<ProcessInfo>(); PackageManager pm = context.getPackageManager(); // Collected in the same loop to save computation. int[] procMem = new int[list.size()]; for (ProcessInfo pi : list) { ProcessInfo item = new ProcessInfo(); PackageInfo pak = getPackageInfo(context, pi.getPName()); if (pak != null) { ApplicationInfo info = pak.applicationInfo; // Human readable label (if any) String label = pm.getApplicationLabel(info).toString(); if (label != null && label.length() > 0) item.setApplicationLabel(label); // TODO: get more application details and assign to item int flags = pak.applicationInfo.flags; // Check if it is a system app boolean isSystemApp = (flags & ApplicationInfo.FLAG_SYSTEM) > 0; isSystemApp = isSystemApp || (flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) > 0; item.setIsSystemApp(isSystemApp); } item.setImportance(pi.getImportance()); item.setPId(pi.getPId()); item.setPName(pi.getPName()); procMem[list.indexOf(pi)] = pi.getPId(); // FIXME: More fields will need to be added here, but ProcessInfo // needs to change. /* * uid lru */ // add to result result.add(item); } // FIXME: These are not used yet. /*ActivityManager pActivityManager = (ActivityManager) context .getSystemService(Activity.ACTIVITY_SERVICE); Debug.MemoryInfo[] memoryInfo = pActivityManager .getProcessMemoryInfo(procMem); for (Debug.MemoryInfo info : memoryInfo) { // Decide which ones of info.* we want, add to a new and improved // ProcessInfo object // FIXME: Not used yet, Sample needs more fields // FIXME: Which memory fields to choose? //int memory = info.dalvikPrivateDirty; }*/ return result; } /** * Depratecated, use int[] meminfo = readMemInfo(); int totalMemory = * meminfo[0] + meminfo[1]; */ @Deprecated public static String getMemoryInfo() { String tmp = null; BufferedReader br = null; try { File file = new File("/proc/meminfo"); FileInputStream in = new FileInputStream(file); br = new BufferedReader(new InputStreamReader(in), READ_BUFFER_SIZE); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { tmp = br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } StringBuilder sMemory = new StringBuilder(); sMemory.append(tmp); try { tmp = br.readLine(); br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } sMemory.append("\n").append(tmp).append("\n"); String result = "Memery Status:\n" + sMemory; return result; } /* * Deprecated, use readMemInfo()[1] */ @Deprecated public static String getMemoryFree() { String tmp = null; BufferedReader br = null; try { File file = new File("/proc/meminfo"); FileInputStream in = new FileInputStream(file); br = new BufferedReader(new InputStreamReader(in), READ_BUFFER_SIZE); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { tmp = br.readLine(); tmp = br.readLine(); if (tmp != null) { // split by whitespace and take 2nd element, so that in: // MemoryFree: x kb // the x remains. String[] arr = tmp.split("\\s+"); if (arr.length > 1) tmp = arr[1]; } br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return tmp; } /** * Return time in seconds since last boot. */ public static double getUptime() { long uptime = SystemClock.elapsedRealtime(); /* * int seconds = (int) (uptime / 1000) % 60; int minutes = (int) (uptime * / (1000 * 60) % 60); int hours = (int) (uptime / (1000 * 60 * 60) % * 24); String tmp = "\nThe uptime is :" + hours + "hr:" + minutes + * "mins:" + seconds + "sec.\n"; return tmp; */ Log.v("uptime", String.valueOf(uptime)); return uptime / 1000.0; } public static String getNetworkStatus(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return NETWORKSTATUS_DISCONNECTED; NetworkInfo i = cm.getActiveNetworkInfo(); if (i == null) return NETWORKSTATUS_DISCONNECTED; NetworkInfo.State s = i.getState(); if (s == NetworkInfo.State.CONNECTED) return NETWORKSTATUS_CONNECTED; if (s == NetworkInfo.State.DISCONNECTED) return NETWORKSTATUS_DISCONNECTED; if (s == NetworkInfo.State.CONNECTING) return NETWORKSTATUS_CONNECTING; if (s == NetworkInfo.State.DISCONNECTING) return NETWORKSTATUS_DISCONNECTING; else return NETWORKSTATUS_DISCONNECTED; } public static String getNetworkType(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return TYPE_UNKNOWN; NetworkInfo i = cm.getActiveNetworkInfo(); if (i == null) return TYPE_UNKNOWN; return i.getTypeName(); } public static boolean networkAvailable(Context c) { String network = getNetworkStatus(c); return network.equals(NETWORKSTATUS_CONNECTED); } /* Get current WiFi signal Strength */ public static int getWifiSignalStrength(Context context) { WifiManager myWifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); WifiInfo myWifiInfo = myWifiManager.getConnectionInfo(); int wifiRssi = myWifiInfo.getRssi(); Log.v("WifiRssi", "Rssi:" + wifiRssi); return wifiRssi; } /** * Get Wifi MAC ADDR. Hashed and used in UUID calculation. */ private static String getWifiMacAddress(Context context) { WifiManager myWifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); if (myWifiManager == null) return null; WifiInfo myWifiInfo = myWifiManager.getConnectionInfo(); if (myWifiInfo == null) return null; return myWifiInfo.getMacAddress(); } /* Get current WiFi link speed */ public static int getWifiLinkSpeed(Context context) { WifiManager myWifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); WifiInfo myWifiInfo = myWifiManager.getConnectionInfo(); int linkSpeed = myWifiInfo.getLinkSpeed(); Log.v("linkSpeed", "Link speed:" + linkSpeed); return linkSpeed; } /* Check whether WiFi is enabled */ public static boolean getWifiEnabled(Context context) { boolean wifiEnabled = false; WifiManager myWifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); wifiEnabled = myWifiManager.isWifiEnabled(); Log.v("WifiEnabled", "Wifi is enabled:" + wifiEnabled); return wifiEnabled; } /* Get Wifi state: */ public static String getWifiState(Context context) { WifiManager myWifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); int wifiState = myWifiManager.getWifiState(); switch (wifiState) { case WifiManager.WIFI_STATE_DISABLED: return WIFI_STATE_DISABLED; case WifiManager.WIFI_STATE_DISABLING: return WIFI_STATE_DISABLING; case WifiManager.WIFI_STATE_ENABLED: return WIFI_STATE_ENABLED; case WifiManager.WIFI_STATE_ENABLING: return WIFI_STATE_ENABLING; default: return WIFI_STATE_UNKNOWN; } } public static WifiInfo getWifiInfo(Context context) { WifiManager myWifiManager = (WifiManager) context .getSystemService(Context.WIFI_SERVICE); WifiInfo connectionInfo = myWifiManager.getConnectionInfo(); Log.v("WifiInfo", "Wifi information:" + connectionInfo); return connectionInfo; } /* * This method is deprecated. As of ICE_CREAM_SANDWICH, availability of * background data depends on several combined factors, and this method will * always return true. Instead, when background data is unavailable, * getActiveNetworkInfo() will now appear disconnected. */ /* Check whether background data are enabled */ @Deprecated public static boolean getBackgroundDataEnabled(Context context) { boolean bacDataEnabled = false; try { if (Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.BACKGROUND_DATA) == 1) { bacDataEnabled = true; } } catch (SettingNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.v("BackgroundDataEnabled", "Background data enabled? " + bacDataEnabled); // return bacDataEnabled; return true; } /* Get Current Screen Brightness Value */ public static int getScreenBrightness(Context context) { int screenBrightnessValue = 0; try { screenBrightnessValue = android.provider.Settings.System.getInt( context.getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS); } catch (SettingNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.v("ScreenBrightness", "Screen brightness value:" + screenBrightnessValue); return screenBrightnessValue; } public static boolean isAutoBrightness(Context context) { boolean autoBrightness = false; try { autoBrightness = Settings.System.getInt( context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC; } catch (SettingNotFoundException e) { e.printStackTrace(); } Log.v("AutoScreenBrightness", "Automatic Screen brightness mode is enabled:" + autoBrightness); return autoBrightness; } /* Check whether GPS are enabled */ public static boolean getGpsEnabled(Context context) { boolean gpsEnabled = false; LocationManager myLocationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); gpsEnabled = myLocationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); Log.v("GPS", "GPS is :" + gpsEnabled); return gpsEnabled; } /* check the GSM cell information */ public static CellInfo getCellInfo(Context context) { CellInfo curCell = new CellInfo(); TelephonyManager myTelManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); String netOperator = myTelManager.getNetworkOperator(); // Fix crash when not connected to network (airplane mode, underground, // etc) if (netOperator == null || netOperator.length() < 3) { return curCell; } /* * FIXME: Actually check for mobile network status == connected before * doing this stuff. */ if (SamplingLibrary.getPhoneType(context) == PHONE_TYPE_CDMA) { CdmaCellLocation cdmaLocation = (CdmaCellLocation) myTelManager .getCellLocation(); if (cdmaLocation == null) { Log.v("cdmaLocation", "CDMA Location:" + cdmaLocation); } else { int cid = cdmaLocation.getBaseStationId(); int lac = cdmaLocation.getNetworkId(); int mnc = cdmaLocation.getSystemId(); int mcc = Integer.parseInt(netOperator.substring(0, 3)); curCell.CID = cid; curCell.LAC = lac; curCell.MNC = mnc; curCell.MCC = mcc; curCell.radioType = SamplingLibrary .getMobileNetworkType(context); Log.v("MCC", "MCC is:" + mcc); Log.v("MNC", "MNC is:" + mnc); Log.v("CID", "CID is:" + cid); Log.v("LAC", "LAC is:" + lac); } } else if (SamplingLibrary.getPhoneType(context) == PHONE_TYPE_GSM) { GsmCellLocation gsmLocation = (GsmCellLocation) myTelManager .getCellLocation(); if (gsmLocation == null) { Log.v("gsmLocation", "GSM Location:" + gsmLocation); } else { int cid = gsmLocation.getCid(); int lac = gsmLocation.getLac(); int mcc = Integer.parseInt(netOperator.substring(0, 3)); int mnc = Integer.parseInt(netOperator.substring(3)); curCell.MCC = mcc; curCell.MNC = mnc; curCell.LAC = lac; curCell.CID = cid; curCell.radioType = SamplingLibrary .getMobileNetworkType(context); Log.v("MCC", "MCC is:" + mcc); Log.v("MNC", "MNC is:" + mnc); Log.v("CID", "CID is:" + cid); Log.v("LAC", "LAC is:" + lac); } } return curCell; } /** * Return distance between <code>lastKnownLocation</code> and a newly * obtained location from any available provider. * * @param c * from Intent or Application. * @return */ public static double getDistance(Context c) { Location l = getLastKnownLocation(c); double distance = 0.0; if (lastKnownLocation != null && l != null) { distance = lastKnownLocation.distanceTo(l); } lastKnownLocation = l; return distance; } public static Location getLastKnownLocation(Context c) { String provider = getBestProvider(c); // FIXME: Some buggy device is giving GPS to us, even though we cannot use it. if (provider != null && !provider.equals("gps")) { Location l = getLastKnownLocation(c, provider); return l; } return null; } private static Location getLastKnownLocation(Context context, String provider) { LocationManager lm = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); Location l = lm.getLastKnownLocation(provider); return l; } /* Get the distance users between two locations */ public static double getDistance(double startLatitude, double startLongitude, double endLatitude, double endLongitude) { float[] results = new float[1]; Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results); return results[0]; } /** * Return a list of enabled LocationProviders, such as GPS, Network, etc. * * @param context * from onReceive or app. * @return */ public static List<String> getEnabledLocationProviders(Context context) { LocationManager lm = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); return lm.getProviders(true); } public static String getBestProvider(Context context) { LocationManager lm = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); Criteria c = new Criteria(); c.setAccuracy(Criteria.ACCURACY_COARSE); c.setPowerRequirement(Criteria.POWER_LOW); String provider = lm.getBestProvider(c, true); return provider; } /* Check the maximum number of satellites can be used in the satellite list */ public static int getMaxNumSatellite(Context context) { LocationManager locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); GpsStatus gpsStatus = locationManager.getGpsStatus(null); int maxNumSatellite = gpsStatus.getMaxSatellites(); Log.v("maxNumStatellite", "Maxmium number of satellites:" + maxNumSatellite); return maxNumSatellite; } /* Get call status */ public static String getCallState(Context context) { TelephonyManager telManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); int callState = telManager.getCallState(); switch (callState) { case TelephonyManager.CALL_STATE_OFFHOOK: return CALL_STATE_OFFHOOK; case TelephonyManager.CALL_STATE_RINGING: return CALL_STATE_RINGING; default: return CALL_STATE_IDLE; } } private static String getDeviceId(Context context) { TelephonyManager telManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); if (telManager == null) return null; return telManager.getDeviceId(); } /* Get network type */ public static String getMobileNetworkType(Context context) { TelephonyManager telManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); int netType = telManager.getNetworkType(); switch (netType) { case TelephonyManager.NETWORK_TYPE_1xRTT: return NETWORK_TYPE_1xRTT; case TelephonyManager.NETWORK_TYPE_CDMA: return NETWORK_TYPE_CDMA; case TelephonyManager.NETWORK_TYPE_EDGE: return NETWORK_TYPE_EDGE; case TelephonyManager.NETWORK_TYPE_EVDO_0: return NETWORK_TYPE_EVDO_0; case TelephonyManager.NETWORK_TYPE_EVDO_A: return NETWORK_TYPE_EVDO_A; case TelephonyManager.NETWORK_TYPE_GPRS: return NETWORK_TYPE_GPRS; case TelephonyManager.NETWORK_TYPE_HSDPA: return NETWORK_TYPE_HSDPA; case TelephonyManager.NETWORK_TYPE_HSPA: return NETWORK_TYPE_HSPA; case TelephonyManager.NETWORK_TYPE_HSUPA: return NETWORK_TYPE_HSUPA; case TelephonyManager.NETWORK_TYPE_IDEN: return NETWORK_TYPE_IDEN; case TelephonyManager.NETWORK_TYPE_UMTS: return NETWORK_TYPE_UMTS; default: return NETWORK_TYPE_UNKNOWN; } } /* Get Phone Type */ public static String getPhoneType(Context context) { TelephonyManager telManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); int phoneType = telManager.getPhoneType(); switch (phoneType) { case TelephonyManager.PHONE_TYPE_CDMA: return PHONE_TYPE_CDMA; case TelephonyManager.PHONE_TYPE_GSM: return PHONE_TYPE_GSM; default: return PHONE_TYPE_NONE; } } /* Check is it network roaming */ public static boolean getRoamingStatus(Context context) { boolean roamStatus = false; TelephonyManager telManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); roamStatus = telManager.isNetworkRoaming(); Log.v("RoamingStatus", "Roaming status:" + roamStatus); return roamStatus; } /* Get data state */ public static String getDataState(Context context) { TelephonyManager telManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); int dataState = telManager.getDataState(); switch (dataState) { case TelephonyManager.DATA_CONNECTED: return DATA_CONNECTED; case TelephonyManager.DATA_CONNECTING: return DATA_CONNECTING; case TelephonyManager.DATA_DISCONNECTED: return DATA_DISCONNECTED; default: return DATA_SUSPENDED; } } /* Get data activity */ public static String getDataActivity(Context context) { TelephonyManager telManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); int dataActivity = telManager.getDataActivity(); switch (dataActivity) { case TelephonyManager.DATA_ACTIVITY_IN: return DATA_ACTIVITY_IN; case TelephonyManager.DATA_ACTIVITY_OUT: return DATA_ACTIVITY_OUT; case TelephonyManager.DATA_ACTIVITY_INOUT: return DATA_ACTIVITY_INOUT; default: return DATA_ACTIVITY_NONE; } } /* Get the current location of the device */ public static CellLocation getDeviceLocation(Context context) { TelephonyManager telManager = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); CellLocation LocDevice = telManager.getCellLocation(); Log.v("DeviceLocation", "Device Location:" + LocDevice); return LocDevice; } /** * Return a long[3] with incoming call time, outgoing call time, and * non-call time in seconds since boot. * * @param context * from onReceive or Activity * @return a long[3] with incoming call time, outgoing call time, and * non-call time in seconds since boot. */ public static long[] getCalltimesSinceBoot(Context context) { long[] result = new long[3]; long callInSeconds = 0; long callOutSeconds = 0; int type; long dur; // ms since boot long uptime = SystemClock.elapsedRealtime(); long now = System.currentTimeMillis(); long bootTime = now - uptime; String[] queries = new String[] { android.provider.CallLog.Calls.TYPE, android.provider.CallLog.Calls.DATE, android.provider.CallLog.Calls.DURATION }; Cursor cur = context.getContentResolver().query( android.provider.CallLog.Calls.CONTENT_URI, queries, android.provider.CallLog.Calls.DATE + " > " + bootTime, null, android.provider.CallLog.Calls.DATE + " ASC"); if (cur != null) { if (cur.moveToFirst()) { while (!cur.isAfterLast()) { type = cur.getInt(0); dur = cur.getLong(2); switch (type) { case android.provider.CallLog.Calls.INCOMING_TYPE: callInSeconds += dur; break; case android.provider.CallLog.Calls.OUTGOING_TYPE: callOutSeconds += dur; break; default: } cur.moveToNext(); } } else { Log.w("CallDurFromBoot", "No calls listed"); } cur.close(); } else { Log.w("CallDurFromBoot", "Cursor is null"); } // uptime is ms, so it needs to be divided by 1000 long nonCallTime = uptime / 1000 - callInSeconds - callOutSeconds; result[0] = callInSeconds; result[1] = callOutSeconds; result[2] = nonCallTime; return result; } /* Get a monthly call duration record */ public static Map<String, CallMonth> getMonthCallDur(Context context) { Map<String, CallMonth> callMonth = new HashMap<String, CallMonth>(); Map<String, String> callInDur = new HashMap<String, String>(); Map<String, String> callOutDur = new HashMap<String, String>(); int callType; long callDur; Date callDate; String tmpTime = null; String time; SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM"); CallMonth curMonth = null; String[] queryFields = new String[] { android.provider.CallLog.Calls.TYPE, android.provider.CallLog.Calls.DATE, android.provider.CallLog.Calls.DURATION }; Cursor myCursor = context.getContentResolver().query( android.provider.CallLog.Calls.CONTENT_URI, queryFields, null, null, android.provider.CallLog.Calls.DATE + " DESC"); if (myCursor.moveToFirst()) { for (int i = 0; i < myCursor.getColumnCount(); i++) { myCursor.moveToPosition(i); callType = myCursor.getInt(0); callDate = new Date(myCursor.getLong(1)); callDur = myCursor.getLong(2); time = dateformat.format(callDate); if (tmpTime != null && !time.equals(tmpTime)) { callMonth.put(tmpTime, curMonth); callInDur.clear(); callOutDur.clear(); curMonth = new CallMonth(); } tmpTime = time; if (callType == 1) { curMonth.tolCallInNum++; curMonth.tolCallInDur += callDur; callInDur.put("tolCallInNum", String.valueOf(curMonth.tolCallInNum)); callInDur.put("tolCallInDur", String.valueOf(curMonth.tolCallInDur)); } if (callType == 2) { curMonth.tolCallOutNum++; curMonth.tolCallOutDur += callDur; callOutDur.put("tolCallOutNum", String.valueOf(curMonth.tolCallOutNum)); callOutDur.put("tolCallOutDur", String.valueOf(curMonth.tolCallOutDur)); } if (callType == 3) { curMonth.tolMissedCallNum++; callInDur.put("tolMissedCallNum", String.valueOf(curMonth.tolMissedCallNum)); } } } else { Log.v("MonthType", "callType=None"); Log.v("MonthDate", "callDate=None"); Log.v("MonthDuration", "callduration =None"); } return callMonth; } public static CallMonth getCallMonthinfo(Context context, String time) { Map<String, CallMonth> callInfo; callInfo = SamplingLibrary.getMonthCallDur(context); CallMonth call = new CallMonth(); call = callInfo.get(time); return call; } public static double getBatteryCapacity(Context context){ PowerProfile powCal=new PowerProfile(context); double batteryCap=powCal.getBatteryCapacity(); return batteryCap; } public static double getAverageBluetoothPower(Context context){ PowerProfile powCal=new PowerProfile(context); double bluetoothOnCost=powCal.getAveragePower(powCal.POWER_BLUETOOTH_ON); Log.i("bluetoothOnCost", "Bluetooth on cost is:"+bluetoothOnCost); double bluetoothActiveCost=powCal.getAveragePower(powCal.POWER_BLUETOOTH_ACTIVE); // double bluetoothAtcmdCost=powCal.getAveragePower(powCal.POWER_BLUETOOTH_AT_CMD); Log.i("bluetoothActiveCost", "Bluetooth active cost is:"+bluetoothActiveCost); double alpha = 0.5; double bluetoothPowerCost=bluetoothOnCost*alpha+bluetoothActiveCost*(1-alpha); Log.i("bluetoothPowerConsumption", "Bluetooth power consumption is:"+bluetoothPowerCost); return bluetoothPowerCost; } public static double getAverageWifiPower(Context context){ PowerProfile powCal=new PowerProfile(context); //double wifiScanCost=powCal.getAveragePower(powCal.POWER_WIFI_SCAN); double wifiOnCost=powCal.getAveragePower(powCal.POWER_WIFI_ON); Log.i("wifiOnCost", "Wifi on cost is:"+wifiOnCost); double wifiActiveCost=powCal.getAveragePower(powCal.POWER_WIFI_ACTIVE); Log.i("wifiActiveCost", "Wifi active cost is:"+wifiActiveCost); double alpha = 0.5; double wifiPowerCost=wifiOnCost*alpha+wifiActiveCost*(1-alpha); Log.i("wifiPowerConsumption", "Wifi power consumption is:"+wifiPowerCost); return wifiPowerCost; } public static double getAverageGpsPower(Context context){ PowerProfile powCal=new PowerProfile(context); double gpsOnCost=powCal.getAveragePower(powCal.POWER_GPS_ON); Log.i("gpsPowerConsumption", "Gps power consumption is:"+gpsOnCost); return gpsOnCost; } public static double [] getAverageCpuPower(Context context){ double result[]=new double[3]; PowerProfile powCal=new PowerProfile(context); double cpuActiveCost=powCal.getAveragePower(powCal.POWER_CPU_ACTIVE); double cpuIdleCost=powCal.getAveragePower(powCal.POWER_CPU_IDLE); double cpuAwakeCost=powCal.getAveragePower(powCal.POWER_CPU_AWAKE); result[0]=cpuActiveCost; result[1]=cpuIdleCost; result[2]=cpuAwakeCost; Log.i("cpuPowerConsumption", "When cpu is active:\n"+cpuActiveCost); Log.i("cpuPowerConsumption", "When cpu is idle:\n"+cpuIdleCost); Log.i("cpuPowerConsumption", "When cpu is awake:\n"+cpuAwakeCost); return result; } public static double getAverageScreenPower(Context context){ PowerProfile powCal=new PowerProfile(context); double screenCost=0; //double wifiScanCost=powCal.getAveragePower(powCal.POWER_WIFI_SCAN); double screenOnCost=powCal.getAveragePower(powCal.POWER_SCREEN_ON); if(SamplingLibrary.getScreenBrightness(context)==255){ screenCost=powCal.getAveragePower(powCal.POWER_SCREEN_FULL); } else{ double curBrightness=SamplingLibrary.getScreenBrightness(context); screenCost=curBrightness/255.0*powCal.getAveragePower(powCal.POWER_SCREEN_FULL); } double screenPowerCost=screenOnCost+screenCost; Log.i("screenPowerConsumption", "Screen power consumption is:"+screenPowerCost); return screenPowerCost; } public static double getAverageScreenOnPower(Context context){ PowerProfile powCal=new PowerProfile(context); double screenOnCost=powCal.getAveragePower(powCal.POWER_SCREEN_ON); return screenOnCost; } public static double getAverageVedioPower(Context context){ PowerProfile powCal=new PowerProfile(context); double vedioOnCost=powCal.getAveragePower(powCal.POWER_VIDEO); Log.i("vedioPowerConsumption", "Vedio power consumption is:"+vedioOnCost); return vedioOnCost; } public static double getAverageAudioPower(Context context){ PowerProfile powCal=new PowerProfile(context); double audioOnCost=powCal.getAveragePower(powCal.POWER_AUDIO); Log.i("audioPowerConsumption", "Audio power consumption is:"+audioOnCost); return audioOnCost; } public static double getAverageRadioPower(Context context){ PowerProfile powCal=new PowerProfile(context); //double radioScanCost=powCal.getAveragePower(powCal.POWER_RADIO_SCANNING); double radioOnCost=powCal.getAveragePower(powCal.POWER_RADIO_ON); double radioActiveCost=powCal.getAveragePower(powCal.POWER_RADIO_ACTIVE); double radioPowerCost=radioOnCost*0.05+radioActiveCost*0.05; Log.i("radioPowerConsumption", "Radio power consumption is:"+radioPowerCost); return radioPowerCost; } public static void printAverageFeaturePower(Context context){ PowerProfile powCal=new PowerProfile(context); /** * Power consumption when CPU is in power collapse mode. */ double powerCpuActive=powCal.getAveragePower(powCal.POWER_CPU_ACTIVE); /** * Power consumption when CPU is awake (when a wake lock is held). This * should be 0 on devices that can go into full CPU power collapse even * when a wake lock is held. Otherwise, this is the power consumption in * addition to POWERR_CPU_IDLE due to a wake lock being held but with no * CPU activity. */ double powerCpuAwake=powCal.getAveragePower(powCal.POWER_CPU_AWAKE); /** * Power consumption when CPU is in power collapse mode. */ double powerCpuIdle=powCal.getAveragePower(powCal.POWER_CPU_IDLE); /** * Power consumption when Bluetooth driver is on. */ double powerBluetoothOn=powCal.getAveragePower(powCal.POWER_BLUETOOTH_ON); /** * Power consumption when Bluetooth driver is transmitting/receiving. */ double powerBluetoothActive=powCal.getAveragePower(powCal.POWER_BLUETOOTH_ACTIVE); /** * Power consumption when Bluetooth driver gets an AT command. */ double powerBluetoothAtCommand=powCal.getAveragePower(powCal.POWER_BLUETOOTH_AT_CMD); /** * Power consumption when cell radio is on but not on a call. */ double powerRadioOn=powCal.getAveragePower(powCal.POWER_RADIO_ON); /** * Power consumption when talking on the phone. */ double powerRadioActive=powCal.getAveragePower(powCal.POWER_RADIO_ACTIVE); /** * Power consumption when cell radio is hunting for a signal. */ double powerRadioScanning=powCal.getAveragePower(powCal.POWER_RADIO_SCANNING); /** * Power consumption when screen is on, not including the backlight power. */ double powerScreenOn=powCal.getAveragePower(powCal.POWER_SCREEN_ON); /** * Power consumption at full backlight brightness. If the backlight is at * 50% brightness, then this should be multiplied by 0.5 */ double powerScreenFull=powCal.getAveragePower(powCal.POWER_SCREEN_FULL); /** * Power consumption when GPS is on. */ double powerGpsOn=powCal.getAveragePower(powCal.POWER_GPS_ON); /** * Power consumption when WiFi driver is on. */ double powerWifiOn=powCal.getAveragePower(powCal.POWER_WIFI_ON); /** * Power consumption when WiFi driver is transmitting/receiving. */ double powerWifiActive=powCal.getAveragePower(powCal.POWER_WIFI_ACTIVE); /** * Power consumption when WiFi driver is scanning for networks. */ double powerWifiScan=powCal.getAveragePower(powCal.POWER_WIFI_SCAN); /** * Power consumed by any media hardware when playing back video content. This is in addition * to the CPU power, probably due to a DSP. */ double powerVedioOn=powCal.getAveragePower(powCal.POWER_VIDEO); /** * Power consumed by the audio hardware when playing back audio content. This is in addition * to the CPU power, probably due to a DSP and / or amplifier. */ double powerAudioOn=powCal.getAveragePower(powCal.POWER_AUDIO); /** * Battery capacity in milliAmpHour (mAh). */ double batteryCapacity=powCal.getBatteryCapacity(); Log.i(TAG, "Power consumption when CPU is active"+powerCpuActive); Log.i(TAG, "Power consumption when CPU is awake"+powerCpuAwake); Log.i(TAG, "Power consumption when CPU is idle"+powerCpuIdle); Log.i(TAG, "Power consumption when bluetooth is on "+powerBluetoothOn); Log.i(TAG, "Power consumption when bluetooth is active "+powerBluetoothActive); Log.i(TAG, "Power consumption when bluetooth is at command "+powerBluetoothAtCommand); Log.i(TAG, "Power consumption when radio is on "+powerRadioOn); Log.i(TAG, "Power consumption when radio is active "+powerRadioActive); Log.i(TAG, "Power consumption when radio is scanning"+powerRadioScanning); Log.i(TAG, "Power consumption when screen is on "+powerScreenOn); Log.i(TAG, "Power consumption when screen is full "+powerScreenFull); Log.i(TAG, "Power consumption when Gps is on "+powerGpsOn); Log.i(TAG, "Power consumption when wifi is on "+powerWifiOn); Log.i(TAG, "Power consumption when wifi is active "+powerWifiActive); Log.i(TAG, "Power consumption when wifi is scanning "+powerWifiScan); Log.i(TAG, "Power consumption when vedio is on "+powerVedioOn); Log.i(TAG, "Power consumption when audio is on "+powerAudioOn); Log.i(TAG, "Battery capacity is "+batteryCapacity); } public static double bluetoothBenefit(Context context){ double bluetoothPowerCost=SamplingLibrary.getAverageBluetoothPower(context); Log.d("bluetoothPowerCost", "Bluetooth power cost: " + bluetoothPowerCost); double batteryCapacity=SamplingLibrary.getBatteryCapacity(context); Log.d("batteryCapacity", "Battery capacity: " + batteryCapacity); double benefit=batteryCapacity/bluetoothPowerCost; Log.d("BluetoothPowerBenefit", "Bluetooth power benefit: " + benefit); return benefit; } public static double wifiBenefit(Context context){ double wifiPowerCost=SamplingLibrary.getAverageWifiPower(context); Log.d("wifiPowerCost", "wifi power cost: " + wifiPowerCost); double batteryCapacity=SamplingLibrary.getBatteryCapacity(context); Log.d("batteryCapacity", "Battery capacity: " + batteryCapacity); // This is not that simple. We have to compare with Carat battery life or power profile battery life -- without wifi. --Eemil double benefit=(batteryCapacity/wifiPowerCost); Log.d("wifiPowerBenefit", "wifi power benefit: " + benefit); return benefit; } public static double gpsBenefit(Context context){ double gpsPowerCost=SamplingLibrary.getAverageGpsPower(context); Log.d("gpsPowerCost", "gps power cost: " + gpsPowerCost); double batteryCapacity=SamplingLibrary.getBatteryCapacity(context); Log.d("batteryCapacity", "Battery capacity: " + batteryCapacity); double benefit=batteryCapacity/gpsPowerCost; Log.d("gpsPowerBenefit", "gps power benefit: " + benefit); return benefit; } public static double screenBrightnessBenefit(Context context){ double screenPowerCost=SamplingLibrary.getAverageScreenPower(context); Log.d("screenPowerCost", "screen power cost: " + screenPowerCost); double batteryCapacity=SamplingLibrary.getBatteryCapacity(context); Log.d("batteryCapacity", "Battery capacity: " + batteryCapacity); double benefit=batteryCapacity/screenPowerCost; Log.d("screenPowerBenefit", "screen power benefit: " + benefit); return benefit; } private static Location lastKnownLocation = null; public static double getBatteryLevel(Context context, Intent intent){ double level = intent.getIntExtra("level", -1); double scale = intent.getIntExtra("scale", 100); // use last known value double batteryLevel = 0.0; // if we have real data, change old value if (level > 0 && scale > 0) { batteryLevel = (level / scale); } return batteryLevel; } public static boolean killApp(Context context, String packageName, String label){ ActivityManager am = (ActivityManager) context .getSystemService(Activity.ACTIVITY_SERVICE); if (am != null){ try{ PackageInfo p = getPackageInfo(context, packageName); Log.v(STAG, "Trying to kill proc="+packageName + " pak=" + p.packageName); FlurryAgent.logEvent("Killing app="+(label==null?"null":label)+" proc="+packageName+" pak="+ (p==null?"null":p.packageName)); am.killBackgroundProcesses(packageName); return true; }catch (Throwable th){ Log.e(STAG, "Could not kill process: " + packageName, th); } } return false; } public static Sample getSample(Context context, Intent intent, Sample lastSample) { String action = intent.getAction(); // Construct sample and return it in the end Sample mySample = new Sample(); SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); boolean newUuid = p.getBoolean(CaratApplication.PREFERENCE_NEW_UUID, false); if (newUuid) mySample.setUuId(SamplingLibrary.getUuid(context)); else mySample.setUuId(SamplingLibrary.getAndroidId(context)); mySample.setTriggeredBy(action); // required always long now = System.currentTimeMillis(); mySample.setTimestamp(now / 1000.0); // Record first data point for CPU usage long[] idleAndCpu1 = readUsagePoint(); List<ProcessInfo> processes = getRunningProcessInfoForSample(context); mySample.setPiList(processes); int screenBrightness = SamplingLibrary.getScreenBrightness(context); mySample.setScreenBrightness(screenBrightness); boolean autoScreenBrightness = SamplingLibrary .isAutoBrightness(context); if (autoScreenBrightness) mySample.setScreenBrightness(-1); // Auto // boolean gpsEnabled = SamplingLibrary.getGpsEnabled(context); // Location providers List<String> enabledLocationProviders = SamplingLibrary .getEnabledLocationProviders(context); mySample.setLocationProviders(enabledLocationProviders); // TODO: not in Sample yet // int maxNumSatellite = SamplingLibrary.getMaxNumSatellite(context); String network = SamplingLibrary.getNetworkStatus(context); String networkType = SamplingLibrary.getNetworkType(context); String mobileNetworkType = SamplingLibrary .getMobileNetworkType(context); // Required in new Carat protocol if (network.equals(NETWORKSTATUS_CONNECTED)){ if (networkType.equals("WIFI")) mySample.setNetworkStatus(networkType); else mySample.setNetworkStatus(mobileNetworkType); }else mySample.setNetworkStatus(network); //String ns = mySample.getNetworkStatus(); //Log.d(STAG, "Set networkStatus="+ns); // Network details NetworkDetails nd = new NetworkDetails(); // Network type nd.setNetworkType(networkType); nd.setMobileNetworkType(mobileNetworkType); boolean roamStatus = SamplingLibrary.getRoamingStatus(context); nd.setRoamingEnabled(roamStatus); String dataState = SamplingLibrary.getDataState(context); nd.setMobileDataStatus(dataState); String dataActivity = SamplingLibrary.getDataActivity(context); nd.setMobileDataActivity(dataActivity); // Wifi stuff String wifiState = SamplingLibrary.getWifiState(context); nd.setWifiStatus(wifiState); int wifiSignalStrength = SamplingLibrary.getWifiSignalStrength(context); nd.setWifiSignalStrength(wifiSignalStrength); int wifiLinkSpeed = SamplingLibrary.getWifiLinkSpeed(context); nd.setWifiLinkSpeed(wifiLinkSpeed); // Add NetworkDetails substruct to Sample mySample.setNetworkDetails(nd); // TODO: is this used for something? // WifiInfo connectionInfo=SamplingLibrary.getWifiInfo(context); /* Calling Information */ // List<String> callInfo; // callInfo=SamplingLibrary.getCallInfo(context); /* Total call time */ // long totalCallTime=0; // totalCallTime=SamplingLibrary.getTotalCallDur(context); /* * long[] incomingOutgoingIdle = getCalltimesSinceBoot(context); * Log.d(STAG, "Call time since boot: Incoming=" + * incomingOutgoingIdle[0] + " Outgoing=" + incomingOutgoingIdle[1] + * " idle=" + incomingOutgoingIdle[2]); * * // Summary Call info CallInfo ci = new CallInfo(); String callState = * SamplingLibrary.getCallState(context); ci.setCallStatus(callState); * ci.setIncomingCallTime(incomingOutgoingIdle[0]); * ci.setOutgoingCallTime(incomingOutgoingIdle[1]); * ci.setNonCallTime(incomingOutgoingIdle[2]); * * mySample.setCallInfo(ci); */ double level = intent.getIntExtra("level", -1); int health = intent.getIntExtra("health", 0); double scale = intent.getIntExtra("scale", 100); int status = intent.getIntExtra("status", 0); // This is really an int. double voltage = intent.getIntExtra("voltage", 0) / 1000.0; // current battery voltage in volts // FIXED: Not used yet, Sample needs more fields int temperature = intent.getIntExtra("temperature", 0) / 10; // current battery temperature in a degree Centigrade int plugged = intent.getIntExtra("plugged", 0); String batteryTechnology = intent.getStringExtra("batteryTechnology"); // use last known value double batteryLevel = 0.0; if (lastSample != null) batteryLevel = lastSample.getBatteryLevel(); // if we have real data, change old value if (level > 0 && scale > 0) { batteryLevel = (level / scale); Log.d(STAG, "BatteryLevel: " + batteryLevel); } // FIXED: Not used yet, Sample needs more fields String batteryHealth = "Unknown"; String batteryStatus = "Unknown"; switch (health) { case BatteryManager.BATTERY_HEALTH_DEAD: batteryHealth = "Dead"; break; case BatteryManager.BATTERY_HEALTH_GOOD: batteryHealth = "Good"; break; case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE: batteryHealth = "Over voltage"; break; case BatteryManager.BATTERY_HEALTH_OVERHEAT: batteryHealth = "Overheat"; break; case BatteryManager.BATTERY_HEALTH_UNKNOWN: batteryHealth = "Unknown"; break; case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE: batteryHealth = "Unspecified failure"; break; } switch (status) { case BatteryManager.BATTERY_STATUS_CHARGING: batteryStatus = "Charging"; break; case BatteryManager.BATTERY_STATUS_DISCHARGING: batteryStatus = "Discharging"; break; case BatteryManager.BATTERY_STATUS_FULL: batteryStatus = "Full"; break; case BatteryManager.BATTERY_STATUS_NOT_CHARGING: batteryStatus = "Not charging"; break; case BatteryManager.BATTERY_STATUS_UNKNOWN: batteryStatus = "Unknown"; break; default: // use last known value if (lastSample != null) batteryStatus = lastSample.getBatteryState(); } // FIXED: Not used yet, Sample needs more fields String batteryCharger = "unplugged"; switch (plugged) { case BatteryManager.BATTERY_PLUGGED_AC: batteryCharger = "ac"; break; case BatteryManager.BATTERY_PLUGGED_USB: batteryCharger = "usb"; break; } BatteryDetails bd = new BatteryDetails(); // otherInfo.setCPUIdleTime(totalIdleTime); bd.setBatteryTemperature(temperature); // otherInfo.setBatteryTemperature(temperature); bd.setBatteryVoltage(voltage); // otherInfo.setBatteryVoltage(voltage); bd.setBatteryTechnology(batteryTechnology); bd.setBatteryCharger(batteryCharger); bd.setBatteryHealth(batteryHealth); mySample.setBatteryDetails(bd); mySample.setBatteryLevel(batteryLevel); mySample.setBatteryState(batteryStatus); int[] usedFreeActiveInactive = SamplingLibrary.readMeminfo(); if (usedFreeActiveInactive != null && usedFreeActiveInactive.length == 4) { mySample.setMemoryUser(usedFreeActiveInactive[0]); mySample.setMemoryFree(usedFreeActiveInactive[1]); mySample.setMemoryActive(usedFreeActiveInactive[2]); mySample.setMemoryInactive(usedFreeActiveInactive[3]); } // TODO: Memory Wired should have memory that is "unevictable", that // will always be used even when all apps are killed // Log.d(STAG, "serial=" + getBuildSerial()); // Record second data point for cpu/idle time now = System.currentTimeMillis(); long[] idleAndCpu2 = readUsagePoint(); CpuStatus cs = new CpuStatus(); cs.setCpuUsage(getUsage(idleAndCpu1, idleAndCpu2)); cs.setUptime(getUptime()); mySample.setCpuStatus(cs); //printAverageFeaturePower(context); return mySample; } }
package org.slf4j.ext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * This class is essentially a wrapper around an * {@link LoggerFactory} producing {@link XLogger} instances. * * <p>Contrary to {@link LoggerFactory#getLogger(String)} method of * {@link LoggerFactory}, each call to {@link getXLogger} * produces a new instance of XLogger. This should not matter because an * XLogger instance does not have any state beyond that of the Logger instance * it wraps. * * @author Ralph Goers * @author Ceki G&uuml;lc&uuml; */ public class XLoggerFactory { /** * Get an XLogger instance by name. * * @param name * @return */ public static XLogger getXLogger(String name) { return new XLogger(LoggerFactory.getLogger(name)); } /** * Get a new XLogger instance by class. The returned XLogger * will be named after the class. * * @param clazz * @return */ @SuppressWarnings("unchecked") public static XLogger getXLogger(Class clazz) { return getXLogger(clazz.getName()); } }
package com.cngu.kittenviewer.ui.presenter; import android.graphics.Bitmap; import android.util.Log; import com.cngu.kittenviewer.R; import com.cngu.kittenviewer.data.listener.DownloadListener; import com.cngu.kittenviewer.domain.service.ImageDownloadService; import com.cngu.kittenviewer.ui.activity.UIThreadExecutor; import com.cngu.kittenviewer.ui.model.PlaceKittenArgs; import com.cngu.kittenviewer.ui.view.KittenPhotoView; public class KittenPhotoPresenterImpl implements KittenPhotoPresenter, DownloadListener<Bitmap> { private static final String TAG = "KittenPhotoPresenter"; private static final boolean DEBUG = true; private KittenPhotoView mView; private UIThreadExecutor mUiThreadExecutor; private ImageDownloadService mImageDownloadService; public KittenPhotoPresenterImpl(KittenPhotoView view, UIThreadExecutor uiThreadExecutor) { mView = view; mUiThreadExecutor = uiThreadExecutor; } @Override public void onViewCreated() { downloadPlaceKittenPhoto(); } @Override public void onServiceConnected(ImageDownloadService imageDownloadService) { mImageDownloadService = imageDownloadService; } @Override public void onSearchButtonClicked() { downloadPlaceKittenPhoto(); } @Override public void onRequestedPhotoDimenChanged(int requestedPhotoWidth, int requestedPhotoHeight) { boolean validDimensions = requestedPhotoWidth > 0 && requestedPhotoHeight > 0; mView.setSearchButtonEnabled(validDimensions); } @Override public void onDownloadComplete(final Bitmap download) { if (DEBUG) { Log.i(TAG, String.format("Received bitmap of size: %dx%d", download.getWidth(), download.getHeight())); } showDownloadProgress(false, 0); showKittenPhoto(download); } @Override public void onDownloadMissing() { if (DEBUG) Log.i(TAG, "Placekitten did not return an image with the requested dimensions"); showDownloadProgress(false, R.string.msg_placekitten_missing_photo); } @Override public void onDownloadError() { if (DEBUG) Log.i(TAG, "Placekitten returned an error"); showDownloadProgress(false, R.string.msg_placekitten_error); } @Override public void onNetworkConnectionLost() { if (DEBUG) Log.i(TAG, "WiFi connection was lost during download"); showDownloadProgress(false, R.string.msg_not_connected_to_wifi); } private void downloadPlaceKittenPhoto() { int reqWidth = mView.getRequestedPhotoWidth(); int reqHeight = mView.getRequestedPhotoHeight(); if (reqWidth <= 0 || reqHeight <= 0) { Log.e(TAG, "Can not download photo with invalid size dimensions <=0"); return; } showDownloadProgress(true, 0); PlaceKittenArgs args = new PlaceKittenArgs(reqWidth, reqHeight); mImageDownloadService.downloadBitmap(args, this); } private void showDownloadProgress(final boolean progressBarVisible, final int msgResId) { mUiThreadExecutor.runOnUiThread(new Runnable() { @Override public void run() { mView.setDownloadProgressBarVisibility(progressBarVisible); if (msgResId > 0) { // Valid resources ids are always positive mView.showToast(msgResId); } } }); } private void showKittenPhoto(final Bitmap bitmap) { mUiThreadExecutor.runOnUiThread(new Runnable() { @Override public void run() { mView.setKittenPhoto(bitmap); } }); } }
package com.felix.zhiban.modelinterface.book; public interface IDoubanBookDetailModel { void initBookById(String id); }
package com.gogocosmo.cosmoqiu.fire_sticker.Acitivty; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Color; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewTreeObserver; import android.view.animation.AlphaAnimation; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.ListView; import com.gogocosmo.cosmoqiu.fire_sticker.Adapter.DrawerRecyclerViewAdapter; import com.gogocosmo.cosmoqiu.fire_sticker.Adapter.ItemArrayAdapter; import com.gogocosmo.cosmoqiu.fire_sticker.Adapter.ViewPagerAdapter; import com.gogocosmo.cosmoqiu.fire_sticker.Fragment.TabFragment; import com.gogocosmo.cosmoqiu.fire_sticker.Model.ItemFactory; import com.gogocosmo.cosmoqiu.fire_sticker.R; import com.gogocosmo.cosmoqiu.slidingtablibrary.SlidingTabLayout; import java.util.ArrayList; import java.util.HashMap; public class LaunchActivity extends ActionBarActivity implements TabFragment.OnTabListItemClickListener, DrawerRecyclerViewAdapter.IDrawerListItemClickListener, android.view.ActionMode.Callback, SlidingTabLayout.OnPageScrollListener { static final private String TAG = "MEMORY-ACC"; // Load the inital data for testing purpose static { String[] questionSamples = new String[]{ "How many rings on the Olympic flag?", "What is the currency of Austria?", "How did Alfred Nobel make his money?", "Which car company makes the Celica?", "What is a baby rabbit called?", "What is a Winston Churchill?", "What plant does the Colorado beetle attack?", "Who wrote the Opera Madam Butterfly?", "Which country do Sinologists study?", "What was the first James Bond film?", "How many rings on the Olympic flag?", "What is the currency of Austria?", "How did Alfred Nobel make his money?", "Which car company makes the Celica?", "What is a baby rabbit called?", "What is a Winston Churchill?", "What plant does the Colorado beetle attack?", "Who wrote the Opera Madam Butterfly?", "Which country do Sinologists study?", "What was the first James Bond film?" }; String[] answerSamples = new String[]{ "Five", "Schilling", "He invented Dynamite", "Toyota", "Kit or Kitten", "Cigar", "Potato", "Puccini", "China", "Dr No", "Five", "Schilling", "He invented Dynamite", "Toyota", "Kit or Kitten", "Cigar", "Potato", "Puccini", "China", "Dr No" }; ItemFactory.createGroup("Job Steve"); ItemFactory.createGroup("Larry Page"); ItemFactory.createGroup("Elon Musk"); ItemFactory.createGroup("Bill Gates"); for (int j = 0; j < ItemFactory.getItemGroupList().size(); ++j) { for (int i = 0; i < 10; ++i) { String title = ""; Boolean light = false; if (i % (j + 1) == 0) { title = "Awesome Title"; light = true; } ItemFactory.createItem(j, questionSamples[i], answerSamples[i], title, light); } } } final private int EDIT_GROUP_REQ = 1; final private int VIEW_DETAILS_REQ = 2; final private int NEW_ITEM_REQ = 3; private ImageButton _fireButton; private Toolbar _toolbar; // Declaring Tab Views and Variables private ViewPager _pager; private ViewPagerAdapter _viewPagerAdapter; private SlidingTabLayout _slidingTabsLayout; // Declaring Drawer Views and Variables private ActionBarDrawerToggle _drawerToggle; private RecyclerView _drawerRecyclerView; private RecyclerView.Adapter _drawerViewAdapter; private RecyclerView.LayoutManager _drawerRecyclerViewLayoutManager; private DrawerLayout _drawerLayout; private String _activityTitle; // Action Mode and Variables private Menu _menu; private android.view.ActionMode _actionMode; private ListView _activatedItemListView; private int _activatedGroupId; private ItemArrayAdapter _activatedItemArrayAdapter; int PROFILE = R.drawable.lollipop; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_launch); _toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object setSupportActionBar(_toolbar); _toolbar.setTitleTextColor(Color.WHITE); _pager = (ViewPager) findViewById(R.id.pager); _slidingTabsLayout = (SlidingTabLayout) findViewById(R.id.tabs); // Setting Custom Color for the Scroll bar indicator of the Tab View _slidingTabsLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() { @Override public int getIndicatorColor(int position) { return getResources().getColor(R.color.tabsScrollColor); } }); updateSlidingTabs(); _fireButton = (ImageButton) findViewById(R.id.FireButton); _fireButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F); v.startAnimation(buttonClick); // TODO: (DONE) add groupId support for carousel activity Intent intent = new Intent(LaunchActivity.this, CarouselActivity.class); intent.putExtra("GROUP", _activatedGroupId); startActivity(intent); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); } }); _drawerRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); _drawerRecyclerView.setHasFixedSize(true); _drawerRecyclerViewLayoutManager = new LinearLayoutManager(this); _drawerRecyclerView.setLayoutManager(_drawerRecyclerViewLayoutManager); _activityTitle = getTitle().toString(); _drawerLayout = (DrawerLayout) findViewById(R.id.DrawerLayout); updateDrawerItems(); setupDrawer(); } private void updateSlidingTabs() { // TODO: Maybe add support for method notifyDataChanged() here _viewPagerAdapter = new ViewPagerAdapter( getSupportFragmentManager(), ItemFactory.getItemGroupList(), ItemFactory.getItemGroupList().size()); _pager.setAdapter(_viewPagerAdapter); if (ItemFactory.getItemGroupList().size() <= 4) { // To make the Tabs Fixed set this true, This makes the _slidingTabsLayout Space Evenly // in Available width _slidingTabsLayout.setDistributeEvenly(true); } else { _slidingTabsLayout.setDistributeEvenly(false); } _slidingTabsLayout.setViewPager(_pager); // Update the Tabs } private void updateDrawerItems() { String[] osArray = ItemFactory.getItemGroupList().toArray(new String[ItemFactory.getItemGroupList().size()]); _drawerViewAdapter = new DrawerRecyclerViewAdapter(osArray, "", "", PROFILE, this); // Setting the adapter to RecyclerView _drawerRecyclerView.setAdapter(_drawerViewAdapter); } private void setupDrawer() { _drawerToggle = new ActionBarDrawerToggle(this, _drawerLayout, _toolbar, R.string.drawer_open, R.string.drawer_close) { @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); super.onDrawerSlide(drawerView, 0); // Disable hamburger/arrow animation // code here will execute once the drawer is opened invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() if (_actionMode != null) { _actionMode.finish(); } } @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); // Code here will execute once drawer is closed getSupportActionBar().setTitle(_activityTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } @Override public void onDrawerSlide(View drawerView, float slideOffset) { super.onDrawerSlide(drawerView, 0); // Disable hamburger/arrow animation } }; // Drawer Toggle Object Made getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); _drawerToggle.setDrawerIndicatorEnabled(true); _drawerLayout.setDrawerListener(_drawerToggle); // Drawer Listener set to the Drawer toggle } private void deleteListItem() { int toRemoveIndex = ItemFactory.getSelectedItemIndex(_activatedGroupId); animateRemoval( _activatedItemArrayAdapter, _activatedItemListView, toRemoveIndex); } @Override public void OnListItemLongClicked(ItemArrayAdapter adapter, ListView listView, View view, int groupId, int position) { //TODO: (DONE) Add Support for item list click listView.setItemChecked(position, true); ItemFactory.setSelectedGroupItemIndex(groupId, position); _activatedItemArrayAdapter = adapter; _activatedItemListView = listView; _activatedGroupId = groupId; startActionMode(this); } @Override public void OnListItemClicked(ItemArrayAdapter adapter, ListView listView, View view, int groupId, int position) { //TODO: (DONE) Add Support for item list long click if (_actionMode != null) { ItemFactory.setSelectedGroupItemIndex(groupId, position); return; } Intent intent = new Intent(this, ViewActivity.class); intent.putExtra("POSITION", position); intent.putExtra("GROUP", groupId); startActivityForResult(intent, VIEW_DETAILS_REQ); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); } @Override public void onDrawerItemClicked(View v, int position, int viewType) { switch (viewType) { case DrawerRecyclerViewAdapter.TYPE_ITEM: // Set the new Tab as the current Tab _slidingTabsLayout.setCurrentTab(position); _drawerLayout.closeDrawers(); break; case DrawerRecyclerViewAdapter.TYPE_HEADER: break; case DrawerRecyclerViewAdapter.TYPE_END: Intent intent = new Intent(this, EditGroupActivity.class); startActivityForResult(intent, EDIT_GROUP_REQ); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); break; default: } } @Override public void OnPageScrolled(int position) { // Called when clients scroll the page tab if (_actionMode != null) { _actionMode.finish(); } _activatedGroupId = position; // Log.d(TAG, "_activatedGroupId = " + String.valueOf(_activatedGroupId)); } @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_launch, menu); _menu = menu; MenuItem itemAdd = _menu.findItem(R.id.action_add); MenuItem itemDelete = _menu.findItem(R.id.action_delete); MenuItem itemBack = _menu.findItem(R.id.action_back); MenuItem itemSlash = _menu.findItem(R.id.action_blank); itemAdd.setVisible(true); itemBack.setVisible(false); itemDelete.setVisible(false); itemSlash.setVisible(false); 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. // Activate the navigation drawer toggle if (_drawerToggle.onOptionsItemSelected(item)) { if (_actionMode != null) { _actionMode.finish(); } return true; } switch (item.getItemId()) { case R.id.action_delete: deleteListItem(); if (_actionMode != null) { _actionMode.finish(); } return true; case R.id.action_add: Intent intent = new Intent(this, NewItemActivity.class); intent.putExtra("CURRENT_TAB", _slidingTabsLayout.getCurrentTabPosition()); startActivityForResult(intent, NEW_ITEM_REQ); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); return true; case R.id.action_back: if (_actionMode != null) { _actionMode.finish(); } return true; default: } return super.onOptionsItemSelected(item); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); _drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); _drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.menu_launch, menu); getSupportActionBar().setTitle(""); MenuItem itemAdd = _menu.findItem(R.id.action_add); MenuItem itemDelete = _menu.findItem(R.id.action_delete); MenuItem itemBack = _menu.findItem(R.id.action_back); MenuItem itemSlash = _menu.findItem(R.id.action_blank); itemAdd.setVisible(false); itemBack.setVisible(true); itemDelete.setVisible(true); itemSlash.setVisible(true); _fireButton.setVisibility(View.INVISIBLE); _actionMode = mode; // Return false since we are using a fake Action Mode with a toolbar return false; } @Override public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) { // We are using a fake Action Mode with a toolbar return false; } @Override public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) { // We are using a fake Action Mode with a toolbar return false; } @Override public void onDestroyActionMode(android.view.ActionMode mode) { // We are using a fake Action Mode with a toolbar Log.d(TAG, "onDestroyActionMode"); getSupportActionBar().setTitle(_activityTitle); MenuItem itemAdd = _menu.findItem(R.id.action_add); MenuItem itemDelete = _menu.findItem(R.id.action_delete); MenuItem itemBack = _menu.findItem(R.id.action_back); MenuItem itemSlash = _menu.findItem(R.id.action_blank); itemAdd.setVisible(true); itemBack.setVisible(false); itemDelete.setVisible(false); itemSlash.setVisible(false); _fireButton.setVisibility(View.VISIBLE); _actionMode = null; if (_activatedItemListView != null) { //TODO: (DONE) Add Support for Group ID _activatedItemListView.setItemChecked(ItemFactory.getSelectedItemIndex(_activatedGroupId), false); } } @Override protected void onResume() { super.onResume(); _slidingTabsLayout.registerPageScrollListener(this); } @Override protected void onPause() { super.onPause(); _slidingTabsLayout.unregisterPageScrollListener(this); // End the Action Mode when this Activity is no longer visible if (_actionMode != null) { _actionMode.finish(); _actionMode = null; } } @Override public void onBackPressed() { if (_actionMode != null) { // If the Action Mode is on, then pressing BACK should exit the Action Mode, instead of // exit the App. _actionMode.finish(); _actionMode = null; return; } super.onBackPressed(); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == EDIT_GROUP_REQ) { if (resultCode == RESULT_OK) { updateDrawerItems(); updateSlidingTabs(); } if (resultCode == RESULT_CANCELED) { } } else if (requestCode == VIEW_DETAILS_REQ) { if (resultCode == RESULT_OK) { updateSlidingTabs(); _slidingTabsLayout.setCurrentTab(_activatedGroupId); } if (resultCode == RESULT_CANCELED) { } } else if (requestCode == NEW_ITEM_REQ) { if (resultCode == RESULT_OK) { int updatedGroupId = data.getExtras().getInt("UPDATED_GROUP"); updateSlidingTabs(); _slidingTabsLayout.setCurrentTab(updatedGroupId); } if (resultCode == RESULT_CANCELED) { } } }//onActivityResult // Adapted from Google I/O 2013 public void animateRemoval(final ArrayAdapter adapter, final ListView listview, int position) { final HashMap<Long, Integer> mItemIdTopMap = new HashMap<>(); int firstVisiblePosition = listview.getFirstVisiblePosition(); for (int i = 0; i < listview.getChildCount(); ++i) { int tmpPosition = firstVisiblePosition + i; if (tmpPosition != position) { View child = listview.getChildAt(i); long itemId = adapter.getItemId(tmpPosition); mItemIdTopMap.put(itemId, child.getTop()); } } // Delete the item from the adapter adapter.remove(adapter.getItem(position)); final ViewTreeObserver observer = listview.getViewTreeObserver(); observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { observer.removeOnPreDrawListener(this); boolean firstAnimation = true; int firstVisiblePosition = listview.getFirstVisiblePosition(); for (int i = 0; i < listview.getChildCount(); ++i) { final View child = listview.getChildAt(i); int position = firstVisiblePosition + i; long itemId = adapter.getItemId(position); Integer startTop = mItemIdTopMap.get(itemId); int top = child.getTop(); if (startTop != null) { if (startTop != top) { int delta = startTop - top; child.setTranslationY(delta); child.animate().setDuration(300).translationY(0); if (firstAnimation) { child.animate().withEndAction(new Runnable() { public void run() { listview.setEnabled(true); } }); firstAnimation = false; } } } else { // Animate new views along with the others. The catch is that they did not // exist in the start state, so we must calculate their starting position // based on neighboring views. int childHeight = child.getHeight() + listview.getDividerHeight(); startTop = top + (i > 0 ? childHeight : -childHeight); int delta = startTop - top; child.setTranslationY(delta); child.animate().setDuration(300).translationY(0); if (firstAnimation) { child.animate().withEndAction(new Runnable() { public void run() { listview.setEnabled(true); } }); firstAnimation = false; } } } mItemIdTopMap.clear(); return true; } }); } }
package com.mohammedsazid.android.listr; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; import com.mohammedsazid.android.listr.data.ListDbContract; import com.mohammedsazid.android.listr.data.ListProvider; import java.text.SimpleDateFormat; import java.util.Calendar; public class ChecklistItemEditorActivity extends AppCompatActivity { private static int timeHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); private static int timeMinute = Calendar.getInstance().get(Calendar.MINUTE); Toolbar toolbar; Cursor cursor = null; EditText checklistItemContentEt; String content; String previousContent; int id; boolean checkedState; boolean priorityState; boolean alarmState; boolean deletePressed = false; long notifyTime = -1; Menu menu; private AlarmManager alarmManager; private PendingIntent pendingIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_checklist_item_editor); id = getIntent().getIntExtra("_id", -1); bindViews(); setSupportActionBar(toolbar); try { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } catch (Exception e) { } loadContent(); Intent intent = new Intent(this, NotifyService.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.putExtra("_id", id); alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); pendingIntent = PendingIntent.getService(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT); if (alarmState) { String alarmText = (new SimpleDateFormat("h:mm a").format(notifyTime)); getSupportActionBar().setTitle("@ " + alarmText); } else if (id <= -1) { getSupportActionBar().setTitle("New Item"); } } private void bindViews() { checklistItemContentEt = (EditText) findViewById(R.id.checklist_item_content); toolbar = (Toolbar) findViewById(R.id.top_toolbar); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. this.menu = menu; getMenuInflater().inflate(R.menu.menu_checklist_item_editor, menu); setOptionVisibility(menu, R.id.action_notify_off, false); setOptionVisibility(menu, R.id.action_notify, false); if (id > -1) { if (alarmState) { setOptionVisibility(menu, R.id.action_notify, false); setOptionVisibility(menu, R.id.action_notify_off, true); } else { setOptionVisibility(menu, R.id.action_notify, true); setOptionVisibility(menu, R.id.action_notify_off, false); } } 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 menuId = item.getItemId(); switch (menuId) { case R.id.action_delete: new MaterialDialog.Builder(ChecklistItemEditorActivity.this) .title("Delete") .content("Do you really want to delete the item?") .positiveText("Ok") .negativeText("Cancel") .callback(new MaterialDialog.ButtonCallback() { @Override public void onPositive(MaterialDialog dialog) { deletePressed = true; deleteItem(id); content = ""; Intent intent = new Intent(ChecklistItemEditorActivity.this, MainActivity.class); startActivity(intent); } }) .show(); return true; case R.id.action_notify: TimePickerFragment fragment = new TimePickerFragment(new AlarmHandler()); getSupportFragmentManager().beginTransaction() .add(fragment, "time_picker") .commit(); return true; case R.id.action_notify_off: cancelAlarm(); return true; } return super.onOptionsItemSelected(item); } private void setOptionVisibility(Menu menu, int id, boolean visible) { MenuItem item = menu.findItem(id); item.setVisible(visible); } private void loadContent() { if (id > -1) { Uri uri = ContentUris.withAppendedId( ListProvider.CONTENT_URI.buildUpon().appendPath("items").build(), id); closeCursor(); cursor = this.getContentResolver().query( uri, new String[]{ ListDbContract.ChecklistItems._ID, ListDbContract.ChecklistItems.COLUMN_LABEL, ListDbContract.ChecklistItems.COLUMN_CHECKED_STATE, ListDbContract.ChecklistItems.COLUMN_PRIORITY, ListDbContract.ChecklistItems.COLUMN_LAST_MODIFIED, ListDbContract.ChecklistItems.COLUMN_NOTIFY_TIME }, null, null, null ); cursor.moveToFirst(); content = previousContent = cursor.getString( cursor.getColumnIndex(ListDbContract.ChecklistItems.COLUMN_LABEL)); checkedState = cursor.getInt( cursor.getColumnIndex(ListDbContract.ChecklistItems.COLUMN_CHECKED_STATE)) != 0; priorityState = cursor.getInt( cursor.getColumnIndex(ListDbContract.ChecklistItems.COLUMN_PRIORITY)) != 0; alarmState = cursor.getLong( cursor.getColumnIndex(ListDbContract.ChecklistItems.COLUMN_NOTIFY_TIME)) > -1; notifyTime = cursor.getLong( cursor.getColumnIndex(ListDbContract.ChecklistItems.COLUMN_NOTIFY_TIME)); checklistItemContentEt.setText(content); } } @Override public void onPause() { if (!deletePressed) { saveContentToDisk(); } super.onPause(); } @Override public void onDestroy() { super.onDestroy(); closeCursor(); } private void closeCursor() { if (cursor != null && !cursor.isClosed()) { cursor.close(); cursor = null; } } private void saveContentToDisk() { if (id > -1) { content = checklistItemContentEt.getText().toString(); updateItem(id); } else { String content = checklistItemContentEt.getText().toString(); if (!TextUtils.isEmpty(content)) { long currentTime = System.currentTimeMillis(); Uri.Builder builder = ListProvider.CONTENT_URI.buildUpon().appendPath("items"); Uri uri = builder.build(); ContentValues values = new ContentValues(); values.put(ListDbContract.ChecklistItems.COLUMN_LABEL, content); values.put(ListDbContract.ChecklistItems.COLUMN_CHECKED_STATE, 0); values.put(ListDbContract.ChecklistItems.COLUMN_PRIORITY, 0); values.put(ListDbContract.ChecklistItems.COLUMN_LAST_MODIFIED, currentTime); values.put(ListDbContract.ChecklistItems.COLUMN_NOTIFY_TIME, -1); Uri insertUri = this.getContentResolver().insert(uri, values); Toast.makeText(this, "New item inserted.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Empty item discarded.", Toast.LENGTH_SHORT).show(); } } } private void updateItem(long id) { if (TextUtils.isEmpty(content)) { deleteItem(id); } long currentTime = System.currentTimeMillis(); Uri.Builder builder = ListProvider.CONTENT_URI.buildUpon().appendPath("items"); Uri uri = ContentUris.withAppendedId(builder.build(), id); ContentValues values = new ContentValues(); if (!content.equals(previousContent)) { values.put(ListDbContract.ChecklistItems.COLUMN_LABEL, content); values.put(ListDbContract.ChecklistItems.COLUMN_CHECKED_STATE, checkedState); values.put(ListDbContract.ChecklistItems.COLUMN_PRIORITY, checkedState); values.put(ListDbContract.ChecklistItems.COLUMN_LAST_MODIFIED, currentTime); } values.put(ListDbContract.ChecklistItems.COLUMN_NOTIFY_TIME, notifyTime); int count = this.getContentResolver().update( uri, values, null, null ); if (!content.equals(previousContent) && count > 0) { Toast.makeText(this, "Item updated.", Toast.LENGTH_SHORT).show(); } } private void deleteItem(long id) { if (id > -1) { Uri.Builder builder = ListProvider.CONTENT_URI.buildUpon().appendPath("items"); Uri uri = ContentUris.withAppendedId(builder.build(), id); int count = this.getContentResolver().delete( uri, null, null ); alarmManager.cancel(pendingIntent); if (TextUtils.isEmpty(content)) { Toast.makeText(this, "Empty item discarded.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Item deleted.", Toast.LENGTH_SHORT).show(); } } } private void setAlarm() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, timeHour); calendar.set(Calendar.MINUTE, timeMinute); notifyTime = calendar.getTimeInMillis(); /* If the time selected by the user is less than the current time then schedule it for the next day */ if (notifyTime <= System.currentTimeMillis()) { // add 1 day to the user selected time calendar.add(Calendar.DATE, 1); Toast.makeText( ChecklistItemEditorActivity.this, "Alarm set for tomorrow!", Toast.LENGTH_SHORT).show(); notifyTime = calendar.getTimeInMillis(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); } else { alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); } setOptionVisibility(menu, R.id.action_notify_off, true); setOptionVisibility(menu, R.id.action_notify, false); String alarmText = (new SimpleDateFormat("h:mm a").format(notifyTime)); getSupportActionBar().setTitle("@ " + alarmText); // Toast.makeText(this, "Alarm set", Toast.LENGTH_SHORT).show(); } private void cancelAlarm() { if (alarmManager != null) { alarmManager.cancel(pendingIntent); notifyTime = -1; setOptionVisibility(menu, R.id.action_notify_off, false); setOptionVisibility(menu, R.id.action_notify, true); getSupportActionBar().setTitle("Edit Item"); // Toast.makeText(this, "Alarm cancelled", Toast.LENGTH_SHORT).show(); } } class AlarmHandler extends Handler { @Override public void handleMessage(Message msg) { Bundle bundle = msg.getData(); timeHour = bundle.getInt("time_hour"); timeMinute = bundle.getInt("time_minute"); setAlarm(); } } }
package de.christinecoenen.code.zapp.repositories; import android.content.Context; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.apache.commons.io.IOUtils; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Type; import java.util.Map; import de.christinecoenen.code.zapp.app.livestream.api.model.ChannelInfo; import de.christinecoenen.code.zapp.app.livestream.repository.ChannelInfoRepository; import de.christinecoenen.code.zapp.model.ChannelModel; import de.christinecoenen.code.zapp.model.ISortableChannelList; import de.christinecoenen.code.zapp.model.json.SortableVisibleJsonChannelList; import io.reactivex.Single; import io.reactivex.disposables.Disposable; import timber.log.Timber; public class ChannelRepository { private final String CHANNEL_INFOS_FILE_NAME = "channelInfoList.json"; private final Gson gson = new Gson(); private final Context context; private final ISortableChannelList channelList; private Map<String, ChannelInfo> channelInfoList; public ChannelRepository(Context context) { this.context = context; channelList = new SortableVisibleJsonChannelList(context); Disposable disposable = getChannelInfoListFromApi() .onErrorReturn(t -> getChannelInfoListFromDisk()) .subscribe(this::onChannelInfoListSuccess, Timber::w); } public ISortableChannelList getChannelList() { channelList.reload(); applyToChannelList(channelInfoList); return channelList; } public void deleteCachedChannelInfos() { deleteChannelInfoListFromDisk(); channelList.reload(); } private void onChannelInfoListSuccess(Map<String, ChannelInfo> channelInfoList) { try { writeChannelInfoListToDisk(channelInfoList); } catch (IOException e) { Timber.e(e); } this.channelInfoList = channelInfoList; applyToChannelList(channelInfoList); } private void applyToChannelList(Map<String, ChannelInfo> channelInfoList) { for (String channelId : channelInfoList.keySet()) { ChannelModel channel = channelList.get(channelId); if (channel != null) { channel.setStreamUrl(channelInfoList.get(channelId).getStreamUrl()); } } } private Single<Map<String, ChannelInfo>> getChannelInfoListFromApi() { return ChannelInfoRepository.getInstance() .getChannelInfoList(); } private Map<String, ChannelInfo> getChannelInfoListFromDisk() throws IOException { try (FileInputStream inputStream = context.openFileInput(CHANNEL_INFOS_FILE_NAME)) { String json = IOUtils.toString(inputStream, "UTF-8"); inputStream.close(); Type type = new TypeToken<Map<String, ChannelInfo>>() { }.getType(); return gson.fromJson(json, type); } } private void writeChannelInfoListToDisk(Map<String, ChannelInfo> channelInfoList) throws IOException { try (FileOutputStream fileOutputStream = context.openFileOutput(CHANNEL_INFOS_FILE_NAME, Context.MODE_PRIVATE)) { String json = gson.toJson(channelInfoList); IOUtils.write(json, fileOutputStream, "UTF-8"); } } private void deleteChannelInfoListFromDisk() { context.deleteFile(CHANNEL_INFOS_FILE_NAME); } }
package edu.stuy.starlorn.entities; public class Bullet extends Entity { protected int speed; protected boolean firedByPlayer, isSeeking; public Bullet(double angle, int speed, String sprite) { super(sprite); this.angle = angle; this.speed = speed; firedByPlayer = false; isSeeking = false; setXvel(speed * Math.cos(-angle)); setYvel(speed * Math.sin(-angle)); } @Override public void step() { if (isSeeking){ setXvel(speed * Math.cos(-angle)); setYvel(speed * Math.sin(-angle)); } super.step(); if (!onScreen()) kill(); for (Ship that : world.getShips()) { if (that.isHit(this)) { this.kill(); that.kill(); Explosion e = new Explosion(); double thatcx = that.getRect().x + that.getRect().width / 2, thatcy = that.getRect().y + that.getRect().height / 2; e.getRect().x = thatcx - e.getRect().width; e.getRect().y = thatcy - e.getRect().height; world.addEntity(e); } } } public void setSpeed(int speed) { this.speed = speed; } public int getSpeed() { return speed; } public void setSeeking(boolean seek) { this.isSeeking = seek; } public boolean getSeeking() { return isSeeking; } public void setFiredByPlayer(boolean value) { firedByPlayer = value; } public boolean wasFiredByPlayer() { return firedByPlayer; } }
package org.jboss.as.appclient.subsystem.parsing; import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP; import static org.jboss.as.controller.parsing.Namespace.DOMAIN_1_0; import static org.jboss.as.controller.parsing.ParseUtils.isNoNamespaceAttribute; import static org.jboss.as.controller.parsing.ParseUtils.missingRequired; import static org.jboss.as.controller.parsing.ParseUtils.nextElement; import static org.jboss.as.controller.parsing.ParseUtils.requireNamespace; import static org.jboss.as.controller.parsing.ParseUtils.requireNoAttributes; import static org.jboss.as.controller.parsing.ParseUtils.unexpectedAttribute; import static org.jboss.as.controller.parsing.ParseUtils.unexpectedElement; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.stream.XMLStreamException; import org.jboss.as.appclient.logging.AppClientLogger; import org.jboss.as.controller.logging.ControllerLogger; import org.jboss.as.controller.extension.ExtensionRegistry; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.controller.parsing.Attribute; import org.jboss.as.controller.parsing.Element; import org.jboss.as.controller.parsing.ExtensionXml; import org.jboss.as.controller.parsing.Namespace; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.as.controller.persistence.ModelMarshallingContext; import org.jboss.as.controller.resource.SocketBindingGroupResourceDefinition; import org.jboss.as.server.parsing.CommonXml; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.modules.ModuleLoader; import org.jboss.staxmapper.XMLExtendedStreamReader; import org.jboss.staxmapper.XMLExtendedStreamWriter; /** * A mapper between an AS server's configuration model and XML representations, particularly {@code appclient.xml}. * * @author Stuart Douglas */ public class AppClientXml extends CommonXml { private final ExtensionXml extensionXml; public AppClientXml(final ModuleLoader loader, final ExtensionRegistry extensionRegistry) { super(); extensionXml = new ExtensionXml(loader, null, extensionRegistry); } public void readElement(final XMLExtendedStreamReader reader, final List<ModelNode> operationList) throws XMLStreamException { final ModelNode address = new ModelNode().setEmptyList(); if (Element.forName(reader.getLocalName()) != Element.SERVER) { throw unexpectedElement(reader); } Namespace readerNS = Namespace.forUri(reader.getNamespaceURI()); switch (readerNS) { case DOMAIN_1_0: readServerElement_1_0(reader, address, operationList); break; default: // Instead of having to list the remaining versions we just check it is actually a valid version. for (Namespace current : Namespace.domainValues()) { if (readerNS.equals(current)) { readServerElement_1_1(readerNS, reader, address, operationList); return; } } throw unexpectedElement(reader); } } /** * Read the <server/> element based on version 1.0 of the schema. * * @param reader the xml stream reader * @param address address of the parent resource of any resources this method will add * @param list the list of boot operations to which any new operations should be added * @throws XMLStreamException if a parsing error occurs */ private void readServerElement_1_0(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list) throws XMLStreamException { parseNamespaces(reader, address, list); String serverName = null; // attributes final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { switch (Namespace.forUri(reader.getAttributeNamespace(i))) { case NONE: { final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: { serverName = value; break; } default: throw unexpectedAttribute(reader, i); } break; } case XML_SCHEMA_INSTANCE: { switch (Attribute.forName(reader.getAttributeLocalName(i))) { case SCHEMA_LOCATION: { parseSchemaLocations(reader, address, list, i); break; } case NO_NAMESPACE_SCHEMA_LOCATION: { // todo, jeez break; } default: { throw unexpectedAttribute(reader, i); } } break; } default: throw unexpectedAttribute(reader, i); } } setServerName(address, list, serverName); // elements - sequence Element element = nextElement(reader, DOMAIN_1_0); if (element == Element.EXTENSIONS) { extensionXml.parseExtensions(reader, address, DOMAIN_1_0, list); element = nextElement(reader, DOMAIN_1_0); } // System properties if (element == Element.SYSTEM_PROPERTIES) { parseSystemProperties(reader, address, DOMAIN_1_0, list, true); element = nextElement(reader, DOMAIN_1_0); } if (element == Element.PATHS) { parsePaths(reader, address, DOMAIN_1_0, list, true); element = nextElement(reader, DOMAIN_1_0); } // Single profile if (element == Element.PROFILE) { parseServerProfile(reader, address, list); element = nextElement(reader, DOMAIN_1_0); } // Interfaces final Set<String> interfaceNames = new HashSet<String>(); if (element == Element.INTERFACES) { parseInterfaces(reader, interfaceNames, address, DOMAIN_1_0, list, true); element = nextElement(reader, DOMAIN_1_0); } // Single socket binding group if (element == Element.SOCKET_BINDING_GROUP) { parseSocketBindingGroup(reader, interfaceNames, address, DOMAIN_1_0, list); element = nextElement(reader, DOMAIN_1_0); } if (element != null) { throw unexpectedElement(reader); } } /** * Read the <server/> element based on version 1.1 of the schema. * * @param reader the xml stream reader * @param address address of the parent resource of any resources this method will add * @param list the list of boot operations to which any new operations should be added * @throws XMLStreamException if a parsing error occurs */ private void readServerElement_1_1(final Namespace namespace, final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list) throws XMLStreamException { parseNamespaces(reader, address, list); String serverName = null; // attributes final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { switch (Namespace.forUri(reader.getAttributeNamespace(i))) { case NONE: { final String value = reader.getAttributeValue(i); final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: { serverName = value; break; } default: throw unexpectedAttribute(reader, i); } break; } case XML_SCHEMA_INSTANCE: { switch (Attribute.forName(reader.getAttributeLocalName(i))) { case SCHEMA_LOCATION: { parseSchemaLocations(reader, address, list, i); break; } case NO_NAMESPACE_SCHEMA_LOCATION: { // todo, jeez break; } default: { throw unexpectedAttribute(reader, i); } } break; } default: throw unexpectedAttribute(reader, i); } } setServerName(address, list, serverName); // elements - sequence Element element = nextElement(reader, namespace); if (element == Element.EXTENSIONS) { extensionXml.parseExtensions(reader, address, namespace, list); element = nextElement(reader, namespace); } // System properties if (element == Element.SYSTEM_PROPERTIES) { parseSystemProperties(reader, address, namespace, list, true); element = nextElement(reader, namespace); } if (element == Element.PATHS) { parsePaths(reader, address, namespace, list, true); element = nextElement(reader, namespace); } if (element == Element.VAULT) { parseVault(reader, address, namespace, list); element = nextElement(reader, namespace); } // Single profile if (element == Element.PROFILE) { parseServerProfile(reader, address, list); element = nextElement(reader, namespace); } // Interfaces final Set<String> interfaceNames = new HashSet<String>(); if (element == Element.INTERFACES) { parseInterfaces(reader, interfaceNames, address, namespace, list, true); element = nextElement(reader, namespace); } // Single socket binding group if (element == Element.SOCKET_BINDING_GROUP) { parseSocketBindingGroup(reader, interfaceNames, address, namespace, list); element = nextElement(reader, namespace); } if (element != null) { throw unexpectedElement(reader); } } private void parseSocketBindingGroup(final XMLExtendedStreamReader reader, final Set<String> interfaces, final ModelNode address, final Namespace expectedNs, final List<ModelNode> updates) throws XMLStreamException { // unique names for both socket-binding and outbound-socket-binding(s) final Set<String> uniqueBindingNames = new HashSet<String>(); ModelNode op = Util.getEmptyOperation(ADD, null); // Handle attributes String socketBindingGroupName = null; final EnumSet<Attribute> required = EnumSet.of(Attribute.NAME, Attribute.DEFAULT_INTERFACE); final int count = reader.getAttributeCount(); for (int i = 0; i < count; i++) { final String value = reader.getAttributeValue(i); if (!isNoNamespaceAttribute(reader, i)) { throw unexpectedAttribute(reader, i); } final Attribute attribute = Attribute.forName(reader.getAttributeLocalName(i)); switch (attribute) { case NAME: { socketBindingGroupName = value; required.remove(attribute); break; } case DEFAULT_INTERFACE: { SocketBindingGroupResourceDefinition.DEFAULT_INTERFACE.parseAndSetParameter(value, op, reader); required.remove(attribute); break; } case PORT_OFFSET: { SocketBindingGroupResourceDefinition.PORT_OFFSET.parseAndSetParameter(value, op, reader); break; } default: throw ParseUtils.unexpectedAttribute(reader, i); } } if (!required.isEmpty()) { throw missingRequired(reader, required); } ModelNode groupAddress = address.clone().add(SOCKET_BINDING_GROUP, socketBindingGroupName); op.get(OP_ADDR).set(groupAddress); updates.add(op); // Handle elements while (reader.nextTag() != END_ELEMENT) { requireNamespace(reader, expectedNs); final Element element = Element.forName(reader.getLocalName()); switch (element) { case SOCKET_BINDING: { // FIXME JBAS-8825 final String bindingName = parseSocketBinding(reader, interfaces, groupAddress, updates); if (!uniqueBindingNames.add(bindingName)) { throw ControllerLogger.ROOT_LOGGER.alreadyDeclared(Element.SOCKET_BINDING.getLocalName(), Element.OUTBOUND_SOCKET_BINDING.getLocalName(), bindingName, Element.SOCKET_BINDING_GROUP.getLocalName(), socketBindingGroupName, reader.getLocation()); } break; } case OUTBOUND_SOCKET_BINDING: { final String bindingName = parseOutboundSocketBinding(reader, interfaces, groupAddress, updates); if (!uniqueBindingNames.add(bindingName)) { throw ControllerLogger.ROOT_LOGGER.alreadyDeclared(Element.SOCKET_BINDING.getLocalName(), Element.OUTBOUND_SOCKET_BINDING.getLocalName(), bindingName, Element.SOCKET_BINDING_GROUP.getLocalName(), socketBindingGroupName, reader.getLocation()); } break; } default: throw unexpectedElement(reader); } } } private void parseServerProfile(final XMLExtendedStreamReader reader, final ModelNode address, final List<ModelNode> list) throws XMLStreamException { // Attributes requireNoAttributes(reader); // Content final Set<String> configuredSubsystemTypes = new HashSet<String>(); while (reader.hasNext() && reader.nextTag() != END_ELEMENT) { if (Element.forName(reader.getLocalName()) != Element.SUBSYSTEM) { throw unexpectedElement(reader); } if (!configuredSubsystemTypes.add(reader.getNamespaceURI())) { throw AppClientLogger.ROOT_LOGGER.duplicateSubsystemDeclaration(reader.getLocation()); } // parse subsystem final List<ModelNode> subsystems = new ArrayList<ModelNode>(); reader.handleAny(subsystems); // Process subsystems for (final ModelNode update : subsystems) { // Process relative subsystem path address final ModelNode subsystemAddress = address.clone(); for (final Property path : update.get(OP_ADDR).asPropertyList()) { subsystemAddress.add(path.getName(), path.getValue().asString()); } update.get(OP_ADDR).set(subsystemAddress); list.add(update); } } } private void setServerName(final ModelNode address, final List<ModelNode> operationList, final String value) { if (value != null && value.length() > 0) { final ModelNode update = Util.getWriteAttributeOperation(address, NAME, value); operationList.add(update); } } public void writeContent(final XMLExtendedStreamWriter writer, final ModelMarshallingContext context) throws XMLStreamException { // we don't marshall appclient.xml } }
package file; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.EnumSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * This class will search all folders and the respective subfolders for files * and return them as a List of File items. */ public class FileWalker{ /** output list for Files or Folders */ private LinkedList<File> resultList = new LinkedList<File>(); /** Directory's to process */ private LinkedList<File> dirToSearch = new LinkedList<File>(); private boolean noSub = false; private boolean folderOnly = false; private boolean imageOnly = false; public void addPath(File file){ File[] f = {file}; addPath(f); } public void addPath(File[] file){ //main add Method for (File f : file){ if(!dirToSearch.contains(f)); dirToSearch.add(f); } } public void addPath(String string) { File[] f = {new File(string)}; // make a 1 element array addPath(f); } public void addPath(String[] dirs){ File[] conv = new File[dirs.length]; int i=0; for (String s : dirs){ //string to File conv[i]=(new File(s)); i++; } addPath(conv); } public void addPath(List<File> dirs){ File[] conv = new File[dirs.size()]; dirs.toArray(conv); addPath(conv); } public void setnoSub(boolean set){ this.noSub = set; } public void setfolderOnly(boolean set){ this.folderOnly = set; } public void setImagesOnly(boolean set){ this.imageOnly = set; } public List<File> fileWalkList(){ LinkedList<File> files = fileWalk(); ArrayList<File> list = new ArrayList<File>(100); Iterator<File> ite = files.iterator(); while(ite.hasNext()){ list.add(ite.next()); } return list; } public List<String> fileWalkStringList(){ LinkedList<File> files = fileWalk(); List<String> list = new ArrayList<String>(100); Iterator<File> ite = files.iterator(); while(ite.hasNext()){ list.add(ite.next().toString()); } return list; } public LinkedList<File> fileWalk(){ for(File f : dirToSearch){ try { if(noSub && folderOnly){ Files.walkFileTree( f.toPath(), EnumSet.noneOf(FileVisitOption.class),2, new FetchFiles()); }else if(noSub && !folderOnly){ Files.walkFileTree( f.toPath(), EnumSet.noneOf(FileVisitOption.class),1, new FetchFiles()); }else{ Files.walkFileTree( f.toPath(), new FetchFiles()); } } catch (IOException e) { e.printStackTrace(); // should not reach this... } } return new LinkedList<File>(resultList); } public void clearAll(){ this.resultList.clear(); this.dirToSearch.clear(); } class FetchFiles extends SimpleFileVisitor<Path>{ @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { if(! folderOnly && attrs.isRegularFile()){ if(imageOnly){ String toTest = path.toString().toLowerCase(); if (toTest.endsWith(".jpg") || toTest.endsWith(".png") || toTest.endsWith(".gif")){ resultList.add(path.toFile()); } }else{ resultList.add(path.toFile()); } } return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if(folderOnly && attrs.isDirectory()){ resultList.add(dir.toFile()); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { System.err.println("unable to access "+file.toString()); return FileVisitResult.CONTINUE; } } }
package filemanager; import javax.swing.*; import java.awt.*; public class GUI{ private JComboBox<String> gcb, gcb2; private JButton helpButton, createFolderButton, copyButton, renameButton, deleteButton, terminalButton, exitButton; private JTable table, table2; private JScrollPane scroll, scroll2; private JLabel labelDisk, labelDisk2, labelMemory, labelMemory2, labelCommandLine; private JTextField commandLine; private GridBagLayout gbl; private GridBagConstraints gbc; private int frameSizeX = 800; private int frameSizeY = 600; private int countButton = 7; public void makeGUI(){ JFrame frame = new JFrame("File Manager"); gbl = new GridBagLayout(); gbc = new GridBagConstraints(); frame.setLayout(gbl); frame.setSize(frameSizeX, frameSizeY); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gbc.weightx = 0.5; gbc.weighty = 0.5; gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 0; gbc.gridy = 0; String disks [] = {"c", "d", "flash"}; gcb = new JComboBox<String> (disks); frame.add(gcb, gbc); gbc.gridx = 1; gbc.gridy = 0; gbc.ipadx = 5; labelDisk = new JLabel ("[work]"); frame.add(labelDisk, gbc); gbc.gridx = 2; gbc.gridy = 0; labelMemory = new JLabel ("100 000 000 250 000 000 "); frame.add(labelMemory, gbc); gbc.gridx = 3; gbc.gridy = 0; gbc.ipadx = 0; gcb2 = new JComboBox<String> (disks); frame.add(gcb2, gbc); gbc.gridx = 4; gbc.gridy = 0; gbc.ipadx = 5; labelDisk2 = new JLabel ("[reserv]"); frame.add(labelDisk2, gbc); gbc.gridx = 5; gbc.gridy = 0; labelMemory2 = new JLabel ("125 545 000 454 545 000 "); frame.add(labelMemory2, gbc); gbc.gridx = 0; gbc.gridy = 1; gbc.ipadx = 380; gbc.ipady = 460; gbc.gridwidth = 3; String[] colHeads = {"Name", "Extension", "Size"}; Object [][] data = { {"My folder", "", "1234"}, {"My folder", "", "12345"}, {"My file", "txt", "146"}, {"My file2", "doc", "1234"}, {"My photo", "jpeg", "454545"}, }; table = new JTable(data, colHeads); scroll = new JScrollPane(table); frame.add(scroll, gbc); gbc.gridx = 3; gbc.gridy = 1; Object [][] data2 = { {"folder", "", "1234"}, {"folder", "", "12345"}, {"file", "txt", "146"}, }; table2 = new JTable(data2, colHeads); scroll2 = new JScrollPane(table2); frame.add(scroll2, gbc); gbc.ipady = 15; gbc.gridx = 0; gbc.gridy = 2; labelCommandLine = new JLabel("C:\\>"); frame.add(labelCommandLine, gbc); commandLine = new JTextField(); gbc.gridx = 1; gbc.gridy = 2; gbc.gridwidth = 8; gbc.ipadx = 724; commandLine = new JTextField(); frame.add(commandLine, gbc); helpButton = new JButton("F1-Help"); createFolderButton = new JButton("F2-New folder"); copyButton = new JButton("F5-Copy"); renameButton = new JButton("F6-Rename"); deleteButton = new JButton("F8-Delete"); terminalButton = new JButton("F9-Terminal"); exitButton = new JButton("F10-Exit"); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(1, countButton)); buttonPanel.add(helpButton); buttonPanel.add(createFolderButton); buttonPanel.add(copyButton); buttonPanel.add(renameButton); buttonPanel.add(deleteButton); buttonPanel.add(terminalButton); buttonPanel.add(exitButton); gbc.gridx = 0; gbc.gridy = 3; gbc.gridwidth = GridBagConstraints.REMAINDER; frame.add(buttonPanel, gbc); frame.setResizable(false); frame.setVisible(true); } public static void main(String[] args) { //test push SwingUtilities.invokeLater(new Runnable(){ public void run(){ GUI fmGUI = new GUI(); fmGUI.makeGUI(); } }); } }
package foam.dao; import foam.core.*; import foam.mlang.order.Comparator; import foam.mlang.predicate.Predicate; import java.util.*; import java.util.concurrent.ConcurrentHashMap; public class MapDAO extends AbstractDAO { protected Map<Object, FObject> data_ = null; protected ClassInfo of_ = null; protected synchronized void data_factory() { if ( data_ == null ) { data_ = (Map<Object, FObject>) new ConcurrentHashMap(); } } protected Map<Object, FObject> getData() { if ( data_ == null ) { data_factory(); } return data_; } public void setData(Map<Object, FObject> data) { data_ = data; } public ClassInfo getOf() { return of_; } public MapDAO setOf(ClassInfo of) { of_ = of; primaryKey_ = (PropertyInfo) of.getAxiomByName("id"); return this; } public FObject put_(X x, FObject obj) { getData().put(getPrimaryKey().get(obj), obj); return obj; } public FObject remove_(X x, FObject obj) { getData().remove(getPrimaryKey().get(obj)); return obj; } public FObject find_(X x, Object o) { return AbstractFObject.maybeClone( getOf().isInstance(o) ? getData().get(getPrimaryKey().get(o)) : getData().get(o) ); } public Sink select_(X x, Sink sink, long skip, long limit, Comparator order, Predicate predicate) { if ( sink == null ) sink = new ListSink(); Sink decorated = decorateSink_(sink, skip, limit, order, predicate); Subscription sub = new Subscription(); for ( FObject obj : getData().values() ) { if ( sub.getDetached() ) break; if ( predicate == null || predicate.f(obj) ) decorated.put(obj, sub); } decorated.eof(); return sink; } public void pipe_(X x, Sink s) { // TODO } }
package gamefiles; public class Poker { }
package tp1.main; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Test; import tp1.utils.TesterEj3; import tp1.utils.Utils; public class TestEj3 { @Test public void testsCatedra() { assertEquals (tp1.main.Main.testCatedraEj3Params("a bcde;b acde;c abde;d abc;e abc"), "2 abdce"); assertEquals (tp1.main.Main.testCatedraEj3Params("a bcd;b ae;c ad;d ac;e b"), "2 abecd"); assertEquals (tp1.main.Main.testCatedraEj3Params("a fb;b gc;d gc;f agh;e hd"), "3 abgcdehf"); assertEquals (tp1.main.Main.testCatedraEj3Params("x yz"), "1 xyz"); } @Test public void test1Element() { assertEquals (tp1.main.Main.testCatedraEj3Params("a"), "0 a"); assertEquals (tp1.main.Main.testCatedraEj3Params("2"), "0 2"); assertNotSame(tp1.main.Main.testCatedraEj3Params("1"), "0 1"); assertNotSame(tp1.main.Main.testCatedraEj3Params("2"), "0 4"); } @Test public void test2Element() { assertEquals (tp1.main.Main.testCatedraEj3Params("a b;b a"), "1 ab"); assertEquals (tp1.main.Main.testCatedraEj3Params("a b"), "1 ab"); } @Test public void testCatedraEj3(){ ArrayList<String> inputs; ArrayList<String> resultados; inputs = Utils.leerInputs("Tp1Ej3.in", 3); resultados = new ArrayList<String>(); for(String input : inputs) { resultados.add(TesterEj3.procesar(input).toString()); } Utils.guardarResultados("Tp1Ej3.out", resultados, 3); } @Test public void worstCase() { for (int i = 0; i < 1000000; i++) { // tp1.main.Main.testCatedraEj3Params("1 2 4 5 7 8 6 4 5 7 8 9 4 5 8 7 4 2 1 4 7 8 5 8 1000",200); } } @Test public void bestCase() { for (int i = 0; i < 1000000; i++) { // tp1.main.Main.testCatedraEj3Params("1 2 4 5 7 8 6 4 5 7 8 9 4 5 8 7 4 2 1 4 7 8 5 8 1000",2000); } } /*@Test public void generateAllbestCase() { String string; double tiempo ; double[] tiempos; for (int i = 1; i < 100; i++) { tiempos = new double[5]; string = generateFriendships(i, 1); for (int j = 0; j < tiempos.length; j++) { tiempo = System.nanoTime(); tp1.main.Main.testCatedraEj3Params(string); tiempo = System.nanoTime() - tiempo; tiempos[j] = tiempo; } System.out.print(obtenerPromedio(tiempos) + ";"); } }*/ @Test public void generateAllworstCase() { String string; double tiempo ; double[] tiempos; for (int i = 14; i < 15; i++) { tiempos = new double[5]; string = generateFriendships(i, i); for (int j = 0; j < tiempos.length; j++) { tiempo = System.nanoTime(); tp1.main.Main.testCatedraEj3Params(string); tiempo = System.nanoTime() - tiempo; tiempos[j] = tiempo; } System.out.print(obtenerPromedio(tiempos) + ";"); } } public String generateFriendships(int elements, int friendships) { String result = ""; for (int i = 0; i < elements; i++) { //Para que empiecen de la "a" sumo 97 result = result + (char)(97 + i) + " "; for (int j = 0; j < friendships; j++) { result = result + (char)(97 + j); } result = result + ";"; } System.out.println(result); return result; } public double obtenerPromedio(double[] tiempos){ Arrays.sort(tiempos); double promedio = 0; for (int i = 2; i < tiempos.length -1; i++) { promedio += tiempos[i]; } return promedio/3; } }
package utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Date; import db.entity.StudentInfo; public class FileHelper { public static void serializeStudentsInfo(ArrayList<StudentInfo> studentsInfo,String tno){ ObjectOutputStream oos = null; File file = null; try { file = new File(Values.save_studentsInfo_path); if ( !file.exists()) file.mkdir(); oos = new ObjectOutputStream( new FileOutputStream(Values.save_studentsInfo_path+tno)); studentsInfoSerializable temp = new studentsInfoSerializable(); temp.setStudentsInfo(studentsInfo); temp.setSize(studentsInfo.size()); oos.writeObject(temp); oos.flush(); oos.close(); } catch (IOException e) { e.printStackTrace(); } } public static ArrayList<StudentInfo> deserializeStudentsInfo(String tno){ ObjectInputStream oin = null; ArrayList<StudentInfo> studentsInfo = null; File file = null; try { file = new File(Values.save_studentsInfo_path); if ( !file.exists()) file.mkdir(); oin = new ObjectInputStream( new FileInputStream(Values.save_studentsInfo_path+tno)); studentsInfoSerializable temp = (studentsInfoSerializable)oin.readObject(); studentsInfo = temp.getStudentsInfo(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return studentsInfo; } public static void serializeStartDate(Date startDate,String tno){ ObjectOutputStream oos = null; File file = null; try { file = new File(Values.save_startDate_path); if ( !file.exists()) file.mkdir(); oos = new ObjectOutputStream( new FileOutputStream(Values.save_startDate_path+tno)); oos.writeObject(startDate); oos.flush(); oos.close(); } catch (IOException e) { e.printStackTrace(); } } public static Date deserializeStartDate(String tno){ ObjectInputStream oin = null; Date startDate = null; File file = null; try { file = new File(Values.save_startDate_path); if ( !file.exists()) file.mkdir(); oin = new ObjectInputStream( new FileInputStream(Values.save_startDate_path+tno)); startDate = (Date)oin.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return startDate; } }
package org.jnosql.diana.arangodb; import com.arangodb.ArangoDB; import com.arangodb.ArangoDBAsync; import org.jnosql.diana.api.Settings; import static java.util.Objects.requireNonNull; import static java.util.Optional.ofNullable; /** * The base to configuration both key-value and document on mongoDB. * To each configuration setted, it will change both builder * {@link ArangoDB.Builder} and {@link ArangoDBAsync.Builder} */ public abstract class ArangoDBConfiguration { protected ArangoDB.Builder builder = new ArangoDB.Builder(); protected ArangoDBAsync.Builder builderAsync = new ArangoDBAsync.Builder(); /** * set the setHost * * @param host the setHost * @deprecated use ArangoDBConfiguration{@link #addHost(String, int)} */ @Deprecated public void setHost(String host) { builder.host(host); builderAsync.host(host); } /** * set the setPort * * @param port the setPort * @deprecated use ArangoDBConfiguration{@link #addHost(String, int)} */ @Deprecated public void setPort(int port) { builder.port(port); builderAsync.port(port); } public void addHost(String host, int port) throws NullPointerException { requireNonNull(host, "host is required"); builder.host(host, port); builderAsync.host(host, port); } /** * set the setTimeout * * @param timeout the setTimeout */ public void setTimeout(int timeout) { builder.timeout(timeout); builderAsync.timeout(timeout); } /** * set the setUser * * @param user the setUser */ public void setUser(String user) { builder.user(user); builderAsync.user(user); } /** * set the setPassword * * @param password the setPassword */ public void setPassword(String password) { builder.password(password); builderAsync.password(password); } /** * set if gonna use ssl * * @param value the ssl */ public void setUseSSL(boolean value) { builder.useSsl(value); builderAsync.useSsl(value); } /** * set the chucksize * * @param chuckSize the cucksize */ public void setChuckSize(int chuckSize) { builder.chunksize(chuckSize); builderAsync.chunksize(chuckSize); } /** * Defines a new builder to sync ArangoDB * * @param builder the new builder * @throws NullPointerException when builder is null */ public void syncBuilder(ArangoDB.Builder builder) throws NullPointerException { requireNonNull(builder, "builder is required"); this.builder = builder; } /** * Defines a new asyncBuilder to ArangoDB * * @param builderAsync the new builderAsync * @throws NullPointerException when builderAsync is null */ public void asyncBuilder(ArangoDBAsync.Builder builderAsync) throws NullPointerException { requireNonNull(builderAsync, "asyncBuilder is required"); this.builderAsync = builderAsync; } protected ArangoDB getArangoDB(Settings settings) { ArangoDB.Builder arangoDB = new ArangoDB.Builder(); ofNullable(settings.get("arangodb-host")).map(Object::toString).ifPresent(arangoDB::host); ofNullable(settings.get("arangodb-user")).map(Object::toString).ifPresent(arangoDB::user); ofNullable(settings.get("arangodb-password")).map(Object::toString).ifPresent(arangoDB::password); ofNullable(settings.get("arangodb-port")).map(Object::toString).map(Integer::valueOf).ifPresent(arangoDB::port); ofNullable(settings.get("arangodb-timeout")).map(Object::toString).map(Integer::valueOf).ifPresent(arangoDB::timeout); ofNullable(settings.get("arangodb-chuckSize")).map(Object::toString).map(Integer::valueOf).ifPresent(arangoDB::port); ofNullable(settings.get("arangodb-userSsl")).map(Object::toString).map(Boolean::valueOf).ifPresent(arangoDB::useSsl); return arangoDB.build(); } protected ArangoDBAsync getArangoDBAsync(Settings settings) { ArangoDBAsync.Builder arangoDB = new ArangoDBAsync.Builder(); ofNullable(settings.get("arangodb-host")).map(Object::toString).ifPresent(arangoDB::host); ofNullable(settings.get("arangodb-user")).map(Object::toString).ifPresent(arangoDB::user); ofNullable(settings.get("arangodb-password")).map(Object::toString).ifPresent(arangoDB::password); ofNullable(settings.get("arangodb-port")).map(Object::toString).map(Integer::valueOf).ifPresent(arangoDB::port); ofNullable(settings.get("arangodb-timeout")).map(Object::toString).map(Integer::valueOf).ifPresent(arangoDB::timeout); ofNullable(settings.get("arangodb-chuckSize")).map(Object::toString).map(Integer::valueOf).ifPresent(arangoDB::port); ofNullable(settings.get("arangodb-userSsl")).map(Object::toString).map(Boolean::valueOf).ifPresent(arangoDB::useSsl); return arangoDB.build(); } }
package org.asciidoctor.jruby.log.internal; import org.asciidoctor.log.LogHandler; import org.asciidoctor.ast.Cursor; import org.asciidoctor.jruby.ast.impl.CursorImpl; import org.asciidoctor.log.LogRecord; import org.asciidoctor.log.Severity; import org.jruby.Ruby; import org.jruby.RubyClass; import org.jruby.RubyHash; import org.jruby.RubyModule; import org.jruby.RubyObject; import org.jruby.anno.JRubyMethod; import org.jruby.runtime.Block; import org.jruby.runtime.Helpers; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.backtrace.BacktraceElement; import org.jruby.runtime.builtin.IRubyObject; import java.util.Objects; import java.util.Optional; public class JavaLogger extends RubyObject { private final LogHandler rootLogHandler; private static final String LOG_PROPERTY_SOURCE_LOCATION = "source_location"; private static final String LOG_PROPERTY_TEXT = "text"; public static void install(final Ruby runtime, final LogHandler logHandler) { final RubyModule asciidoctorModule = runtime.getModule("Asciidoctor"); final RubyModule loggerManager = asciidoctorModule.defineOrGetModuleUnder("LoggerManager"); final RubyClass loggerBaseClass = asciidoctorModule.getClass("Logger"); final RubyClass loggerClass = asciidoctorModule .defineOrGetModuleUnder("LoggerManager") .defineClassUnder("JavaLogger", loggerBaseClass, new ObjectAllocator() { @Override public IRubyObject allocate(Ruby runtime, RubyClass klazz) { return new JavaLogger(runtime, klazz, logHandler); } }); loggerClass.defineAnnotatedMethods(JavaLogger.class); final IRubyObject logger = loggerClass.allocate(); logger.callMethod(runtime.getCurrentContext(), "initialize", runtime.getNil()); loggerManager.callMethod("logger=", logger); } private JavaLogger(final Ruby runtime, final RubyClass metaClass, final LogHandler rootLogHandler) { super(runtime, metaClass); this.rootLogHandler = rootLogHandler; } @JRubyMethod(name = "initialize", required = 1, optional = 2) public IRubyObject initialize(final ThreadContext threadContext, final IRubyObject[] args) { return Helpers.invokeSuper( threadContext, this, getMetaClass(), "initialize", args, Block.NULL_BLOCK); } /** * @param threadContext * @param args */ @JRubyMethod(name = "add", required = 1, optional = 2) public IRubyObject add(final ThreadContext threadContext, final IRubyObject[] args, Block block) { final IRubyObject rubyMessage; if (args.length >= 2 && !args[1].isNil()) { rubyMessage = args[1]; } else if (block.isGiven()) { rubyMessage = block.yield(threadContext, getRuntime().getNil()); } else { rubyMessage = args[2]; } final Cursor cursor = getSourceLocation(rubyMessage); final String message = formatMessage(rubyMessage); final Severity severity = mapRubyLogLevel(args[0]); final LogRecord record = createLogRecord(threadContext, severity, cursor, message); rootLogHandler.log(record); return getRuntime().getNil(); } @JRubyMethod(name = "fatal", required = 1, optional = 1) public IRubyObject fatal(final ThreadContext threadContext, final IRubyObject[] args, Block block) { return log(threadContext, args, block, Severity.FATAL); } @JRubyMethod(name = "fatal?") public IRubyObject fatal(final ThreadContext threadContext) { return getRuntime().getTrue(); } @JRubyMethod(name = "error", required = 1, optional = 1) public IRubyObject error(final ThreadContext threadContext, final IRubyObject[] args, Block block) { return log(threadContext, args, block, Severity.ERROR); } @JRubyMethod(name = "error?") public IRubyObject error(final ThreadContext threadContext) { return getRuntime().getTrue(); } @JRubyMethod(name = "warn", required = 1, optional = 1) public IRubyObject warn(final ThreadContext threadContext, final IRubyObject[] args, Block block) { return log(threadContext, args, block, Severity.WARN); } @JRubyMethod(name = "warn?") public IRubyObject warn(final ThreadContext threadContext) { return getRuntime().getTrue(); } @JRubyMethod(name = "info", required = 1, optional = 1) public IRubyObject info(final ThreadContext threadContext, final IRubyObject[] args, Block block) { return log(threadContext, args, block, Severity.INFO); } @JRubyMethod(name = "info?") public IRubyObject info(final ThreadContext threadContext) { return getRuntime().getTrue(); } @JRubyMethod(name = "debug", required = 1, optional = 1) public IRubyObject debug(final ThreadContext threadContext, final IRubyObject[] args, Block block) { return log(threadContext, args, block, Severity.DEBUG); } @JRubyMethod(name = "debug?") public IRubyObject debug(final ThreadContext threadContext) { return getRuntime().getTrue(); } private IRubyObject log(ThreadContext threadContext, IRubyObject[] args, Block block, Severity severity) { final IRubyObject rubyMessage; if (block.isGiven()) { rubyMessage = block.yield(threadContext, getRuntime().getNil()); } else { rubyMessage = args[0]; } final Cursor cursor = getSourceLocation(rubyMessage); final String message = formatMessage(rubyMessage); final LogRecord record = createLogRecord(threadContext, severity, cursor, message); rootLogHandler.log(record); return getRuntime().getNil(); } private LogRecord createLogRecord(final ThreadContext threadContext, final Severity severity, final Cursor cursor, final String message) { final Optional<BacktraceElement> elem = threadContext.getBacktrace(0) .skip(1) .findFirst(); final String sourceFileName = elem.map(BacktraceElement::getFilename).orElse(null); final String sourceMethodName = elem.map(BacktraceElement::getMethod).orElse(null); final LogRecord record = new LogRecord(severity, cursor, message, sourceFileName, sourceMethodName); return record; } private Severity mapRubyLogLevel(IRubyObject arg) { final int rubyId = arg.convertToInteger().getIntValue(); switch (rubyId) { case 0: return Severity.DEBUG; case 1: return Severity.INFO; case 2: return Severity.WARN; case 3: return Severity.ERROR; case 4: return Severity.FATAL; default: return Severity.UNKNOWN; } } private String formatMessage(final IRubyObject msg) { if (getRuntime().getString().equals(msg.getType())) { return msg.asJavaString(); } else if (getRuntime().getHash().equals(msg.getType())) { final RubyHash hash = (RubyHash) msg; return Objects.toString(hash.get(getRuntime().newSymbol(LOG_PROPERTY_TEXT))); } throw new IllegalArgumentException(Objects.toString(msg)); } private Cursor getSourceLocation(IRubyObject msg) { if (getRuntime().getHash().equals(msg.getType())) { final RubyHash hash = (RubyHash) msg; final Object sourceLocation = hash.get(getRuntime().newSymbol(LOG_PROPERTY_SOURCE_LOCATION)); return new CursorImpl((IRubyObject) sourceLocation); } return null; } }
package views; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.Dictionary; import java.util.Hashtable; import java.util.List; import java.util.Observable; import java.util.Observer; import javax.swing.AbstractAction; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultCellEditor; import javax.swing.ImageIcon; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableRowSorter; import viewModels.CopyTableModel; import domain.Book; import domain.BookList; import domain.Copy; import domain.CopyList; import domain.Library; import domain.Loan; import domain.Copy.Condition; import domain.Shelf; public class BookDetail extends javax.swing.JFrame implements Observer { private static final long serialVersionUID = 1L; private JTextField txtTitle; private JTextField txtAuthor; private JTextField txtPublisher; private JPanel pnlInformation; private JLabel lblTitle; private JLabel lblAuthor; private JLabel lblPublisher; private JLabel lblShelf; private JComboBox<Shelf> cmbShelf; private JPanel pnlCopiesEdit; private JPanel pnlAction; private JLabel lblAmount; private JButton btnRemove; private JButton btnAdd; private JPanel pnlCopies; private Book book; private Library library; private BookList books; private JTable tblCopies; private JScrollPane scrollPane; // Models private CopyTableModel copyTableModel; private TableRowSorter<CopyTableModel> sorter; private CopyList copies; private static Dictionary<Book, BookDetail> editFramesDict = new Hashtable<Book, BookDetail>(); private JPanel pnlButtons; private JPanel pnlBookButtons; // Buttons private JButton btnSave; private JButton btnCancel; private JButton btnReset; private JButton btnDelete; private Component horizontalGlue; private static Boolean newlyCreated; private static BookDetail editFrame; /** * Create the application. */ public BookDetail(Library library, Book book) { super(); setBounds(new Rectangle(59, 24, 500, 500)); this.library = library; this.books = library.getBookList(); this.book = book; this.copies = new CopyList(); this.copies.setCopyList( library.getCopiesOfBook( book ) ); this.copyTableModel = new CopyTableModel( this.copies, library ); initialize(); } public static void editBook(Library library, Book book) { newlyCreated = false; if ( book == null ) { book = new Book(""); newlyCreated = true; } editFrame = editFramesDict.get(book); if (editFrame == null) { editFrame = new BookDetail(library, book); editFramesDict.put(book, editFrame); } editFrame.setVisible(true); } private void displayBook() { if (book == null) { txtTitle.setEnabled(false); txtPublisher.setEnabled(false); txtAuthor.setEnabled(false); cmbShelf.setEnabled(false); } else { setBookValuesToView(); } setTitle( Messages.getString("BookDetail.this.title", book.getName() ) ); } /** * Initialize the contents of the frame. */ private void initialize() { try { setMinimumSize( new Dimension(500, 444) ); setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); getContentPane().setLayout( new BoxLayout( this.getContentPane(), BoxLayout.Y_AXIS ) ); // ACTIONS // Close (via Esc-Key (?), Button) AbstractAction cancel = new CloseAction( Messages.getString( "MainView.btnExit.text"), "Revert Changes, close dialog" ); // Save (via S, Button) AbstractAction save = new SaveAction( Messages.getString( "BookDetail.btnSave.text"), "Save changes" ); // Reset (via R, Button) AbstractAction reset = new ResetAction(Messages.getString( "BookDetail.btnReset.text"), "Revert changes" ); // Remove Book (via D, Button) AbstractAction delete = new DeleteAction( Messages.getString("BookDetail.btnRemove.text"), "Remove this book" ); // Add Copy (via A, Button) AbstractAction addCopy = new AddCopyAction( Messages.getString("BookDetail.btnAdd.text"), "Add a copy of this book" ); // Remove Selected Copies (via Button) AbstractAction removeCopy = new RemoveCopyAction( Messages.getString("BookDetail.btnRemoveCopy.text"), "Remove selected copies" ); // INFORMATION PANEL pnlInformation = new JPanel(); pnlInformation .setBorder(new TitledBorder( new LineBorder(new Color(0, 0, 0)), Messages.getString("BookDetail.pnlInformation.borderTitle"), TitledBorder.LEADING, TitledBorder.TOP, null, null)); getContentPane().add(pnlInformation); GridBagLayout gbl_pnlInformation = new GridBagLayout(); gbl_pnlInformation.columnWidths = new int[] { 0, 0, 0, 0, 0 }; gbl_pnlInformation.rowHeights = new int[] { 0, 0, 0, 0, 0, 0 }; gbl_pnlInformation.columnWeights = new double[] { 0.0, 0.0, 1.0, 0.0, Double.MIN_VALUE }; gbl_pnlInformation.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE }; pnlInformation.setLayout(gbl_pnlInformation); lblTitle = new JLabel( Messages.getString("BookDetail.lblTitle.text") ); GridBagConstraints gbc_lblTitle = new GridBagConstraints(); gbc_lblTitle.anchor = GridBagConstraints.EAST; gbc_lblTitle.insets = new Insets(0, 0, 5, 5); gbc_lblTitle.gridx = 1; gbc_lblTitle.gridy = 0; pnlInformation.add(lblTitle, gbc_lblTitle); txtTitle = new JTextField(); txtTitle.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { validateInformation(); handleFieldError(txtTitle); } }); GridBagConstraints gbc_txtTitle = new GridBagConstraints(); gbc_txtTitle.insets = new Insets(0, 0, 5, 5); gbc_txtTitle.fill = GridBagConstraints.HORIZONTAL; gbc_txtTitle.gridx = 2; gbc_txtTitle.gridy = 0; pnlInformation.add(txtTitle, gbc_txtTitle); txtTitle.setColumns(10); lblAuthor = new JLabel( Messages.getString("BookDetail.lblAuthor.text") ); GridBagConstraints gbc_lblAuthor = new GridBagConstraints(); gbc_lblAuthor.insets = new Insets(0, 0, 5, 5); gbc_lblAuthor.anchor = GridBagConstraints.EAST; gbc_lblAuthor.gridx = 1; gbc_lblAuthor.gridy = 1; pnlInformation.add( lblAuthor, gbc_lblAuthor ); txtAuthor = new JTextField(); GridBagConstraints gbc_txtAuthor = new GridBagConstraints(); gbc_txtAuthor.insets = new Insets(0, 0, 5, 5); gbc_txtAuthor.fill = GridBagConstraints.HORIZONTAL; gbc_txtAuthor.gridx = 2; gbc_txtAuthor.gridy = 1; pnlInformation.add(txtAuthor, gbc_txtAuthor); txtAuthor.setColumns(10); txtAuthor.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { validateInformation(); handleFieldError(txtAuthor); } }); lblPublisher = new JLabel( Messages.getString("BookDetail.lblPublisher.text") ); GridBagConstraints gbc_lblPublisher = new GridBagConstraints(); gbc_lblPublisher.insets = new Insets(0, 0, 5, 5); gbc_lblPublisher.anchor = GridBagConstraints.EAST; gbc_lblPublisher.gridx = 1; gbc_lblPublisher.gridy = 2; pnlInformation.add(lblPublisher, gbc_lblPublisher); txtPublisher = new JTextField(); GridBagConstraints gbc_txtPublisher = new GridBagConstraints(); gbc_txtPublisher.insets = new Insets(0, 0, 5, 5); gbc_txtPublisher.fill = GridBagConstraints.HORIZONTAL; gbc_txtPublisher.gridx = 2; gbc_txtPublisher.gridy = 2; pnlInformation.add(txtPublisher, gbc_txtPublisher); txtPublisher.setColumns(10); txtPublisher.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { validateInformation(); handleFieldError(txtPublisher); } }); lblShelf = new JLabel( Messages.getString("BookDetail.lblShelf.text") ); GridBagConstraints gbc_lblShelf = new GridBagConstraints(); gbc_lblShelf.insets = new Insets(0, 0, 5, 5); gbc_lblShelf.anchor = GridBagConstraints.EAST; gbc_lblShelf.gridx = 1; gbc_lblShelf.gridy = 3; pnlInformation.add(lblShelf, gbc_lblShelf); cmbShelf = new JComboBox<Shelf>(); for (Shelf shelf : Shelf.values()) { cmbShelf.addItem(shelf); } cmbShelf.addActionListener(new ShelfAction()); GridBagConstraints gbc_cmbShelf = new GridBagConstraints(); gbc_cmbShelf.insets = new Insets(0, 0, 5, 5); gbc_cmbShelf.fill = GridBagConstraints.HORIZONTAL; gbc_cmbShelf.gridx = 2; gbc_cmbShelf.gridy = 3; pnlInformation.add(cmbShelf, gbc_cmbShelf); pnlBookButtons = new JPanel(); GridBagConstraints gbc_panel = new GridBagConstraints(); gbc_panel.insets = new Insets(0, 0, 0, 5); gbc_panel.fill = GridBagConstraints.BOTH; gbc_panel.gridx = 2; gbc_panel.gridy = 4; pnlInformation.add( pnlBookButtons, gbc_panel ); pnlBookButtons.setLayout( new BoxLayout( pnlBookButtons, BoxLayout.X_AXIS ) ); horizontalGlue = Box.createHorizontalGlue(); pnlBookButtons.add( horizontalGlue ); // BOOK-BUTTONS // DELETE btnDelete = new JButton( delete ); btnDelete.setEnabled( !newlyCreated ); pnlBookButtons.add( btnDelete ); // RESET btnReset = new JButton( reset ); btnReset.setEnabled( false ); pnlBookButtons.add( btnReset ); // SAVE btnSave = new JButton( save ); btnSave.setEnabled( false ); pnlBookButtons.add( btnSave ); // COPY AREA pnlCopiesEdit = new JPanel(); pnlCopiesEdit.setBorder(new TitledBorder( new LineBorder(new Color(0, 0, 0)), Messages.getString("BookDetail.pnlSpecimensEdit.borderTitle"), TitledBorder.LEADING, TitledBorder.TOP, null, null)); getContentPane().add(pnlCopiesEdit); pnlCopiesEdit.setLayout(new BoxLayout(pnlCopiesEdit, BoxLayout.Y_AXIS)); pnlAction = new JPanel(); pnlCopiesEdit.add(pnlAction); pnlAction.setLayout(new BoxLayout(pnlAction, BoxLayout.X_AXIS)); lblAmount = new JLabel( Messages.getString("BookDetail.lblAmount.text") ); pnlAction.add(lblAmount); Component hglCopiesEdit = Box.createHorizontalGlue(); pnlAction.add(hglCopiesEdit); // COPY-BUTTONS // DELETE btnRemove = new JButton( removeCopy ); btnRemove.setEnabled(false); pnlAction.add(btnRemove); Component horizontalStrut = Box.createHorizontalStrut(5); pnlAction.add(horizontalStrut); // ADD btnAdd = new JButton( addCopy ); pnlAction.add(btnAdd); // COPIES PANEL pnlCopies = new JPanel(); GridBagConstraints gbc_pnlCopies = new GridBagConstraints(); gbc_pnlCopies.insets = new Insets(0, 0, 5, 0); gbc_pnlCopies.fill = GridBagConstraints.BOTH; gbc_pnlCopies.gridx = 0; gbc_pnlCopies.gridy = 1; pnlCopies.setLayout(new BoxLayout( pnlCopies, BoxLayout.Y_AXIS)); pnlCopiesEdit.add( pnlCopies, gbc_pnlCopies); scrollPane = new JScrollPane(); { tblCopies = new JTable(); initTable(); } scrollPane.setViewportView(tblCopies); pnlCopies.add(scrollPane); // BUTTONS PANEL pnlButtons = new JPanel(); pnlButtons.setMaximumSize(new Dimension(32767, 50)); getContentPane().add(pnlButtons); pnlButtons.setLayout(new BoxLayout(pnlButtons, BoxLayout.X_AXIS)); pnlButtons.add(Box.createHorizontalGlue()); // CANCEL btnCancel = new JButton( cancel ); btnCancel.setEnabled( true ); btnCancel.setIcon( new ImageIcon("icons/close_32.png") ); pnlButtons.add( btnCancel ); displayBook(); updateLabels(); updateListButtons(); // Add Escape-Action ( close dialog ) KeyStroke stroke = KeyStroke.getKeyStroke("ESCAPE"); InputMap inputMap = rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(stroke, "ESCAPE"); rootPane.getActionMap().put("ESCAPE", cancel); pack(); } catch (Exception e) { e.printStackTrace(); } } private void initTable() { tblCopies.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); tblCopies.setModel( copyTableModel ); sorter = new TableRowSorter<CopyTableModel>( copyTableModel ); tblCopies.setRowSorter( sorter ); // Ignore the title and author in this view, because all copies from this book have the same properties in those fields. tblCopies.getColumnModel().removeColumn( tblCopies.getColumnModel().getColumn(1) ); tblCopies.getColumnModel().removeColumn( tblCopies.getColumnModel().getColumn(1) ); tblCopies.getColumnModel().getColumn( 1 ).setCellRenderer(new LoanTableCellRenderer(library) { private static final long serialVersionUID = 1L; @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); // Get value from TableModel boolean isLent = (boolean) value; if ( isLent ) { label.setText( Messages.getString("LoanTable.CellContent.Lent") ); label.setIcon( new ImageIcon("icons/warning_16.png") ); } else { label.setText( Messages.getString("LoanTable.CellContent.Available") ); label.setIcon( null ); } // Bug: every 10th copy or so gets a red text. Overrule! label.setForeground( Color.BLACK ); return label; } }); tblCopies.getColumnModel().getColumn( 2 ).setCellEditor(new DefaultCellEditor(new JComboBox<>(Condition.values()))); // TODO: make cell editable (already prepared in CopyTableModel!), but TODO: save changes! // Add Listeners tblCopies.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent evt) { SwingUtilities.invokeLater(new Runnable() { public void run() { // Update the "Show Selected" button updateListButtons(); } }); } } ); } private void handleFieldError(JTextField field) { if("".equals(field.getText())){ field.setBackground(Color.PINK); }else { field.setBackground(Color.WHITE); } } private void validateInformation(){ boolean hasValidationError = "".equals(txtAuthor.getText()) || "".equals(txtPublisher.getText()) || "".equals(txtTitle.getText()); if(hasValidationError){ btnSave.setEnabled(false); }else { btnSave.setEnabled(true); } // in any way, enable the reset button btnReset.setEnabled( true ); } private void setBookValuesToView() { txtAuthor.setText(book.getAuthor()); txtPublisher.setText(book.getPublisher()); txtTitle.setText(book.getName()); cmbShelf.setSelectedItem(book.getShelf()); btnSave.setEnabled(false); } public void updateLabels() { lblAmount.setText( Messages.getString("BookDetail.lblAmount.text", String.valueOf( library.getCopiesOfBook( book ).size() ) ) ); } public void updateListButtons() { // Enables or disables the buttons // Here we check if this copy is lent. If so, we disable the removeCopyButton, if not, we enable it. if ( tblCopies.getSelectedRowCount() > 0 ) { Copy copy = copies.getCopyAt( tblCopies.convertRowIndexToModel( tblCopies.getSelectedRow() ) ); List<Loan> lentCopiesOfBook = library.getLentCopiesOfBook(book); boolean copyIsLent = false; for(Loan loan : lentCopiesOfBook){ if(copy.equals(loan.getCopy())){ copyIsLent = true; break; } } btnRemove.setEnabled( !copyIsLent ); } else { btnRemove.setEnabled( false ); } btnDelete.setEnabled( library.getLentCopiesOfBook( book ).size() == 0 ); } @Override public void update(Observable o, Object arg) { displayBook(); updateLabels(); updateListButtons(); } // Action Subclasses /** * Change Shelf Action. * @author PFOR */ class ShelfAction extends AbstractAction { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { validateInformation(); } } /** * Closes the current dialog. * @author PCHR */ class CloseAction extends AbstractAction { private static final long serialVersionUID = 1L; public CloseAction( String text, String desc ) { super( text ); putValue( SHORT_DESCRIPTION, desc ); putValue( MNEMONIC_KEY, KeyEvent.VK_C ); } public void actionPerformed(ActionEvent e) { dispose(); } } /** * Saves the (changed) entries for the currently opened book. * @author PFORSTER, PCHR */ class SaveAction extends AbstractAction { private static final long serialVersionUID = 1L; public SaveAction( String text, String desc ) { super( text ); putValue( SHORT_DESCRIPTION, desc ); putValue( MNEMONIC_KEY, KeyEvent.VK_S ); } public void actionPerformed(ActionEvent e) { book.setAuthor(txtAuthor.getText()); book.setName(txtTitle.getText()); book.setPublisher(txtPublisher.getText()); book.setShelf((Shelf) cmbShelf.getSelectedItem()); btnSave.setEnabled(false); if ( newlyCreated ) { // Saving a book that we just created. // we can only add it now, because before it shouldn't // belong to the library, only on saving. books.addBook(book); if ( library.getCopiesOfBook( book ).size() == 0 ) { library.createAndAddCopy( book ); } updateLabels(); } copies.setCopyList(library.getCopiesOfBook(book)); } } /** * Reset the form * @author PFORSTER, PCHR */ class ResetAction extends AbstractAction { private static final long serialVersionUID = 1L; public ResetAction( String text, String desc ) { super( text ); putValue( SHORT_DESCRIPTION, desc ); putValue( MNEMONIC_KEY, KeyEvent.VK_R ); } public void actionPerformed(ActionEvent e) { setBookValuesToView(); btnReset.setEnabled( false ); btnSave.setEnabled( false ); } } // Copy: /** * Add a copy to the currently opened book * @author PFORSTER, PCHR */ class AddCopyAction extends AbstractAction { private static final long serialVersionUID = 1L; public AddCopyAction( String text, String desc ) { super( text ); putValue( SHORT_DESCRIPTION, desc ); putValue( MNEMONIC_KEY, KeyEvent.VK_A ); } public void actionPerformed(ActionEvent e) { library.createAndAddCopy(book); copies.setCopyList( library.getCopiesOfBook( book ) ); updateLabels(); } } /** * Remove the currently selected copies from the currently opened book. * @author PFORSTER, PCHR */ class RemoveCopyAction extends AbstractAction { private static final long serialVersionUID = 1L; public RemoveCopyAction( String text, String desc ) { super( text ); putValue( SHORT_DESCRIPTION, desc ); //putValue( MNEMONIC_KEY, KeyEvent.VK_R ); } public void actionPerformed(ActionEvent e) { Copy copy = copies.getCopyAt( tblCopies.convertRowIndexToModel( tblCopies.getSelectedRow() ) ); List<Loan> lentCopiesOfBook = library.getLentCopiesOfBook(book); boolean copyIsLent = false; for(Loan loan : lentCopiesOfBook){ if(copy.equals(loan.getCopy())){ copyIsLent = true; } } if(copyIsLent){ JOptionPane.showMessageDialog( editFrame, "Dieses Exemplar ist zur Zeit ausgeliehen und kann nicht gelöscht werden.", Messages.getString("Exemplar ausgeliehen"), JOptionPane.YES_NO_OPTION ); }else { library.removeCopy(copy); copies.setCopyList( library.getCopiesOfBook( book ) ); } updateLabels(); } } /** * Delete the currently opened book, if there are no currently lent copies. * @author PCHR */ class DeleteAction extends AbstractAction { private static final long serialVersionUID = 1L; public DeleteAction( String text, String desc ) { super( text ); putValue( SHORT_DESCRIPTION, desc ); putValue( MNEMONIC_KEY, KeyEvent.VK_D ); } public void actionPerformed(ActionEvent e) { boolean canDelete = false; canDelete = library.getLentCopiesOfBook(book).size() == 0; if ( canDelete ) { int delete = JOptionPane.showConfirmDialog( editFrame, Messages.getString("BookDetail.deleteDlg.message"), Messages.getString("BookDetail.deleteDlg.title"), JOptionPane.YES_NO_OPTION ); if ( delete == 0 ) { if ( books.removeBook( book ) ) { // SUCCESS dispose(); } else { try { throw new Exception( "Yeah, deleting that book didn't really work. Sorry about that, please restart the application." ); } catch (Exception e1) { e1.printStackTrace(); } } } } } } }
package com.netflix.astyanax.model; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.util.AbstractList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.apache.cassandra.utils.ByteBufferUtil; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableClassToInstanceMap; import com.netflix.astyanax.Serializer; import com.netflix.astyanax.serializers.AsciiSerializer; import com.netflix.astyanax.serializers.BigIntegerSerializer; import com.netflix.astyanax.serializers.BooleanSerializer; import com.netflix.astyanax.serializers.ByteBufferOutputStream; import com.netflix.astyanax.serializers.ByteBufferSerializer; import com.netflix.astyanax.serializers.ComparatorType; import com.netflix.astyanax.serializers.IntegerSerializer; import com.netflix.astyanax.serializers.LongSerializer; import com.netflix.astyanax.serializers.SerializerTypeInferer; import com.netflix.astyanax.serializers.StringSerializer; import com.netflix.astyanax.serializers.UUIDSerializer; /** * Parent class of Composite and DynamicComposite. Acts as a list of objects * that get serialized into a composite column name. Unless * setAutoDeserialize(true) is called, it's going to try to match serializers to * Cassandra comparator types. * * @author edanuff */ @SuppressWarnings("rawtypes") public abstract class AbstractComposite extends AbstractList<Object> implements Comparable<AbstractComposite> { public enum ComponentEquality { LESS_THAN_EQUAL((byte) -1), EQUAL((byte) 0), GREATER_THAN_EQUAL((byte) 1); private final byte equality; ComponentEquality(byte equality) { this.equality = equality; } public byte toByte() { return equality; } public static ComponentEquality fromByte(byte equality) { if (equality > 0) { return GREATER_THAN_EQUAL; } if (equality < 0) { return LESS_THAN_EQUAL; } return EQUAL; } } static final Logger logger = Logger.getLogger(AbstractComposite.class.getName()); public static final BiMap<Class<? extends Serializer>, String> DEFAULT_SERIALIZER_TO_COMPARATOR_MAPPING = new ImmutableBiMap.Builder<Class<? extends Serializer>, String>() .put(IntegerSerializer.class, IntegerSerializer.get().getComparatorType().getTypeName()) .put(BooleanSerializer.class, BooleanSerializer.get().getComparatorType().getTypeName()) .put(AsciiSerializer.class, AsciiSerializer.get().getComparatorType().getTypeName()) .put(BigIntegerSerializer.class, BigIntegerSerializer.get().getComparatorType().getTypeName()) .put(ByteBufferSerializer.class, ByteBufferSerializer.get().getComparatorType().getTypeName()) .put(LongSerializer.class, LongSerializer.get().getComparatorType().getTypeName()) .put(StringSerializer.class, StringSerializer.get().getComparatorType().getTypeName()) .put(UUIDSerializer.class, UUIDSerializer.get().getComparatorType().getTypeName()).build(); static final ImmutableClassToInstanceMap<Serializer> SERIALIZERS = new ImmutableClassToInstanceMap.Builder<Serializer>() .put(IntegerSerializer.class, IntegerSerializer.get()) .put(BooleanSerializer.class, BooleanSerializer.get()) .put(AsciiSerializer.class, AsciiSerializer.get()) .put(BigIntegerSerializer.class, BigIntegerSerializer.get()) .put(ByteBufferSerializer.class, ByteBufferSerializer.get()) .put(LongSerializer.class, LongSerializer.get()) .put(StringSerializer.class, StringSerializer.get()) .put(UUIDSerializer.class, UUIDSerializer.get()).build(); public static final BiMap<Byte, String> DEFAULT_ALIAS_TO_COMPARATOR_MAPPING = new ImmutableBiMap.Builder<Byte, String>() .put((byte) 'a', ComparatorType.ASCIITYPE.getTypeName()) .put((byte) 'b', ComparatorType.BYTESTYPE.getTypeName()) .put((byte) 'i', ComparatorType.INTEGERTYPE.getTypeName()) .put((byte) 'x', ComparatorType.LEXICALUUIDTYPE.getTypeName()) .put((byte) 'l', ComparatorType.LONGTYPE.getTypeName()) .put((byte) 't', ComparatorType.TIMEUUIDTYPE.getTypeName()) .put((byte) 's', ComparatorType.UTF8TYPE.getTypeName()) .put((byte) 'u', ComparatorType.UUIDTYPE.getTypeName()).build(); BiMap<Class<? extends Serializer>, String> serializerToComparatorMapping = DEFAULT_SERIALIZER_TO_COMPARATOR_MAPPING; BiMap<Byte, String> aliasToComparatorMapping = DEFAULT_ALIAS_TO_COMPARATOR_MAPPING; final boolean dynamic; List<Serializer<?>> serializersByPosition = null; List<String> comparatorsByPosition = null; public class Component<T> { final Serializer<T> serializer; final T value; final ByteBuffer bytes; final String comparator; final ComponentEquality equality; public Component(T value, ByteBuffer bytes, Serializer<T> serializer, String comparator, ComponentEquality equality) { this.serializer = serializer; this.value = value; this.bytes = bytes; this.comparator = comparator; this.equality = equality; } public Serializer<T> getSerializer() { return serializer; } @SuppressWarnings("unchecked") public <A> A getValue(Serializer<A> s) { if (s == null) { s = (Serializer<A>) serializer; } if ((value == null) && (bytes != null) && (s != null)) { ByteBuffer cb = bytes.duplicate(); if (cb.hasRemaining()) { return s.fromByteBuffer(cb); } } if (value instanceof ByteBuffer) { return (A) ((ByteBuffer) value).duplicate(); } return (A) value; } public T getValue() { return getValue(serializer); } @SuppressWarnings("unchecked") public <A> ByteBuffer getBytes(Serializer<A> s) { if (bytes == null) { if (value instanceof ByteBuffer) { return ((ByteBuffer) value).duplicate(); } if (value == null) { return null; } if (s == null) { s = (Serializer<A>) serializer; } if (s != null) { return s.toByteBuffer((A) value).duplicate(); } } return bytes.duplicate(); } public ByteBuffer getBytes() { return getBytes(serializer); } public String getComparator() { return comparator; } public ComponentEquality getEquality() { return equality; } @Override public String toString() { return "Component [" + getValue() + "]"; } } List<Component<?>> components = new ArrayList<Component<?>>(); ByteBuffer serialized = null; public AbstractComposite(boolean dynamic) { this.dynamic = dynamic; } public AbstractComposite(boolean dynamic, Object... o) { this.dynamic = dynamic; this.addAll(Arrays.asList(o)); } public AbstractComposite(boolean dynamic, List<?> l) { this.dynamic = dynamic; this.addAll(l); } public List<Component<?>> getComponents() { return components; } public void setComponents(List<Component<?>> components) { serialized = null; this.components = components; } public Map<Class<? extends Serializer>, String> getSerializerToComparatorMapping() { return serializerToComparatorMapping; } public void setSerializerToComparatorMapping(Map<Class<? extends Serializer>, String> serializerToComparatorMapping) { serialized = null; this.serializerToComparatorMapping = new ImmutableBiMap.Builder<Class<? extends Serializer>, String>().putAll( serializerToComparatorMapping).build(); } public Map<Byte, String> getAliasesToComparatorMapping() { return aliasToComparatorMapping; } public void setAliasesToComparatorMapping(Map<Byte, String> aliasesToComparatorMapping) { serialized = null; aliasToComparatorMapping = new ImmutableBiMap.Builder<Byte, String>().putAll(aliasesToComparatorMapping) .build(); } public boolean isDynamic() { return dynamic; } public List<Serializer<?>> getSerializersByPosition() { return serializersByPosition; } public void setSerializersByPosition(List<Serializer<?>> serializersByPosition) { this.serializersByPosition = serializersByPosition; } public void setSerializersByPosition(Serializer<?>... serializers) { serializersByPosition = Arrays.asList(serializers); } public void setSerializerByPosition(int index, Serializer<?> s) { if (serializersByPosition == null) { serializersByPosition = new ArrayList<Serializer<?>>(); } while (serializersByPosition.size() <= index) { serializersByPosition.add(null); } serializersByPosition.set(index, s); } public List<String> getComparatorsByPosition() { return comparatorsByPosition; } public void setComparatorsByPosition(List<String> comparatorsByPosition) { this.comparatorsByPosition = comparatorsByPosition; } public void setComparatorsByPosition(String... comparators) { comparatorsByPosition = Arrays.asList(comparators); } public void setComparatorByPosition(int index, String c) { if (comparatorsByPosition == null) { comparatorsByPosition = new ArrayList<String>(); } while (comparatorsByPosition.size() <= index) { comparatorsByPosition.add(null); } comparatorsByPosition.set(index, c); } @Override public int compareTo(AbstractComposite o) { return serialize().compareTo(o.serialize()); } private String comparatorForSerializer(Serializer<?> s) { String comparator = serializerToComparatorMapping.get(s.getClass()); if (comparator != null) { return comparator; } return ComparatorType.BYTESTYPE.getTypeName(); } private Serializer<?> serializerForComparator(String c) { int p = c.indexOf('('); if (p >= 0) { c = c.substring(0, p); } if (ComparatorType.LEXICALUUIDTYPE.getTypeName().equals(c) || ComparatorType.TIMEUUIDTYPE.getTypeName().equals(c)) { return UUIDSerializer.get(); } Serializer<?> s = SERIALIZERS.getInstance(serializerToComparatorMapping.inverse().get(c)); if (s != null) { return s; } return ByteBufferSerializer.get(); } private Serializer<?> serializerForPosition(int i) { if (serializersByPosition == null) { return null; } if (i >= serializersByPosition.size()) { return null; } return serializersByPosition.get(i); } private Serializer<?> getSerializer(int i, String c) { Serializer<?> s = serializerForPosition(i); if (s != null) { return s; } return serializerForComparator(c); } private String comparatorForPosition(int i) { if (comparatorsByPosition == null) { return null; } if (i >= comparatorsByPosition.size()) { return null; } return comparatorsByPosition.get(i); } private String getComparator(int i, ByteBuffer bb) { String name = comparatorForPosition(i); if (name != null) { return name; } if (!dynamic) { if (bb.hasRemaining()) { return ComparatorType.BYTESTYPE.getTypeName(); } else { return null; } } if (bb.hasRemaining()) { try { int header = getShortLength(bb); if ((header & 0x8000) == 0) { name = ByteBufferUtil.string(getBytes(bb, header)); } else { byte a = (byte) (header & 0xFF); name = aliasToComparatorMapping.get(a); if (name == null) { a = (byte) Character.toLowerCase((char) a); name = aliasToComparatorMapping.get(a); if (name != null) { name += "(reversed=true)"; } } } } catch (CharacterCodingException e) { throw new RuntimeException(e); } } if ((name != null) && (name.length() == 0)) { name = null; } return name; } @Override public void clear() { serialized = null; components = new ArrayList<Component<?>>(); } @Override public int size() { return components.size(); } public <T> AbstractComposite addComponent(T value, Serializer<T> s) { addComponent(value, s, comparatorForSerializer(s)); return this; } public <T> AbstractComposite addComponent(T value, Serializer<T> s, ComponentEquality equality) { addComponent(value, s, comparatorForSerializer(s), equality); return this; } public <T> AbstractComposite addComponent(T value, Serializer<T> s, String comparator) { addComponent(value, s, comparator, ComponentEquality.EQUAL); return this; } public <T> AbstractComposite addComponent(T value, Serializer<T> s, String comparator, ComponentEquality equality) { addComponent(-1, value, s, comparator, equality); return this; } @SuppressWarnings("unchecked") public <T> AbstractComposite addComponent(int index, T value, Serializer<T> s, String comparator, ComponentEquality equality) { serialized = null; if (index < 0) { index = components.size(); } while (components.size() < index) { components.add(null); } components.add(index, new Component(value, null, s, comparator, equality)); return this; } private static Object mapIfNumber(Object o) { if ((o instanceof Byte) || (o instanceof Integer) || (o instanceof Short)) { return BigInteger.valueOf(((Number) o).longValue()); } return o; } @SuppressWarnings({ "unchecked" }) private static Collection<?> flatten(Collection<?> c) { if (c instanceof AbstractComposite) { return ((AbstractComposite) c).getComponents(); } boolean hasCollection = false; for (Object o : c) { if (o instanceof Collection) { hasCollection = true; break; } } if (!hasCollection) { return c; } List newList = new ArrayList(); for (Object o : c) { if (o instanceof Collection) { newList.addAll(flatten((Collection) o)); } else { newList.add(o); } } return newList; } @Override public boolean addAll(Collection<? extends Object> c) { return super.addAll(flatten(c)); } @Override public boolean containsAll(Collection<?> c) { return super.containsAll(flatten(c)); } @Override public boolean removeAll(Collection<?> c) { return super.removeAll(flatten(c)); } @Override public boolean retainAll(Collection<?> c) { return super.retainAll(flatten(c)); } @Override public boolean addAll(int i, Collection<? extends Object> c) { return super.addAll(i, flatten(c)); } @SuppressWarnings("unchecked") @Override public void add(int index, Object element) { serialized = null; if (element instanceof Component) { components.add(index, (Component<?>) element); return; } element = mapIfNumber(element); Serializer s = serializerForPosition(index); if (s == null) { s = SerializerTypeInferer.getSerializer(element); } String c = comparatorForPosition(index); if (c == null) { c = comparatorForSerializer(s); } components.add(index, new Component(element, null, s, c, ComponentEquality.EQUAL)); } @Override public Object remove(int index) { serialized = null; Component prev = components.remove(index); if (prev != null) { return prev.getValue(); } return null; } public <T> AbstractComposite setComponent(int index, T value, Serializer<T> s) { setComponent(index, value, s, comparatorForSerializer(s)); return this; } public <T> AbstractComposite setComponent(int index, T value, Serializer<T> s, String comparator) { setComponent(index, value, s, comparator, ComponentEquality.EQUAL); return this; } @SuppressWarnings("unchecked") public <T> AbstractComposite setComponent(int index, T value, Serializer<T> s, String comparator, ComponentEquality equality) { serialized = null; while (components.size() <= index) { components.add(null); } components.set(index, new Component(value, null, s, comparator, equality)); return this; } @SuppressWarnings("unchecked") @Override public Object set(int index, Object element) { serialized = null; if (element instanceof Component) { Component prev = components.set(index, (Component<?>) element); if (prev != null) { return prev.getValue(); } return null; } element = mapIfNumber(element); Serializer s = serializerForPosition(index); if (s == null) { s = SerializerTypeInferer.getSerializer(element); } String c = comparatorForPosition(index); if (c == null) { c = comparatorForSerializer(s); } Component prev = components.set(index, new Component(element, null, s, c, ComponentEquality.EQUAL)); if (prev != null) { return prev.getValue(); } return null; } @Override public Object get(int i) { Component c = components.get(i); if (c != null) { return c.getValue(); } return null; } public <T> T get(int i, Serializer<T> s) throws ClassCastException { T value = null; Component<?> c = components.get(i); if (c != null) { value = c.getValue(s); } return value; } public Component getComponent(int i) { if (i >= components.size()) { return null; } Component c = components.get(i); return c; } public Iterator<Component<?>> componentsIterator() { return components.iterator(); } @SuppressWarnings("unchecked") public ByteBuffer serialize() { if (serialized != null) { return serialized.duplicate(); } ByteBufferOutputStream out = new ByteBufferOutputStream(); int i = 0; for (Component c : components) { Serializer<?> s = serializerForPosition(i); ByteBuffer cb = c.getBytes(s); if (cb == null) { cb = ByteBuffer.allocate(0); } if (dynamic) { String comparator = comparatorForPosition(i); if (comparator == null) { comparator = c.getComparator(); } if (comparator == null) { comparator = ComparatorType.BYTESTYPE.getTypeName(); } int p = comparator.indexOf("(reversed=true)"); boolean desc = false; if (p >= 0) { comparator = comparator.substring(0, p); desc = true; } if (aliasToComparatorMapping.inverse().containsKey(comparator)) { byte a = aliasToComparatorMapping.inverse().get(comparator); if (desc) { a = (byte) Character.toUpperCase((char) a); } out.writeShort((short) (0x8000 | a)); } else { out.writeShort((short) comparator.length()); out.write(ByteBufferUtil.bytes(comparator)); } } out.writeShort((short) cb.remaining()); out.write(cb.slice()); out.write(c.getEquality().toByte()); i++; } serialized = out.getByteBuffer(); return serialized.duplicate(); } @SuppressWarnings("unchecked") public void deserialize(ByteBuffer b) { serialized = b.duplicate(); components = new ArrayList<Component<?>>(); String comparator = null; int i = 0; while ((comparator = getComparator(i, b)) != null) { ByteBuffer data = getWithShortLength(b); if (data != null) { Serializer<?> s = getSerializer(i, comparator); ComponentEquality equality = ComponentEquality.fromByte(b.get()); components.add(new Component(null, data.slice(), s, comparator, equality)); } else { throw new RuntimeException("Missing component data in composite type"); } i++; } } protected static int getShortLength(ByteBuffer bb) { int length = (bb.get() & 0xFF) << 8; return length | (bb.get() & 0xFF); } protected static ByteBuffer getBytes(ByteBuffer bb, int length) { ByteBuffer copy = bb.duplicate(); copy.limit(copy.position() + length); bb.position(bb.position() + length); return copy; } protected static ByteBuffer getWithShortLength(ByteBuffer bb) { int length = getShortLength(bb); return getBytes(bb, length); } }
package com.itranswarp.bitcoin.constant; import java.math.BigInteger; import com.itranswarp.bitcoin.util.HashUtils; public final class BitcoinConstants { /** * Magic number for bitcoin message. */ public static final int MAGIC = 0xd9b4bef9; /** * Default port for bitcoin peer. */ public static final int PORT = 8333; /** * Bitcoin protocol version. */ public static final int PROTOCOL_VERSION = 70014; /** * Network services. */ public static final long NETWORK_SERVICES = 1L; /** * Network ID: 0x00 = main network. */ public static final byte NETWORK_ID = 0x00; public static final byte[] NETWORK_ID_ARRAY = { NETWORK_ID }; /** * Public key prefix: 0x04. */ public static final byte PUBLIC_KEY_PREFIX = 0x04; public static final byte[] PUBLIC_KEY_PREFIX_ARRAY = { PUBLIC_KEY_PREFIX }; /** * Private key prefix: 0x80. */ public static final byte PRIVATE_KEY_PREFIX = (byte) 0x80; public static final byte[] PRIVATE_KEY_PREFIX_ARRAY = { PRIVATE_KEY_PREFIX }; /** * Minimum value of private key. */ public static final BigInteger MIN_PRIVATE_KEY = new BigInteger("ffffffffffffffff", 16); /** * Maximum value of private key. */ public static final BigInteger MAX_PRIVATE_KEY = new BigInteger( "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140", 16); /** * Random node id generated at startup. */ public static final long NODE_ID = (long) (Math.random() * Long.MAX_VALUE); /** * Bitcoin client subversion. */ public static final String SUB_VERSION = "/Satoshi:0.7.2/"; /** * Genesis block hash as string. */ public static final String GENESIS_HASH = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"; /** * Genesis block hash as bytes. */ public static final byte[] GENESIS_HASH_BYTES = HashUtils.toBytesAsLittleEndian(GENESIS_HASH); /** * Hardcoded genesis block data. */ public static final byte[] GENESIS_BLOCK_DATA = HashUtils.toBytes( "0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c0101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000"); /** * Hash bytes as "00000000...0000" */ public static final String ZERO_HASH = "0000000000000000000000000000000000000000000000000000000000000000"; /** * Hash bytes as "00000000...0000" */ public static final byte[] ZERO_HASH_BYTES = HashUtils .toBytesAsLittleEndian("0000000000000000000000000000000000000000000000000000000000000000"); /** * Transaction version. */ public static final int TX_VERSION = 0x01; /** * Signature type: SIGHASH_ALL. */ public static final int SIGHASH_ALL = 0x01; }
package gov.nih.nci.cabig.caaers.web.study; import gov.nih.nci.cabig.caaers.dao.workflow.WorkflowConfigDao; import gov.nih.nci.cabig.caaers.domain.Study; import gov.nih.nci.cabig.caaers.domain.StudySite; import gov.nih.nci.cabig.caaers.domain.StudyOrganization; import gov.nih.nci.cabig.caaers.domain.Organization; import gov.nih.nci.cabig.caaers.domain.workflow.StudySiteWorkflowConfig; import gov.nih.nci.cabig.caaers.domain.workflow.WorkflowConfig; import gov.nih.nci.cabig.caaers.web.fields.InputField; import gov.nih.nci.cabig.caaers.web.fields.InputFieldFactory; import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroup; import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroupMap; import gov.nih.nci.cabig.caaers.web.fields.RepeatingFieldGroupFactory; import java.util.*; import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.springframework.beans.BeanWrapper; import org.springframework.validation.Errors; /** * @author Rhett Sutphin * @author <a href="mailto:biju.joseph@semanticbits.com">Biju Joseph</a> */ class SitesTab extends StudyTab { private RepeatingFieldGroupFactory rfgFactory; private WorkflowConfigDao workflowConfigDao; public SitesTab() { super("Sites", "Sites", "study/study_sites"); } @Override public Map<String, Object> referenceData(HttpServletRequest request, StudyCommand command) { for(StudySite site : command.getStudy().getActiveStudySites()){ site.getActiveStudyInvestigators().size(); site.getActiveStudyPersonnel().size(); } return super.referenceData(request, command); } @Override public void postProcess(HttpServletRequest request, StudyCommand command, Errors errors) { String action = request.getParameter("_action"); Object isAjax = request.getAttribute("_isAjax"); if (isAjax != null) return; if (StringUtils.equals(action, "removeSite")) { int index = Integer.parseInt(request.getParameter("_selected")); StudySite site = command.getStudy().getStudySites().get(index); if (site.getId() != null) { if (CollectionUtils.isNotEmpty(site.getActiveStudyInvestigators())) { errors.reject("STU_013", "The site is associated to investigators, so unable to delete"); site.setRetiredIndicator(false); } if (CollectionUtils.isNotEmpty(site.getActiveStudyPersonnel())) { errors.reject("STU_014", "The site is associated to research staffs, so unable to delete"); site.setRetiredIndicator(false); } } //remove site, if no investigator or research person is associated to site. if(!errors.hasErrors()){ command.deleteStudySiteAtIndex(index); command.setStudySiteIndex(-1); } } request.setAttribute("tabFlashMessage", messageSource.getMessage(String.format("MSG_study.%s.flash_message", this.getClass().getSimpleName()), null, Locale.getDefault())); } @Override public Map<String, InputFieldGroup> createFieldGroups(StudyCommand command) { if (rfgFactory == null) { rfgFactory = new RepeatingFieldGroupFactory("main", "study.studySites"); InputField siteField = InputFieldFactory.createAutocompleterField("organization", "Site", true); siteField.getAttributes().put(InputField.ENABLE_CLEAR, true); rfgFactory.addField(siteField); } InputFieldGroupMap map = new InputFieldGroupMap(); Study study = command.getStudy(); map.addRepeatingFieldGroupFactory(rfgFactory, study.getStudySites().size()); return map; } @Override protected void validate(StudyCommand command, BeanWrapper commandBean, Map<String, InputFieldGroup> fieldGroups, Errors errors) { super.validate(command, commandBean, fieldGroups, errors); // check if there are duplicate sites. HashSet<Integer> set = new HashSet<Integer>(); int size = command.getStudy().getStudySites().size(); StudySite site = null; for(int i = 0; i < size; i++){ site = command.getStudy().getStudySites().get(i); if(site.isRetired() || site.getOrganization() == null) continue; if(!set.add(site.getOrganization().getId())){ rejectFields(fieldGroups.get("main" + i).getFields(), errors, "Duplicate"); } } } public void setWorkflowConfigDao(WorkflowConfigDao workflowConfigDao) { this.workflowConfigDao = workflowConfigDao; } }
package org.jasig.cas.authentication.principal; import java.net.URLEncoder; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class Response { /** Pattern to detect unprintable ASCII characters. */ private static final Pattern NON_PRINTABLE = Pattern.compile("[\\x00-\\x19\\x7F]+"); /** Log instance. */ protected static final Logger LOG = LoggerFactory.getLogger(Response.class); public static enum ResponseType { POST, REDIRECT } private final ResponseType responseType; private final String url; private final Map<String, String> attributes; protected Response(ResponseType responseType, final String url, final Map<String, String> attributes) { this.responseType = responseType; this.url = url; this.attributes = attributes; } public static Response getPostResponse(final String url, final Map<String, String> attributes) { return new Response(ResponseType.POST, url, attributes); } public static Response getRedirectResponse(final String url, final Map<String, String> parameters) { final StringBuilder builder = new StringBuilder(parameters.size() * 40 + 100); boolean isFirst = true; final String[] fragmentSplit = sanitizeUrl(url).split(" builder.append(fragmentSplit[0]); for (final Map.Entry<String, String> entry : parameters.entrySet()) { if (entry.getValue() != null) { if (isFirst) { builder.append(url.contains("?") ? "&" : "?"); isFirst = false; } else { builder.append("&"); } builder.append(entry.getKey()); builder.append("="); try { builder.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } catch (final Exception e) { builder.append(entry.getValue()); } } } if (fragmentSplit.length > 1) { builder.append(" builder.append(fragmentSplit[1]); } return new Response(ResponseType.REDIRECT, builder.toString(), parameters); } public Map<String, String> getAttributes() { return this.attributes; } public ResponseType getResponseType() { return this.responseType; } public String getUrl() { return this.url; } /** * Sanitize a URL provided by a relying party by normalizing non-printable * ASCII character sequences into spaces. This functionality protects * against CRLF attacks and other similar attacks using invisible characters * that could be abused to trick user agents. * * @param url URL to sanitize. * * @return Sanitized URL string. */ private static String sanitizeUrl(final String url) { final Matcher m = NON_PRINTABLE.matcher(url); final StringBuffer sb = new StringBuffer(url.length()); boolean hasNonPrintable = false; while (m.find()) { m.appendReplacement(sb, " "); hasNonPrintable = true; } m.appendTail(sb); if (hasNonPrintable) { LOG.warn("Non-printable characters detected in redirect URL. This may indicate a CRLF attack."); } return sb.toString(); } }
package pl.edu.icm.cermine.web.controller; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static java.util.Collections.singletonList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringEscapeUtils; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import pl.edu.icm.cermine.bibref.CRFBibReferenceParser; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.bibref.transformers.BibEntryToNLMElementConverter; import pl.edu.icm.cermine.metadata.affiliation.AffiliationParser; import pl.edu.icm.cermine.service.*; /** * * @author bart * @author axnow */ @org.springframework.stereotype.Controller public class CermineController { @Autowired CermineExtractorService extractorService; @Autowired TaskManager taskManager; Logger logger = LoggerFactory.getLogger(CermineController.class); @RequestMapping(value = "/index.html") public String showHome(Model model) { return "home"; } @RequestMapping(value = "/about.html") public String showAbout(Model model) { return "about"; } @RequestMapping(value = "/download.html") public ResponseEntity<String> downloadXML(@RequestParam("task") long taskId, @RequestParam("type") String resultType, Model model) throws NoSuchTaskException { ExtractionTask task = taskManager.getTask(taskId); if ("nlm".equals(resultType)) { String nlm = task.getResult().getNlm(); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Content-Type", "application/xml;charset=utf-8"); return new ResponseEntity<String>(nlm, responseHeaders, HttpStatus.OK); } else { throw new RuntimeException("Unknown request type: " + resultType); } } @RequestMapping(value = "/examplepdf.html", method = RequestMethod.GET) public void getExamplePDF(@RequestParam("file") String filename, HttpServletRequest request, HttpServletResponse response) { InputStream in = null; OutputStream out = null; try { if (!filename.matches("^example\\d+\\.pdf$")) { throw new RuntimeException("No such example file!"); } response.setContentType("application/pdf"); in = CermineController.class.getResourceAsStream("/examples/"+filename); if (in == null) { throw new RuntimeException("No such example file!"); } out = response.getOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (IOException ex) { throw new RuntimeException(ex); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ex) { } } } @RequestMapping(value = "/uploadexample.do", method = RequestMethod.GET) public String uploadExampleFileStream(@RequestParam("file") String filename, HttpServletRequest request, Model model) { if (!filename.matches("^example\\d+\\.pdf$")) { throw new RuntimeException("No such example file!"); } logger.info("Got an upload request."); try { InputStream in = CermineController.class.getResourceAsStream("/examples/"+filename); if (in == null) { throw new RuntimeException("No such example file!"); } byte[] content = IOUtils.toByteArray(in); if (content.length == 0) { model.addAttribute("warning", "An empty or no file sent."); return "home"; } logger.debug("Original filename is: " + filename); filename = taskManager.getProperFilename(filename); logger.debug("Created filename: " + filename); long taskId = extractorService.initExtractionTask(content, filename); logger.debug("Task manager is: " + taskManager); return "redirect:/task.html?task=" + taskId; } catch (Exception ex) { throw new RuntimeException(ex); } } @RequestMapping(value = "/upload.do", method = RequestMethod.POST) public String uploadFileStream(@RequestParam("files") MultipartFile file, HttpServletRequest request, Model model) { logger.info("Got an upload request."); try { byte[] content = file.getBytes(); if (content.length == 0) { model.addAttribute("warning", "An empty or no file sent."); return "home"; } String filename = file.getOriginalFilename(); logger.debug("Original filename is: " + filename); filename = taskManager.getProperFilename(filename); logger.debug("Created filename: " + filename); long taskId = extractorService.initExtractionTask(content, filename); logger.debug("Task manager is: " + taskManager); return "redirect:/task.html?task=" + taskId; } catch (Exception ex) { throw new RuntimeException(ex); } } @RequestMapping(value = "/extract.do", method = RequestMethod.POST) public ResponseEntity<String> extractSync(@RequestBody byte[] content, HttpServletRequest request, Model model) { try { logger.debug("content length: {}", content.length); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.APPLICATION_XML); ExtractionResult result = extractorService.extractNLM(new ByteArrayInputStream(content)); String nlm = result.getNlm(); return new ResponseEntity<String>(nlm, responseHeaders, HttpStatus.OK); } catch (Exception ex) { java.util.logging.Logger.getLogger(CermineController.class.getName()).log(Level.SEVERE, null, ex); return new ResponseEntity<String>("Exception: " + ex.getMessage(), null, HttpStatus.INTERNAL_SERVER_ERROR); } } @RequestMapping(value = "/parse.do", method = RequestMethod.POST) public ResponseEntity<String> parseSync(HttpServletRequest request, Model model) { try { String refText = request.getParameter("reference"); if (refText == null) { refText = request.getParameter("ref"); } String affText = request.getParameter("affiliation"); if (affText == null) { affText = request.getParameter("aff"); } if (refText == null && affText == null) { return new ResponseEntity<String>( "Exception: \"reference\" or \"affiliation\" parameter has to be passed!\n", null, HttpStatus.INTERNAL_SERVER_ERROR); } HttpHeaders responseHeaders = new HttpHeaders(); String response; if (refText != null) { String format = request.getParameter("format"); if (format == null) { format = "bibtex"; } format = format.toLowerCase(); if (!format.equals("nlm") && !format.equals("bibtex")) { return new ResponseEntity<String>( "Exception: format must be \"bibtex\" or \"nlm\"!\n", null, HttpStatus.INTERNAL_SERVER_ERROR); } CRFBibReferenceParser parser = CRFBibReferenceParser.getInstance(); BibEntry reference = parser.parseBibReference(refText); if (format.equals("bibtex")) { responseHeaders.setContentType(MediaType.TEXT_PLAIN); response = reference.toBibTeX(); } else { responseHeaders.setContentType(MediaType.APPLICATION_XML); BibEntryToNLMElementConverter converter = new BibEntryToNLMElementConverter(); Element element = converter.convert(reference); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); response = outputter.outputString(element); } } else { AffiliationParser parser = new AffiliationParser(); Element parsedAff = parser.parse(affText); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); response = outputter.outputString(parsedAff); } return new ResponseEntity<String>(response+"\n", responseHeaders, HttpStatus.OK); } catch (Exception ex) { java.util.logging.Logger.getLogger(CermineController.class.getName()).log(Level.SEVERE, null, ex); return new ResponseEntity<String>("Exception: " + ex.getMessage(), null, HttpStatus.INTERNAL_SERVER_ERROR); } } @ExceptionHandler(value = NoSuchTaskException.class) public ModelAndView taskNotFoundHandler(NoSuchTaskException nste) { return new ModelAndView("error", "errorMessage", nste.getMessage()); } @RequestMapping(value = "/task.html", method = RequestMethod.GET) public ModelAndView showTask(@RequestParam("task") long id) throws NoSuchTaskException { ExtractionTask task = taskManager.getTask(id); HashMap<String, Object> model = new HashMap<String, Object>(); model.put("task", task); if (task.isFinished()) { model.put("result", task.getResult()); String nlmHtml = StringEscapeUtils.escapeHtml(task.getResult().getNlm()); model.put("nlm", nlmHtml); model.put("meta", task.getResult().getMeta()); model.put("html", task.getResult().getHtml()); } return new ModelAndView("task", model); } @RequestMapping(value = "/tasks.html") public ModelAndView showTasks() { return new ModelAndView("tasks", "tasks", taskManager.taskList()); } private static ResponseEntity<List<Map<String, Object>>> wrapResponse(Map<String, Object> rBody) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<List<Map<String, Object>>>(singletonList(rBody), headers, HttpStatus.OK); } private static Map<String, Object> fileDetails(MultipartFile file, int size) { Map<String, Object> rBody = new HashMap<String, Object>(); rBody.put("name", file.getOriginalFilename()); rBody.put("size", size); return rBody; } public CermineExtractorService getExtractorService() { return extractorService; } public void setExtractorService(CermineExtractorService extractorService) { this.extractorService = extractorService; } public TaskManager getTaskManager() { return taskManager; } public void setTaskManager(TaskManager taskManager) { this.taskManager = taskManager; } }
package ru.job4j.tasksortdeparament; import java.util.*; public class DescendingComporatorLow implements Comparator<String> { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }
package io.strimzi.operator.cluster.model; import io.fabric8.kubernetes.api.model.Affinity; import io.fabric8.kubernetes.api.model.AffinityBuilder; import io.fabric8.kubernetes.api.model.Container; import io.fabric8.kubernetes.api.model.ContainerBuilder; import io.fabric8.kubernetes.api.model.ContainerPort; import io.fabric8.kubernetes.api.model.EnvVar; import io.fabric8.kubernetes.api.model.IntOrString; import io.fabric8.kubernetes.api.model.LabelSelector; import io.fabric8.kubernetes.api.model.LifecycleBuilder; import io.fabric8.kubernetes.api.model.PersistentVolumeClaim; import io.fabric8.kubernetes.api.model.Quantity; import io.fabric8.kubernetes.api.model.ResourceRequirements; import io.fabric8.kubernetes.api.model.ResourceRequirementsBuilder; import io.fabric8.kubernetes.api.model.Secret; import io.fabric8.kubernetes.api.model.Service; import io.fabric8.kubernetes.api.model.ServiceAccount; import io.fabric8.kubernetes.api.model.ServiceAccountBuilder; import io.fabric8.kubernetes.api.model.ServicePort; import io.fabric8.kubernetes.api.model.Volume; import io.fabric8.kubernetes.api.model.VolumeMount; import io.fabric8.kubernetes.api.model.networking.NetworkPolicy; import io.fabric8.kubernetes.api.model.networking.NetworkPolicyBuilder; import io.fabric8.kubernetes.api.model.networking.NetworkPolicyIngressRule; import io.fabric8.kubernetes.api.model.networking.NetworkPolicyIngressRuleBuilder; import io.fabric8.kubernetes.api.model.networking.NetworkPolicyPeer; import io.fabric8.kubernetes.api.model.networking.NetworkPolicyPort; import io.fabric8.kubernetes.api.model.apps.StatefulSet; import io.fabric8.kubernetes.api.model.policy.PodDisruptionBudget; import io.fabric8.openshift.api.model.Route; import io.fabric8.openshift.api.model.RouteBuilder; import io.strimzi.api.kafka.model.EphemeralStorage; import io.strimzi.api.kafka.model.InlineLogging; import io.strimzi.api.kafka.model.JbodStorage; import io.strimzi.api.kafka.model.Kafka; import io.strimzi.api.kafka.model.KafkaAuthorization; import io.strimzi.api.kafka.model.KafkaAuthorizationSimple; import io.strimzi.api.kafka.model.KafkaClusterSpec; import io.strimzi.api.kafka.model.listener.ExternalListenerBootstrapOverride; import io.strimzi.api.kafka.model.listener.ExternalListenerBrokerOverride; import io.strimzi.api.kafka.model.listener.LoadBalancerListenerOverride; import io.strimzi.api.kafka.model.listener.NodePortListenerBrokerOverride; import io.strimzi.api.kafka.model.listener.NodePortListenerOverride; import io.strimzi.api.kafka.model.listener.KafkaListenerAuthenticationTls; import io.strimzi.api.kafka.model.listener.KafkaListenerExternalLoadBalancer; import io.strimzi.api.kafka.model.listener.KafkaListenerExternalNodePort; import io.strimzi.api.kafka.model.listener.KafkaListenerExternalRoute; import io.strimzi.api.kafka.model.listener.KafkaListeners; import io.strimzi.api.kafka.model.KafkaResources; import io.strimzi.api.kafka.model.Logging; import io.strimzi.api.kafka.model.PersistentClaimStorage; import io.strimzi.api.kafka.model.Rack; import io.strimzi.api.kafka.model.SingleVolumeStorage; import io.strimzi.api.kafka.model.Storage; import io.strimzi.api.kafka.model.TlsSidecar; import io.strimzi.api.kafka.model.listener.RouteListenerBrokerOverride; import io.strimzi.api.kafka.model.listener.RouteListenerOverride; import io.strimzi.api.kafka.model.template.KafkaClusterTemplate; import io.strimzi.certs.CertAndKey; import io.strimzi.operator.common.Annotations; import io.strimzi.operator.common.model.Labels; import io.strimzi.operator.common.operator.resource.ClusterRoleBindingOperator; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static java.util.Collections.singletonMap; public class KafkaCluster extends AbstractModel { protected static final String INIT_NAME = "kafka-init"; protected static final String INIT_VOLUME_NAME = "rack-volume"; protected static final String INIT_VOLUME_MOUNT = "/opt/kafka/init"; private static final String ENV_VAR_KAFKA_INIT_RACK_TOPOLOGY_KEY = "RACK_TOPOLOGY_KEY"; private static final String ENV_VAR_KAFKA_INIT_NODE_NAME = "NODE_NAME"; private static final String ENV_VAR_KAFKA_INIT_EXTERNAL_ADDRESS = "EXTERNAL_ADDRESS"; private static final String ENV_VAR_KAFKA_INIT_EXTERNAL_ADVERTISED_ADDRESSES = "EXTERNAL_ADVERTISED_ADDRESSES"; /** {@code TRUE} when the CLIENT listener (PLAIN transport) should be enabled*/ private static final String ENV_VAR_KAFKA_CLIENT_ENABLED = "KAFKA_CLIENT_ENABLED"; /** The authentication to configure for the CLIENT listener (PLAIN transport). */ private static final String ENV_VAR_KAFKA_CLIENT_AUTHENTICATION = "KAFKA_CLIENT_AUTHENTICATION"; /** {@code TRUE} when the CLIENTTLS listener (TLS transport) should be enabled*/ private static final String ENV_VAR_KAFKA_CLIENTTLS_ENABLED = "KAFKA_CLIENTTLS_ENABLED"; /** The authentication to configure for the CLIENTTLS listener (TLS transport) . */ private static final String ENV_VAR_KAFKA_CLIENTTLS_AUTHENTICATION = "KAFKA_CLIENTTLS_AUTHENTICATION"; protected static final String ENV_VAR_KAFKA_EXTERNAL_ENABLED = "KAFKA_EXTERNAL_ENABLED"; protected static final String ENV_VAR_KAFKA_EXTERNAL_ADDRESSES = "KAFKA_EXTERNAL_ADDRESSES"; protected static final String ENV_VAR_KAFKA_EXTERNAL_AUTHENTICATION = "KAFKA_EXTERNAL_AUTHENTICATION"; protected static final String ENV_VAR_KAFKA_EXTERNAL_TLS = "KAFKA_EXTERNAL_TLS"; private static final String ENV_VAR_KAFKA_AUTHORIZATION_TYPE = "KAFKA_AUTHORIZATION_TYPE"; private static final String ENV_VAR_KAFKA_AUTHORIZATION_SUPER_USERS = "KAFKA_AUTHORIZATION_SUPER_USERS"; public static final String ENV_VAR_KAFKA_ZOOKEEPER_CONNECT = "KAFKA_ZOOKEEPER_CONNECT"; private static final String ENV_VAR_KAFKA_METRICS_ENABLED = "KAFKA_METRICS_ENABLED"; public static final String ENV_VAR_KAFKA_LOG_DIRS = "KAFKA_LOG_DIRS"; public static final String ENV_VAR_KAFKA_CONFIGURATION = "KAFKA_CONFIGURATION"; protected static final int CLIENT_PORT = 9092; protected static final String CLIENT_PORT_NAME = "clients"; protected static final int REPLICATION_PORT = 9091; protected static final String REPLICATION_PORT_NAME = "replication"; protected static final int CLIENT_TLS_PORT = 9093; protected static final String CLIENT_TLS_PORT_NAME = "clientstls"; protected static final int EXTERNAL_PORT = 9094; protected static final String EXTERNAL_PORT_NAME = "external"; protected static final String KAFKA_NAME = "kafka"; protected static final String CLUSTER_CA_CERTS_VOLUME = "cluster-ca"; protected static final String BROKER_CERTS_VOLUME = "broker-certs"; protected static final String CLIENT_CA_CERTS_VOLUME = "client-ca-cert"; protected static final String CLUSTER_CA_CERTS_VOLUME_MOUNT = "/opt/kafka/cluster-ca-certs"; protected static final String BROKER_CERTS_VOLUME_MOUNT = "/opt/kafka/broker-certs"; protected static final String CLIENT_CA_CERTS_VOLUME_MOUNT = "/opt/kafka/client-ca-certs"; protected static final String TLS_SIDECAR_NAME = "tls-sidecar"; protected static final String TLS_SIDECAR_KAFKA_CERTS_VOLUME_MOUNT = "/etc/tls-sidecar/kafka-brokers/"; protected static final String TLS_SIDECAR_CLUSTER_CA_CERTS_VOLUME_MOUNT = "/etc/tls-sidecar/cluster-ca-certs/"; private static final String NAME_SUFFIX = "-kafka"; // Suffixes for secrets with certificates private static final String SECRET_BROKERS_SUFFIX = NAME_SUFFIX + "-brokers"; /** Records the Kafka version currently running inside Kafka StatefulSet */ public static final String ANNO_STRIMZI_IO_KAFKA_VERSION = Annotations.STRIMZI_DOMAIN + "/kafka-version"; /** Records the state of the Kafka upgrade process. Unset outside of upgrades. */ public static final String ANNO_STRIMZI_IO_FROM_VERSION = Annotations.STRIMZI_DOMAIN + "/from-version"; /** Records the state of the Kafka upgrade process. Unset outside of upgrades. */ public static final String ANNO_STRIMZI_IO_TO_VERSION = Annotations.STRIMZI_DOMAIN + "/to-version"; // Kafka configuration private String zookeeperConnect; private Rack rack; private String initImage; private TlsSidecar tlsSidecar; private KafkaListeners listeners; private KafkaAuthorization authorization; private Set<String> externalAddresses = new HashSet<>(); private KafkaVersion kafkaVersion; // Templates protected Map<String, String> templateExternalBootstrapServiceLabels; protected Map<String, String> templateExternalBootstrapServiceAnnotations; protected Map<String, String> templatePerPodServiceLabels; protected Map<String, String> templatePerPodServiceAnnotations; protected Map<String, String> templateExternalBootstrapRouteLabels; protected Map<String, String> templateExternalBootstrapRouteAnnotations; protected Map<String, String> templatePerPodRouteLabels; protected Map<String, String> templatePerPodRouteAnnotations; // Configuration defaults private static final int DEFAULT_REPLICAS = 3; private static final int DEFAULT_HEALTHCHECK_DELAY = 15; private static final int DEFAULT_HEALTHCHECK_TIMEOUT = 5; private static final boolean DEFAULT_KAFKA_METRICS_ENABLED = false; /** * Private key and certificate for each Kafka Pod name * used as server certificates for Kafka brokers */ private Map<String, CertAndKey> brokerCerts; /** * Lists with volumes, persistent volume claims and related volume mount paths for the storage */ List<Volume> dataVolumes = new ArrayList<>(); List<PersistentVolumeClaim> dataPvcs = new ArrayList<>(); List<VolumeMount> dataVolumeMountPaths = new ArrayList<>(); /** * Constructor * * @param namespace Kubernetes/OpenShift namespace where Kafka cluster resources are going to be created * @param cluster overall cluster name * @param labels labels to add to the cluster */ private KafkaCluster(String namespace, String cluster, Labels labels) { super(namespace, cluster, labels); this.name = kafkaClusterName(cluster); this.serviceName = serviceName(cluster); this.headlessServiceName = headlessServiceName(cluster); this.ancillaryConfigName = metricAndLogConfigsName(cluster); this.replicas = DEFAULT_REPLICAS; this.readinessTimeout = DEFAULT_HEALTHCHECK_TIMEOUT; this.readinessInitialDelay = DEFAULT_HEALTHCHECK_DELAY; this.livenessTimeout = DEFAULT_HEALTHCHECK_TIMEOUT; this.livenessInitialDelay = DEFAULT_HEALTHCHECK_DELAY; this.isMetricsEnabled = DEFAULT_KAFKA_METRICS_ENABLED; setZookeeperConnect(ZookeeperCluster.serviceName(cluster) + ":2181"); this.mountPath = "/var/lib/kafka"; this.logAndMetricsConfigVolumeName = "kafka-metrics-and-logging"; this.logAndMetricsConfigMountPath = "/opt/kafka/custom-config/"; this.initImage = KafkaClusterSpec.DEFAULT_INIT_IMAGE; } public static String kafkaClusterName(String cluster) { return KafkaResources.kafkaStatefulSetName(cluster); } public static String metricAndLogConfigsName(String cluster) { return KafkaResources.kafkaMetricsAndLogConfigMapName(cluster); } public static String serviceName(String cluster) { return KafkaResources.bootstrapServiceName(cluster); } public static String podDnsName(String namespace, String cluster, int podId) { return String.format("%s.%s.%s.svc.%s", KafkaCluster.kafkaPodName(cluster, podId), KafkaCluster.headlessServiceName(cluster), namespace, ModelUtils.KUBERNETES_SERVICE_DNS_DOMAIN); } /** * Generates the name of the service used as bootstrap service for external clients * * @param cluster Name of the cluster * @return */ public static String externalBootstrapServiceName(String cluster) { return KafkaResources.externalBootstrapServiceName(cluster); } /** * Generates the name of the service for exposing individual pods * * @param cluster Name of the cluster * @param pod Pod sequence number assign by StatefulSet * @return */ public static String externalServiceName(String cluster, int pod) { return kafkaClusterName(cluster) + "-" + pod; } public static String headlessServiceName(String cluster) { return KafkaResources.brokersServiceName(cluster); } public static String kafkaPodName(String cluster, int pod) { return kafkaClusterName(cluster) + "-" + pod; } public static String clientsCaKeySecretName(String cluster) { return KafkaResources.clientsCaKeySecretName(cluster); } public static String brokersSecretName(String cluster) { return cluster + KafkaCluster.SECRET_BROKERS_SUFFIX; } public static String clientsCaCertSecretName(String cluster) { return KafkaResources.clientsCaCertificateSecretName(cluster); } public static KafkaCluster fromCrd(Kafka kafkaAssembly, KafkaVersion.Lookup versions) { KafkaCluster result = new KafkaCluster(kafkaAssembly.getMetadata().getNamespace(), kafkaAssembly.getMetadata().getName(), Labels.fromResource(kafkaAssembly).withKind(kafkaAssembly.getKind())); result.setOwnerReference(kafkaAssembly); KafkaClusterSpec kafkaClusterSpec = kafkaAssembly.getSpec().getKafka(); result.setReplicas(kafkaClusterSpec.getReplicas()); String image = versions.kafkaImage(kafkaClusterSpec.getImage(), kafkaClusterSpec.getVersion()); if (image == null) { throw new InvalidResourceException("Version is not supported"); } result.setImage(image); if (kafkaClusterSpec.getReadinessProbe() != null) { result.setReadinessInitialDelay(kafkaClusterSpec.getReadinessProbe().getInitialDelaySeconds()); result.setReadinessTimeout(kafkaClusterSpec.getReadinessProbe().getTimeoutSeconds()); } if (kafkaClusterSpec.getLivenessProbe() != null) { result.setLivenessInitialDelay(kafkaClusterSpec.getLivenessProbe().getInitialDelaySeconds()); result.setLivenessTimeout(kafkaClusterSpec.getLivenessProbe().getTimeoutSeconds()); } result.setRack(kafkaClusterSpec.getRack()); String initImage = kafkaClusterSpec.getBrokerRackInitImage(); if (initImage == null) { initImage = KafkaClusterSpec.DEFAULT_INIT_IMAGE; } result.setInitImage(initImage); Logging logging = kafkaClusterSpec.getLogging(); result.setLogging(logging == null ? new InlineLogging() : logging); result.setGcLoggingEnabled(kafkaClusterSpec.getJvmOptions() == null ? true : kafkaClusterSpec.getJvmOptions().isGcLoggingEnabled()); result.setJvmOptions(kafkaClusterSpec.getJvmOptions()); result.setConfiguration(new KafkaConfiguration(kafkaClusterSpec.getConfig().entrySet())); Map<String, Object> metrics = kafkaClusterSpec.getMetrics(); if (metrics != null) { result.setMetricsEnabled(true); result.setMetricsConfig(metrics.entrySet()); } if (kafkaClusterSpec.getStorage() instanceof PersistentClaimStorage) { PersistentClaimStorage persistentClaimStorage = (PersistentClaimStorage) kafkaClusterSpec.getStorage(); if (persistentClaimStorage.getSize() == null || persistentClaimStorage.getSize().isEmpty()) { throw new InvalidResourceException("The size is mandatory for a persistent-claim storage"); } } result.setStorage(kafkaClusterSpec.getStorage()); result.setDataVolumesClaimsAndMountPaths(result.getStorage()); result.setUserAffinity(kafkaClusterSpec.getAffinity()); result.setResources(kafkaClusterSpec.getResources()); result.setTolerations(kafkaClusterSpec.getTolerations()); result.setTlsSidecar(kafkaClusterSpec.getTlsSidecar()); KafkaListeners listeners = kafkaClusterSpec.getListeners(); result.setListeners(listeners); if (listeners != null) { if (listeners.getPlain() != null && listeners.getPlain().getAuthentication() instanceof KafkaListenerAuthenticationTls) { throw new InvalidResourceException("You cannot configure TLS authentication on a plain listener."); } if (listeners.getExternal() != null && !result.isExposedWithTls() && listeners.getExternal().getAuth() instanceof KafkaListenerAuthenticationTls) { throw new InvalidResourceException("TLS Client Authentication can be used only with enabled TLS encryption!"); } } result.setAuthorization(kafkaClusterSpec.getAuthorization()); if (kafkaClusterSpec.getTemplate() != null) { KafkaClusterTemplate template = kafkaClusterSpec.getTemplate(); if (template.getStatefulset() != null && template.getStatefulset().getMetadata() != null) { result.templateStatefulSetLabels = template.getStatefulset().getMetadata().getLabels(); result.templateStatefulSetAnnotations = template.getStatefulset().getMetadata().getAnnotations(); } ModelUtils.parsePodTemplate(result, template.getPod()); if (template.getBootstrapService() != null && template.getBootstrapService().getMetadata() != null) { result.templateServiceLabels = template.getBootstrapService().getMetadata().getLabels(); result.templateServiceAnnotations = template.getBootstrapService().getMetadata().getAnnotations(); } if (template.getBrokersService() != null && template.getBrokersService().getMetadata() != null) { result.templateHeadlessServiceLabels = template.getBrokersService().getMetadata().getLabels(); result.templateHeadlessServiceAnnotations = template.getBrokersService().getMetadata().getAnnotations(); } if (template.getExternalBootstrapService() != null && template.getExternalBootstrapService().getMetadata() != null) { result.templateExternalBootstrapServiceLabels = template.getExternalBootstrapService().getMetadata().getLabels(); result.templateExternalBootstrapServiceAnnotations = template.getExternalBootstrapService().getMetadata().getAnnotations(); } if (template.getPerPodService() != null && template.getPerPodService().getMetadata() != null) { result.templatePerPodServiceLabels = template.getPerPodService().getMetadata().getLabels(); result.templatePerPodServiceAnnotations = template.getPerPodService().getMetadata().getAnnotations(); } if (template.getExternalBootstrapRoute() != null && template.getExternalBootstrapRoute().getMetadata() != null) { result.templateExternalBootstrapRouteLabels = template.getExternalBootstrapRoute().getMetadata().getLabels(); result.templateExternalBootstrapRouteAnnotations = template.getExternalBootstrapRoute().getMetadata().getAnnotations(); } if (template.getPerPodRoute() != null && template.getPerPodRoute().getMetadata() != null) { result.templatePerPodRouteLabels = template.getPerPodRoute().getMetadata().getLabels(); result.templatePerPodRouteAnnotations = template.getPerPodRoute().getMetadata().getAnnotations(); } ModelUtils.parsePodDisruptionBudgetTemplate(result, template.getPodDisruptionBudget()); } result.kafkaVersion = versions.version(kafkaClusterSpec.getVersion()); return result; } /** * Manage certificates generation based on those already present in the Secrets * * @param kafka The Kafka custom resource * @param clusterCa The CA for cluster certificates * @param externalBootstrapDnsName The set of DNS names for bootstrap service (should be appended to every broker certificate) * @param externalDnsNames The list of DNS names for broker pods (should be appended only to specific certificates for given broker) */ public void generateCertificates(Kafka kafka, ClusterCa clusterCa, Set<String> externalBootstrapDnsName, Map<Integer, Set<String>> externalDnsNames) { log.debug("Generating certificates"); try { brokerCerts = clusterCa.generateBrokerCerts(kafka, externalBootstrapDnsName, externalDnsNames); } catch (IOException e) { log.warn("Error while generating certificates", e); } log.debug("End generating certificates"); } /** * Generates ports for bootstrap service. * The bootstrap service contains only the client interfaces. * Not the replication interface which doesn't need bootstrap service. * * @return List with generated ports */ private List<ServicePort> getServicePorts() { List<ServicePort> ports = new ArrayList<>(4); ports.add(createServicePort(REPLICATION_PORT_NAME, REPLICATION_PORT, REPLICATION_PORT, "TCP")); if (listeners != null && listeners.getPlain() != null) { ports.add(createServicePort(CLIENT_PORT_NAME, CLIENT_PORT, CLIENT_PORT, "TCP")); } if (listeners != null && listeners.getTls() != null) { ports.add(createServicePort(CLIENT_TLS_PORT_NAME, CLIENT_TLS_PORT, CLIENT_TLS_PORT, "TCP")); } if (isMetricsEnabled()) { ports.add(createServicePort(METRICS_PORT_NAME, METRICS_PORT, METRICS_PORT, "TCP")); } return ports; } /** * Generates ports for headless service. * The headless service contains both the client interfaces as well as replication interface. * * @return List with generated ports */ private List<ServicePort> getHeadlessServicePorts() { List<ServicePort> ports = new ArrayList<>(3); ports.add(createServicePort(REPLICATION_PORT_NAME, REPLICATION_PORT, REPLICATION_PORT, "TCP")); if (listeners != null && listeners.getPlain() != null) { ports.add(createServicePort(CLIENT_PORT_NAME, CLIENT_PORT, CLIENT_PORT, "TCP")); } if (listeners != null && listeners.getTls() != null) { ports.add(createServicePort(CLIENT_TLS_PORT_NAME, CLIENT_TLS_PORT, CLIENT_TLS_PORT, "TCP")); } return ports; } /** * Generates a Service according to configured defaults * @return The generated Service */ public Service generateService() { return createService("ClusterIP", getServicePorts(), mergeAnnotations(getPrometheusAnnotations(), templateServiceAnnotations)); } /** * Utility function to help to determine the type of service based on external listener configuration * * @return Service type */ private String getExternalServiceType() { if (isExposedWithNodePort()) { return "NodePort"; } else if (isExposedWithLoadBalancer()) { return "LoadBalancer"; } else { return "ClusterIP"; } } /** * Generates external bootstrap service. This service is used for exposing it externally. * It exposes only the external port 9094. * Separate service is used to make sure that we do not expose the internal ports to the outside of the cluster * * @return The generated Service */ public Service generateExternalBootstrapService() { if (isExposed()) { String externalBootstrapServiceName = externalBootstrapServiceName(cluster); List<ServicePort> ports; Integer nodePort = null; if (isExposedWithNodePort()) { KafkaListenerExternalNodePort externalNodePort = (KafkaListenerExternalNodePort) listeners.getExternal(); if (externalNodePort.getOverrides() != null && externalNodePort.getOverrides().getBootstrap() != null) { nodePort = externalNodePort.getOverrides().getBootstrap().getNodePort(); } } ports = Collections.singletonList(createServicePort(EXTERNAL_PORT_NAME, EXTERNAL_PORT, EXTERNAL_PORT, nodePort, "TCP")); return createService(externalBootstrapServiceName, getExternalServiceType(), ports, getLabelsWithName(externalBootstrapServiceName, templateExternalBootstrapServiceLabels), getSelectorLabels(), mergeAnnotations(Collections.EMPTY_MAP, templateExternalBootstrapServiceAnnotations)); } return null; } /** * Generates service for pod. This service is used for exposing it externally. * * @param pod Number of the pod for which this service should be generated * @return The generated Service */ public Service generateExternalService(int pod) { if (isExposed()) { String perPodServiceName = externalServiceName(cluster, pod); List<ServicePort> ports = new ArrayList<>(1); Integer nodePort = null; if (isExposedWithNodePort()) { KafkaListenerExternalNodePort externalNodePort = (KafkaListenerExternalNodePort) listeners.getExternal(); if (externalNodePort.getOverrides() != null && externalNodePort.getOverrides().getBrokers() != null) { nodePort = externalNodePort.getOverrides().getBrokers().stream() .filter(broker -> broker != null && broker.getBroker() != null && broker.getBroker() == pod) .map(NodePortListenerBrokerOverride::getNodePort) .findAny().orElse(null); } } ports.add(createServicePort(EXTERNAL_PORT_NAME, EXTERNAL_PORT, EXTERNAL_PORT, nodePort, "TCP")); Labels selector = Labels.fromMap(getSelectorLabels()).withStatefulSetPod(kafkaPodName(cluster, pod)); return createService(perPodServiceName, getExternalServiceType(), ports, getLabelsWithName(perPodServiceName, templatePerPodServiceLabels), selector.toMap(), mergeAnnotations(Collections.EMPTY_MAP, templatePerPodServiceAnnotations)); } return null; } /** * Generates route for pod. This route is used for exposing it externally using OpenShift Routes. * * @param pod Number of the pod for which this route should be generated * @return The generated Route */ public Route generateExternalRoute(int pod) { if (isExposedWithRoute()) { String perPodServiceName = externalServiceName(cluster, pod); Route route = new RouteBuilder() .withNewMetadata() .withName(perPodServiceName) .withLabels(getLabelsWithName(perPodServiceName, templatePerPodRouteLabels)) .withAnnotations(mergeAnnotations(null, templatePerPodRouteAnnotations)) .withNamespace(namespace) .withOwnerReferences(createOwnerReference()) .endMetadata() .withNewSpec() .withNewTo() .withKind("Service") .withName(perPodServiceName) .endTo() .withNewPort() .withNewTargetPort(EXTERNAL_PORT) .endPort() .withNewTls() .withTermination("passthrough") .endTls() .endSpec() .build(); KafkaListenerExternalRoute listener = (KafkaListenerExternalRoute) listeners.getExternal(); if (listener.getOverrides() != null && listener.getOverrides().getBrokers() != null) { String specHost = listener.getOverrides().getBrokers().stream() .filter(broker -> broker != null && broker.getBroker() == pod && broker.getHost() != null) .map(RouteListenerBrokerOverride::getHost) .findAny() .orElse(null); if (specHost != null && !specHost.isEmpty()) { route.getSpec().setHost(specHost); } } return route; } return null; } /** * Generates a bootstrap route which can be used to bootstrap clients outside of OpenShift. * @return The generated Routes */ public Route generateExternalBootstrapRoute() { if (isExposedWithRoute()) { Route route = new RouteBuilder() .withNewMetadata() .withName(serviceName) .withLabels(getLabelsWithName(serviceName, templateExternalBootstrapRouteLabels)) .withAnnotations(mergeAnnotations(null, templateExternalBootstrapRouteAnnotations)) .withNamespace(namespace) .withOwnerReferences(createOwnerReference()) .endMetadata() .withNewSpec() .withNewTo() .withKind("Service") .withName(externalBootstrapServiceName(cluster)) .endTo() .withNewPort() .withNewTargetPort(EXTERNAL_PORT) .endPort() .withNewTls() .withTermination("passthrough") .endTls() .endSpec() .build(); KafkaListenerExternalRoute listener = (KafkaListenerExternalRoute) listeners.getExternal(); if (listener.getOverrides() != null && listener.getOverrides().getBootstrap() != null && listener.getOverrides().getBootstrap().getHost() != null && !listener.getOverrides().getBootstrap().getHost().isEmpty()) { route.getSpec().setHost(listener.getOverrides().getBootstrap().getHost()); } return route; } return null; } /** * Generates a headless Service according to configured defaults * @return The generated Service */ public Service generateHeadlessService() { Map<String, String> annotations = Collections.singletonMap("service.alpha.kubernetes.io/tolerate-unready-endpoints", "true"); return createHeadlessService(getHeadlessServicePorts(), annotations); } /** * Generates a StatefulSet according to configured defaults * @param isOpenShift True iff this operator is operating within OpenShift. * @return The generate StatefulSet */ public StatefulSet generateStatefulSet(boolean isOpenShift, ImagePullPolicy imagePullPolicy) { return createStatefulSet( singletonMap(ANNO_STRIMZI_IO_KAFKA_VERSION, kafkaVersion.version()), getVolumes(isOpenShift), getVolumeClaims(), getMergedAffinity(), getInitContainers(imagePullPolicy), getContainers(imagePullPolicy), isOpenShift); } /** * Generate the Secret containing the Kafka brokers certificates signed by the cluster CA certificate used for TLS based * internal communication with Zookeeper. * It also contains the related Kafka brokers private keys. * * @return The generated Secret */ public Secret generateBrokersSecret() { Map<String, String> data = new HashMap<>(); for (int i = 0; i < replicas; i++) { CertAndKey cert = brokerCerts.get(KafkaCluster.kafkaPodName(cluster, i)); data.put(KafkaCluster.kafkaPodName(cluster, i) + ".key", cert.keyAsBase64String()); data.put(KafkaCluster.kafkaPodName(cluster, i) + ".crt", cert.certAsBase64String()); } return createSecret(KafkaCluster.brokersSecretName(cluster), data); } private List<ContainerPort> getContainerPortList() { List<ContainerPort> portList = new ArrayList<>(5); portList.add(createContainerPort(REPLICATION_PORT_NAME, REPLICATION_PORT, "TCP")); if (listeners != null && listeners.getPlain() != null) { portList.add(createContainerPort(CLIENT_PORT_NAME, CLIENT_PORT, "TCP")); } if (listeners != null && listeners.getTls() != null) { portList.add(createContainerPort(CLIENT_TLS_PORT_NAME, CLIENT_TLS_PORT, "TCP")); } if (isExposed()) { portList.add(createContainerPort(EXTERNAL_PORT_NAME, EXTERNAL_PORT, "TCP")); } if (isMetricsEnabled) { portList.add(createContainerPort(METRICS_PORT_NAME, METRICS_PORT, "TCP")); } return portList; } /** * Fill the with volumes, persistent volume claims and related volume mount paths for the storage * It's called recursively on the related inner volumes if the storage is of {@link Storage#TYPE_JBOD} type * * @param storage the Storage instance from which building volumes, persistent volume claims and * related volume mount paths */ private void setDataVolumesClaimsAndMountPaths(Storage storage) { if (storage != null) { Integer id; if (storage instanceof EphemeralStorage) { id = ((EphemeralStorage) storage).getId(); } else if (storage instanceof PersistentClaimStorage) { id = ((PersistentClaimStorage) storage).getId(); } else if (storage instanceof JbodStorage) { for (SingleVolumeStorage volume : ((JbodStorage) storage).getVolumes()) { if (volume.getId() == null) throw new InvalidResourceException("Volumes under JBOD storage type have to have 'id' property"); // it's called recursively for setting the information from the current volume setDataVolumesClaimsAndMountPaths(volume); } return; } else { throw new IllegalStateException("The declared storage is not supported"); } String name = ModelUtils.getVolumePrefix(id); String mountPath = this.mountPath + "/" + name; if (storage instanceof EphemeralStorage) { dataVolumes.add(createEmptyDirVolume(name)); } else if (storage instanceof PersistentClaimStorage) { dataPvcs.add(createPersistentVolumeClaim(name, (PersistentClaimStorage) storage)); } dataVolumeMountPaths.add(createVolumeMount(name, mountPath)); } } private List<Volume> getVolumes(boolean isOpenShift) { List<Volume> volumeList = new ArrayList<>(); volumeList.addAll(dataVolumes); if (rack != null || isExposedWithNodePort()) { volumeList.add(createEmptyDirVolume(INIT_VOLUME_NAME)); } volumeList.add(createSecretVolume(CLUSTER_CA_CERTS_VOLUME, AbstractModel.clusterCaCertSecretName(cluster), isOpenShift)); volumeList.add(createSecretVolume(BROKER_CERTS_VOLUME, KafkaCluster.brokersSecretName(cluster), isOpenShift)); volumeList.add(createSecretVolume(CLIENT_CA_CERTS_VOLUME, KafkaCluster.clientsCaCertSecretName(cluster), isOpenShift)); volumeList.add(createConfigMapVolume(logAndMetricsConfigVolumeName, ancillaryConfigName)); return volumeList; } /* test */ List<PersistentVolumeClaim> getVolumeClaims() { List<PersistentVolumeClaim> pvcList = new ArrayList<>(); pvcList.addAll(dataPvcs); return pvcList; } private List<VolumeMount> getVolumeMounts() { List<VolumeMount> volumeMountList = new ArrayList<>(); volumeMountList.addAll(dataVolumeMountPaths); volumeMountList.add(createVolumeMount(CLUSTER_CA_CERTS_VOLUME, CLUSTER_CA_CERTS_VOLUME_MOUNT)); volumeMountList.add(createVolumeMount(BROKER_CERTS_VOLUME, BROKER_CERTS_VOLUME_MOUNT)); volumeMountList.add(createVolumeMount(CLIENT_CA_CERTS_VOLUME, CLIENT_CA_CERTS_VOLUME_MOUNT)); volumeMountList.add(createVolumeMount(logAndMetricsConfigVolumeName, logAndMetricsConfigMountPath)); if (rack != null || isExposedWithNodePort()) { volumeMountList.add(createVolumeMount(INIT_VOLUME_NAME, INIT_VOLUME_MOUNT)); } return volumeMountList; } /** * Returns a combined affinity: Adding the affinity needed for the "kafka-rack" to the {@link #getUserAffinity()}. */ @Override protected Affinity getMergedAffinity() { Affinity userAffinity = getUserAffinity(); AffinityBuilder builder = new AffinityBuilder(userAffinity == null ? new Affinity() : userAffinity); if (rack != null) { // If there's a rack config, we need to add a podAntiAffinity to spread the brokers among the racks builder = builder .editOrNewPodAntiAffinity() .addNewPreferredDuringSchedulingIgnoredDuringExecution() .withWeight(100) .withNewPodAffinityTerm() .withTopologyKey(rack.getTopologyKey()) .withNewLabelSelector() .addToMatchLabels(Labels.STRIMZI_CLUSTER_LABEL, cluster) .addToMatchLabels(Labels.STRIMZI_NAME_LABEL, name) .endLabelSelector() .endPodAffinityTerm() .endPreferredDuringSchedulingIgnoredDuringExecution() .endPodAntiAffinity(); } return builder.build(); } @Override protected List<Container> getInitContainers(ImagePullPolicy imagePullPolicy) { List<Container> initContainers = new ArrayList<>(); if (rack != null || isExposedWithNodePort()) { ResourceRequirements resources = new ResourceRequirementsBuilder() .addToRequests("cpu", new Quantity("100m")) .addToRequests("memory", new Quantity("128Mi")) .addToLimits("cpu", new Quantity("1")) .addToLimits("memory", new Quantity("256Mi")) .build(); List<EnvVar> varList = new ArrayList<>(); varList.add(buildEnvVarFromFieldRef(ENV_VAR_KAFKA_INIT_NODE_NAME, "spec.nodeName")); if (rack != null) { varList.add(buildEnvVar(ENV_VAR_KAFKA_INIT_RACK_TOPOLOGY_KEY, rack.getTopologyKey())); } if (isExposedWithNodePort()) { varList.add(buildEnvVar(ENV_VAR_KAFKA_INIT_EXTERNAL_ADDRESS, "TRUE")); varList.add(buildEnvVar(ENV_VAR_KAFKA_INIT_EXTERNAL_ADVERTISED_ADDRESSES, String.join(" ", externalAddresses))); } Container initContainer = new ContainerBuilder() .withName(INIT_NAME) .withImage(initImage) .withResources(resources) .withEnv(varList) .withVolumeMounts(createVolumeMount(INIT_VOLUME_NAME, INIT_VOLUME_MOUNT)) .withImagePullPolicy(determineImagePullPolicy(imagePullPolicy, initImage)) .build(); initContainers.add(initContainer); } return initContainers; } @Override protected List<Container> getContainers(ImagePullPolicy imagePullPolicy) { List<Container> containers = new ArrayList<>(); Container container = new ContainerBuilder() .withName(KAFKA_NAME) .withImage(getImage()) .withEnv(getEnvVars()) .withVolumeMounts(getVolumeMounts()) .withPorts(getContainerPortList()) .withLivenessProbe(createTcpSocketProbe(REPLICATION_PORT, livenessInitialDelay, livenessTimeout)) .withReadinessProbe(createTcpSocketProbe(REPLICATION_PORT, readinessInitialDelay, readinessTimeout)) .withResources(ModelUtils.resources(getResources())) .withImagePullPolicy(determineImagePullPolicy(imagePullPolicy, getImage())) .build(); String tlsSidecarImage = KafkaClusterSpec.DEFAULT_TLS_SIDECAR_IMAGE; if (tlsSidecar != null && tlsSidecar.getImage() != null) { tlsSidecarImage = tlsSidecar.getImage(); } Container tlsSidecarContainer = new ContainerBuilder() .withName(TLS_SIDECAR_NAME) .withImage(tlsSidecarImage) .withLivenessProbe(ModelUtils.tlsSidecarLivenessProbe(tlsSidecar)) .withReadinessProbe(ModelUtils.tlsSidecarReadinessProbe(tlsSidecar)) .withResources(ModelUtils.tlsSidecarResources(tlsSidecar)) .withEnv(asList(buildEnvVar(ENV_VAR_KAFKA_ZOOKEEPER_CONNECT, zookeeperConnect), ModelUtils.tlsSidecarLogEnvVar(tlsSidecar))) .withVolumeMounts(createVolumeMount(BROKER_CERTS_VOLUME, TLS_SIDECAR_KAFKA_CERTS_VOLUME_MOUNT), createVolumeMount(CLUSTER_CA_CERTS_VOLUME, TLS_SIDECAR_CLUSTER_CA_CERTS_VOLUME_MOUNT)) .withLifecycle(new LifecycleBuilder().withNewPreStop().withNewExec().withCommand("/opt/stunnel/stunnel_pre_stop.sh", String.valueOf(templateTerminationGracePeriodSeconds)).endExec().endPreStop().build()) .withImagePullPolicy(determineImagePullPolicy(imagePullPolicy, tlsSidecarImage)) .build(); containers.add(container); containers.add(tlsSidecarContainer); return containers; } @Override protected String getServiceAccountName() { return initContainerServiceAccountName(cluster); } @Override protected List<EnvVar> getEnvVars() { List<EnvVar> varList = new ArrayList<>(); varList.add(buildEnvVar(ENV_VAR_KAFKA_METRICS_ENABLED, String.valueOf(isMetricsEnabled))); varList.add(buildEnvVar(ENV_VAR_STRIMZI_KAFKA_GC_LOG_ENABLED, String.valueOf(gcLoggingEnabled))); heapOptions(varList, 0.5, 5L * 1024L * 1024L * 1024L); jvmPerformanceOptions(varList); if (configuration != null && !configuration.getConfiguration().isEmpty()) { varList.add(buildEnvVar(ENV_VAR_KAFKA_CONFIGURATION, configuration.getConfiguration())); } if (listeners != null) { if (listeners.getPlain() != null) { varList.add(buildEnvVar(ENV_VAR_KAFKA_CLIENT_ENABLED, "TRUE")); if (listeners.getPlain().getAuthentication() != null) { varList.add(buildEnvVar(ENV_VAR_KAFKA_CLIENT_AUTHENTICATION, listeners.getPlain().getAuthentication().getType())); } } if (listeners.getTls() != null) { varList.add(buildEnvVar(ENV_VAR_KAFKA_CLIENTTLS_ENABLED, "TRUE")); if (listeners.getTls().getAuth() != null) { varList.add(buildEnvVar(ENV_VAR_KAFKA_CLIENTTLS_AUTHENTICATION, listeners.getTls().getAuth().getType())); } } if (listeners.getExternal() != null) { varList.add(buildEnvVar(ENV_VAR_KAFKA_EXTERNAL_ENABLED, listeners.getExternal().getType())); varList.add(buildEnvVar(ENV_VAR_KAFKA_EXTERNAL_ADDRESSES, String.join(" ", externalAddresses))); varList.add(buildEnvVar(ENV_VAR_KAFKA_EXTERNAL_TLS, Boolean.toString(isExposedWithTls()))); if (listeners.getExternal().getAuth() != null) { varList.add(buildEnvVar(ENV_VAR_KAFKA_EXTERNAL_AUTHENTICATION, listeners.getExternal().getAuth().getType())); } } } if (authorization != null && KafkaAuthorizationSimple.TYPE_SIMPLE.equals(authorization.getType())) { varList.add(buildEnvVar(ENV_VAR_KAFKA_AUTHORIZATION_TYPE, KafkaAuthorizationSimple.TYPE_SIMPLE)); KafkaAuthorizationSimple simpleAuthz = (KafkaAuthorizationSimple) authorization; if (simpleAuthz.getSuperUsers() != null && simpleAuthz.getSuperUsers().size() > 0) { String superUsers = simpleAuthz.getSuperUsers().stream().map(e -> String.format("User:%s", e)).collect(Collectors.joining(";")); varList.add(buildEnvVar(ENV_VAR_KAFKA_AUTHORIZATION_SUPER_USERS, superUsers)); } } String logDirs = dataVolumeMountPaths.stream() .map(volumeMount -> volumeMount.getMountPath()).collect(Collectors.joining(",")); varList.add(buildEnvVar(ENV_VAR_KAFKA_LOG_DIRS, logDirs)); return varList; } protected void setZookeeperConnect(String zookeeperConnect) { this.zookeeperConnect = zookeeperConnect; } protected void setRack(Rack rack) { this.rack = rack; } protected void setInitImage(String initImage) { this.initImage = initImage; } protected void setTlsSidecar(TlsSidecar tlsSidecar) { this.tlsSidecar = tlsSidecar; } @Override protected String getDefaultLogConfigFileName() { return "kafkaDefaultLoggingProperties"; } public ServiceAccount generateInitContainerServiceAccount() { return new ServiceAccountBuilder() .withNewMetadata() .withName(initContainerServiceAccountName(cluster)) .withNamespace(namespace) .withOwnerReferences(createOwnerReference()) .endMetadata() .build(); } /** * Get the name of the kafka service account given the name of the {@code kafkaResourceName}. */ public static String initContainerServiceAccountName(String kafkaResourceName) { return kafkaClusterName(kafkaResourceName); } /** * Get the name of the kafka init container role binding given the name of the {@code namespace} and {@code cluster}. */ public static String initContainerClusterRoleBindingName(String namespace, String cluster) { return "strimzi-" + namespace + "-" + cluster + "-kafka-init"; } public ClusterRoleBindingOperator.ClusterRoleBinding generateClusterRoleBinding(String assemblyNamespace) { if (rack != null || isExposedWithNodePort()) { return new ClusterRoleBindingOperator.ClusterRoleBinding( initContainerClusterRoleBindingName(namespace, cluster), "strimzi-kafka-broker", assemblyNamespace, initContainerServiceAccountName(cluster), createOwnerReference()); } else { return null; } } public static String policyName(String cluster) { return cluster + NETWORK_POLICY_KEY_SUFFIX + NAME_SUFFIX; } public NetworkPolicy generateNetworkPolicy() { List<NetworkPolicyIngressRule> rules = new ArrayList<>(5); // Restrict access to 9091 / replication port NetworkPolicyPort replicationPort = new NetworkPolicyPort(); replicationPort.setPort(new IntOrString(REPLICATION_PORT)); NetworkPolicyPeer kafkaClusterPeer = new NetworkPolicyPeer(); LabelSelector labelSelector = new LabelSelector(); Map<String, String> expressions = new HashMap<>(); expressions.put(Labels.STRIMZI_NAME_LABEL, kafkaClusterName(cluster)); labelSelector.setMatchLabels(expressions); kafkaClusterPeer.setPodSelector(labelSelector); NetworkPolicyPeer entityOperatorPeer = new NetworkPolicyPeer(); LabelSelector labelSelector2 = new LabelSelector(); Map<String, String> expressions2 = new HashMap<>(); expressions2.put(Labels.STRIMZI_NAME_LABEL, EntityOperator.entityOperatorName(cluster)); labelSelector2.setMatchLabels(expressions2); entityOperatorPeer.setPodSelector(labelSelector2); NetworkPolicyIngressRule replicationRule = new NetworkPolicyIngressRuleBuilder() .withPorts(replicationPort) .withFrom(kafkaClusterPeer, entityOperatorPeer) .build(); rules.add(replicationRule); // Free access to 9092, 9093 and 9094 ports if (listeners != null) { if (listeners.getPlain() != null) { NetworkPolicyPort plainPort = new NetworkPolicyPort(); plainPort.setPort(new IntOrString(CLIENT_PORT)); NetworkPolicyIngressRule plainRule = new NetworkPolicyIngressRuleBuilder() .withPorts(plainPort) .withFrom(listeners.getPlain().getNetworkPolicyPeers()) .build(); rules.add(plainRule); } if (listeners.getTls() != null) { NetworkPolicyPort tlsPort = new NetworkPolicyPort(); tlsPort.setPort(new IntOrString(CLIENT_TLS_PORT)); NetworkPolicyIngressRule tlsRule = new NetworkPolicyIngressRuleBuilder() .withPorts(tlsPort) .withFrom(listeners.getTls().getNetworkPolicyPeers()) .build(); rules.add(tlsRule); } if (isExposed()) { NetworkPolicyPort externalPort = new NetworkPolicyPort(); externalPort.setPort(new IntOrString(EXTERNAL_PORT)); NetworkPolicyIngressRule externalRule = new NetworkPolicyIngressRuleBuilder() .withPorts(externalPort) .withFrom(listeners.getExternal().getNetworkPolicyPeers()) .build(); rules.add(externalRule); } } if (isMetricsEnabled) { NetworkPolicyPort metricsPort = new NetworkPolicyPort(); metricsPort.setPort(new IntOrString(METRICS_PORT)); NetworkPolicyIngressRule metricsRule = new NetworkPolicyIngressRuleBuilder() .withPorts(metricsPort) .withFrom() .build(); rules.add(metricsRule); } NetworkPolicy networkPolicy = new NetworkPolicyBuilder() .withNewMetadata() .withName(policyName(cluster)) .withNamespace(namespace) .withLabels(labels.toMap()) .withOwnerReferences(createOwnerReference()) .endMetadata() .withNewSpec() .withPodSelector(labelSelector) .withIngress(rules) .endSpec() .build(); log.trace("Created network policy {}", networkPolicy); return networkPolicy; } /** * Generates the PodDisruptionBudget * * @return */ public PodDisruptionBudget generatePodDisruptionBudget() { return createPodDisruptionBudget(); } /** * Sets the object with Kafka listeners configuration * * @param listeners */ public void setListeners(KafkaListeners listeners) { this.listeners = listeners; } /** * Sets the object with Kafka authorization configuration * * @param authorization */ public void setAuthorization(KafkaAuthorization authorization) { this.authorization = authorization; } /** * Sets the Map with Kafka pod's external addresses * * @param externalAddresses Set with external addresses */ public void setExternalAddresses(Set<String> externalAddresses) { this.externalAddresses = externalAddresses; } /** * Returns true when the Kafka cluster is exposed to the outside of OpenShift / Kubernetes * * @return */ public boolean isExposed() { return listeners != null && listeners.getExternal() != null; } /** * Returns true when the Kafka cluster is exposed to the outside of OpenShift using OpenShift routes * * @return */ public boolean isExposedWithRoute() { return isExposed() && listeners.getExternal() instanceof KafkaListenerExternalRoute; } /** * Returns true when the Kafka cluster is exposed to the outside using LoadBalancers * * @return */ public boolean isExposedWithLoadBalancer() { return isExposed() && listeners.getExternal() instanceof KafkaListenerExternalLoadBalancer; } /** * Returns true when the Kafka cluster is exposed to the outside using NodePort type services * * @return */ public boolean isExposedWithNodePort() { return isExposed() && listeners.getExternal() instanceof KafkaListenerExternalNodePort; } /** * Returns the list broker overrides for external listeners * * @return */ private List<ExternalListenerBrokerOverride> getExternalListenerBrokerOverride() { List<ExternalListenerBrokerOverride> brokerOverride = new ArrayList<>(); if (isExposedWithNodePort()) { NodePortListenerOverride overrides = ((KafkaListenerExternalNodePort) listeners.getExternal()).getOverrides(); if (overrides != null && overrides.getBrokers() != null) { brokerOverride.addAll(overrides.getBrokers()); } } else if (isExposedWithLoadBalancer()) { LoadBalancerListenerOverride overrides = ((KafkaListenerExternalLoadBalancer) listeners.getExternal()).getOverrides(); if (overrides != null && overrides.getBrokers() != null) { brokerOverride.addAll(overrides.getBrokers()); } } else if (isExposedWithRoute()) { RouteListenerOverride overrides = ((KafkaListenerExternalRoute) listeners.getExternal()).getOverrides(); if (overrides != null && overrides.getBrokers() != null) { brokerOverride.addAll(overrides.getBrokers()); } } return brokerOverride; } /** * Returns the bootstrap override for external listeners * * @return */ public ExternalListenerBootstrapOverride getExternalListenerBootstrapOverride() { ExternalListenerBootstrapOverride bootstrapOverride = null; if (isExposedWithNodePort()) { NodePortListenerOverride overrides = ((KafkaListenerExternalNodePort) listeners.getExternal()).getOverrides(); if (overrides != null) { bootstrapOverride = overrides.getBootstrap(); } } else if (isExposedWithLoadBalancer()) { LoadBalancerListenerOverride overrides = ((KafkaListenerExternalLoadBalancer) listeners.getExternal()).getOverrides(); if (overrides != null) { bootstrapOverride = overrides.getBootstrap(); } } else if (isExposedWithRoute()) { RouteListenerOverride overrides = ((KafkaListenerExternalRoute) listeners.getExternal()).getOverrides(); if (overrides != null) { bootstrapOverride = overrides.getBootstrap(); } } return bootstrapOverride; } /** * Returns advertised address of external nodeport service * * @return */ public String getExternalServiceAdvertisedHostOverride(int podNumber) { String advertisedHost = null; List<ExternalListenerBrokerOverride> brokerOverride = getExternalListenerBrokerOverride(); advertisedHost = brokerOverride.stream() .filter(brokerService -> brokerService != null && brokerService.getBroker() == podNumber && brokerService.getAdvertisedHost() != null) .map(ExternalListenerBrokerOverride::getAdvertisedHost) .findAny() .orElse(null); if (advertisedHost != null && advertisedHost.isEmpty()) { advertisedHost = null; } return advertisedHost; } /** * Returns advertised address of external nodeport service * * @return */ public Integer getExternalServiceAdvertisedPortOverride(int podNumber) { Integer advertisedPort = null; List<ExternalListenerBrokerOverride> brokerOverride = getExternalListenerBrokerOverride(); advertisedPort = brokerOverride.stream() .filter(brokerService -> brokerService != null && brokerService.getBroker() == podNumber && brokerService.getAdvertisedPort() != null) .map(ExternalListenerBrokerOverride::getAdvertisedPort) .findAny() .orElse(null); if (advertisedPort != null && advertisedPort == 0) { advertisedPort = null; } return advertisedPort; } /** * Returns the advertised URL for given pod. * It will take into account the overrides specified by the user. * If some segment is not know - e.g. the hostname for the NodePort access, it should be left empty * * @param podNumber Pod index * @param address The advertised hostname * @param port The advertised port * @return The advertised URL in format podNumber://address:port (e.g. 1://my-broker-1:9094) */ public String getExternalAdvertisedUrl(int podNumber, String address, String port) { String advertisedHost = getExternalServiceAdvertisedHostOverride(podNumber); Integer advertisedPort = getExternalServiceAdvertisedPortOverride(podNumber); String url = String.valueOf(podNumber) + "://" + (advertisedHost != null ? advertisedHost : address) + ":" + (advertisedPort != null ? advertisedPort : port); return url; } /** * Returns true when the Kafka cluster is exposed to the outside of OpenShift with TLS enabled * * @return */ public boolean isExposedWithTls() { if (isExposed() && listeners.getExternal() instanceof KafkaListenerExternalRoute) { return true; } else if (isExposed()) { if (listeners.getExternal() instanceof KafkaListenerExternalLoadBalancer) { return ((KafkaListenerExternalLoadBalancer) listeners.getExternal()).isTls(); } else if (listeners.getExternal() instanceof KafkaListenerExternalNodePort) { return ((KafkaListenerExternalNodePort) listeners.getExternal()).isTls(); } } return false; } @Override public KafkaConfiguration getConfiguration() { return (KafkaConfiguration) configuration; } }
package com.ray3k.skincomposer.dialog.scenecomposer; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.ui.*; import com.badlogic.gdx.utils.*; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.ReflectionException; import com.ray3k.skincomposer.Main; import com.ray3k.skincomposer.data.ColorData; import com.ray3k.skincomposer.data.DrawableData; import com.ray3k.skincomposer.data.StyleData; import com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposer.View; import com.ray3k.skincomposer.dialog.scenecomposer.undoables.SceneComposerUndoable; import javax.xml.crypto.Data; import java.util.Locale; import static com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposer.dialog; public class DialogSceneComposerModel { private transient Main main; public transient Array<SceneComposerUndoable> undoables; public transient Array<SceneComposerUndoable> redoables; public static SimRootGroup rootActor; public transient Stack preview; private static Json json; private final static Vector2 temp = new Vector2(); public enum Interpol { LINEAR(Interpolation.linear, "Linear", "linear"), SMOOTH(Interpolation.smooth, "Smooth", "smooth"), SMOOTH2( Interpolation.smooth2, "Smooth 2", "smooth2"), SMOOTHER(Interpolation.smoother, "Smoother", "smoother"), FADE(Interpolation.fade, "Fade", "fade"), POW2( Interpolation.pow2, "Pow 2", "pow2"), POW2IN(Interpolation.pow2In, "Pow 2 In", "pow2In"), SLOW_FAST(Interpolation.slowFast, "Slow Fast", "slowFast"), POW2OUT(Interpolation.pow2Out, "Pow 2 Out", "pow2Out"), FAST_SLOW(Interpolation.fastSlow, "Fast Slow", "fastSlow"), POW2IN_INVERSE(Interpolation.pow2In, "Pow 2 In Inverse", "pow2In"), POW2OUT_INVERSE(Interpolation.pow2OutInverse, "Pow 2 Out Inverse", "pow2OutInverse"), POW3(Interpolation.pow3, "Pow 3", "pow3"), POW3IN(Interpolation.pow3In, "Pow 3 In", "pow3In"), POW3OUT(Interpolation.pow3Out, "Pow 3 Out", "pow3Out"), POW3IN_INVERSE(Interpolation.pow3InInverse, "Pow 3 In Inverse", "pow3InInverse"), POW3OUT_INVERSE(Interpolation.pow3OutInverse, "Pow 3 Out Inverse", "pow3OutInverse"), POW4(Interpolation.pow4, "Pow 4", "pow4"), POW4IN(Interpolation.pow4In, "Pow 4 In", "pow4In"), POW4OUT(Interpolation.pow4Out, "Pow 4 Out", "pow4Out"), POW5(Interpolation.pow5, "Pow 5", "pow5"), POW5IN( Interpolation.pow5In, "Pow 5 In", "pow5In"), POW5OUT(Interpolation.pow5Out, "Pow 5 Out", "pow5Out"), SINE(Interpolation.sine, "Sine", "sine"), SINE_IN( Interpolation.sineIn, "Sine In", "sineIn"), SINE_OUT(Interpolation.sineOut, "Sine Out", "sineOut"), EXP10(Interpolation.exp10, "Exp 10", "exp10"), EXP10_IN( Interpolation.exp10In, "Exp 10 In", "exp10In"), EXP10_OUT(Interpolation.exp10Out, "Exp 10 Out", "exp10Out"), EXP5(Interpolation.exp5, "Exp 5", "exp5"), EXP5IN( Interpolation.exp5In, "Exp 5 In", "exp5In"), EXP5OUT(Interpolation.exp5Out, "Exp 5 Out", "exp5Out"), CIRCLE(Interpolation.circle, "Circle", "circle"), CIRCLE_IN(Interpolation.circleIn, "Circle In", "circleIn"), CIRCLE_OUT(Interpolation.circleOut, "Circle Out", "circleOut"), ELASTIC(Interpolation.elastic, "Elastic", "elastic"), ELASTIC_IN(Interpolation.elasticIn, "Elastic In", "elasticIn"), ELASTIC_OUT(Interpolation.elasticOut, "Elastic Out", "elasticOut"), SWING(Interpolation.swing, "Swing", "swing"), SWING_IN(Interpolation.swingIn, "Swing In", "swingIn"), SWING_OUT(Interpolation.swingOut, "Swing Out", "swingOut"), BOUNCE(Interpolation.bounce, "Bounce", "bounce"), BOUNCE_IN(Interpolation.bounceIn, "Bounce In", "bounceIn"), BOUNCE_OUT(Interpolation.bounceOut, " Bounce Out", "bounceOut"); public Interpolation interpolation; public String text; public String code; Interpol(Interpolation interpolation, String text, String code) { this.interpolation = interpolation; this.text = text; this.code = code; } @Override public String toString() { return text; } } public DialogSceneComposerModel() { undoables = new Array<>(); redoables = new Array<>(); preview = new Stack(); main = Main.main; json = new Json(); json.setSerializer(ColorData.class, new Json.Serializer<>() { @Override public void write(Json json, ColorData object, Class knownType) { json.writeValue(object.getName()); } @Override public ColorData read(Json json, JsonValue jsonData, Class type) { return Main.main.getJsonData().getColorByName(jsonData.asString()); } }); json.setSerializer(DrawableData.class, new Json.Serializer<>() { @Override public void write(Json json, DrawableData object, Class knownType) { json.writeValue(object.name); } @Override public DrawableData read(Json json, JsonValue jsonData, Class type) { return Main.main.getAtlasData().getDrawable(jsonData.asString()); } }); json.setSerializer(StyleData.class, new Json.Serializer<>() { @Override public void write(Json json, StyleData object, Class knownType) { json.writeObjectStart(); json.writeValue("clazz", object.clazz.getName()); json.writeValue("name", object.name); json.writeObjectEnd(); } @Override public StyleData read(Json json, JsonValue jsonData, Class type) { try { return Main.main.getJsonData().findStyle(ClassReflection.forName(jsonData.getString("clazz")), jsonData.getString("name")); } catch (ReflectionException e) { e.printStackTrace(); return null; } } }); json.setOutputType(JsonWriter.OutputType.json); json.setUsePrototypes(false); json.addClassTag("Actor", SimActor.class); json.addClassTag("Button", SimButton.class); json.addClassTag("Cell", SimCell.class); json.addClassTag("CheckBox", SimCheckBox.class); json.addClassTag("Container", SimContainer.class); json.addClassTag("HorizontalGroup", SimHorizontalGroup.class); json.addClassTag("Image", SimImage.class); json.addClassTag("ImageButton", SimImageButton.class); json.addClassTag("ImageTextButton", SimImageTextButton.class); json.addClassTag("Label", SimLabel.class); json.addClassTag("List", SimList.class); json.addClassTag("Node", SimNode.class); json.addClassTag("ProgressBar", SimProgressBar.class); json.addClassTag("Root", SimRootGroup.class); json.addClassTag("ScrollPane", SimScrollPane.class); json.addClassTag("SelectBox", SimSelectBox.class); json.addClassTag("Slider", SimSlider.class); json.addClassTag("SplitPane", SimSplitPane.class); json.addClassTag("Stack", SimStack.class); json.addClassTag("Table", SimTable.class); json.addClassTag("TextArea", SimTextArea.class); json.addClassTag("TextButton", SimTextButton.class); json.addClassTag("TextField", SimTextField.class); json.addClassTag("TouchPad", SimTouchPad.class); json.addClassTag("Tree", SimTree.class); json.addClassTag("VerticalGroup", SimVerticalGroup.class); if (rootActor == null) rootActor = new SimRootGroup(); assignParentRecursive(rootActor); primeStyles(); } private void primeStyles() { primeStyles(rootActor); } private void primeStyles(SimActor simActor) { for (var field : ClassReflection.getFields(simActor.getClass())) { if (field.getType() == StyleData.class) { try { var style = (StyleData) field.get(simActor); var foundStyle = main.getJsonData().findStyle(style.clazz, style.name); if (foundStyle == null) foundStyle = main.getJsonData().findStyle(style.clazz, "default"); if (foundStyle == null) foundStyle = main.getJsonData().findStyle(style.clazz, "default-horizontal"); field.set(simActor, foundStyle); } catch (ReflectionException e) { e.printStackTrace(System.out); } } else if (field.getType() == DrawableData.class) { try { var drawable = (DrawableData) field.get(simActor); var foundDrawable = main.getAtlasData().getDrawable(drawable.name); field.set(simActor, foundDrawable); } catch (ReflectionException e) { e.printStackTrace(System.out); } } } if (simActor instanceof SimMultipleChildren) { for (var child : ((SimMultipleChildren) simActor).getChildren()) { if (child != null) primeStyles(child); } } if (simActor instanceof SimSingleChild) { var child = ((SimSingleChild) simActor).getChild(); if (child != null) primeStyles(child); } } public static void saveToJson(FileHandle saveFile) { if (!saveFile.extension().toLowerCase(Locale.ROOT).equals("json")) { saveFile = saveFile.sibling(saveFile.nameWithoutExtension() + ".json"); } saveFile.writeString(json.prettyPrint(rootActor), false); } public static void loadFromJson(FileHandle loadFile) { rootActor = json.fromJson(SimRootGroup.class, loadFile); assignParentRecursive(rootActor); } public void undo() { if (undoables.size > 0) { var undoable = undoables.pop(); redoables.add(undoable); undoable.undo(); var fadeLabel = new FadeLabel(undoable.getUndoString(), main.getSkin(), "scene-edit-tip"); temp.set(dialog.previewTable.getWidth() / 2, dialog.previewTable.getHeight() / 2); dialog.previewTable.localToStageCoordinates(temp); fadeLabel.setPosition(temp.x - (int) fadeLabel.getWidth() / 2, temp.y - (int) fadeLabel.getHeight() / 2); main.getStage().addActor(fadeLabel); } } public void redo() { if (redoables.size > 0) { var undoable = redoables.pop(); undoables.add(undoable); undoable.redo(); } } public void updatePreview() { preview.clearChildren(); switch (dialog.view) { case LIVE: createPreviewWidgets(); preview.setDebug(false, true); break; case EDIT: createPreviewWidgets(); createEditWidgets(); preview.setDebug(false, true); break; case OUTLINE: createPreviewWidgets(); preview.debugAll(); break; } } private void createEditWidgets() { if (dialog.simActor.parent != null) { var edit = new EditWidget(main.getSkin(), "scene-select-back"); edit.setFillParent(true); edit.setSimActorTarget(dialog.simActor.parent); preview.add(edit); } if (dialog.simActor instanceof SimRootGroup) { var simGroup = (SimRootGroup) dialog.simActor; var edit = new EditWidget(main.getSkin(), "scene-selection"); edit.setFillParent(true); edit.setSimActorTarget(dialog.simActor.parent); preview.add(edit); if (simGroup.children.size > 0) { edit = new EditWidget(main.getSkin(), "scene-selector"); edit.setFillParent(true); edit.setSimActorTarget(simGroup.children.peek()); preview.add(edit); } } else if (dialog.simActor instanceof SimTable) { var edit = new EditWidget(main.getSkin(), "scene-selection"); edit.setFollowActor(dialog.simActor.previewActor); edit.setSimActorTarget(dialog.simActor.parent); preview.add(edit); var simTable = (SimTable) dialog.simActor; for (var simCell : simTable.cells) { var table = (Table) simTable.previewActor; var cell = table.getCells().get(simCell.row * table.getColumns() + simCell.column); edit = new EditWidget(main.getSkin(), "scene-selector"); edit.setCell(cell); edit.setSimActorTarget(simCell); preview.add(edit); } } else if (dialog.simActor instanceof SimCell) { var simCell = (SimCell) dialog.simActor; var table = (Table) ((SimTable) simCell.parent).previewActor; var cell = table.getCells().get(simCell.row * table.getColumns() + simCell.column); var edit = new EditWidget(main.getSkin(), "scene-selection"); edit.setCell(cell); edit.setSimActorTarget(dialog.simActor.parent); preview.add(edit); if (simCell.child != null) { edit = new EditWidget(main.getSkin(), "scene-selector"); edit.setFollowActor(simCell.child.previewActor); edit.setSimActorTarget(simCell.child); preview.add(edit); } } else if (dialog.simActor.previewActor != null) { var edit = new EditWidget(main.getSkin(), "scene-selection"); edit.setFollowActor(dialog.simActor.previewActor); edit.setSimActorTarget(dialog.simActor.parent); preview.add(edit); if (dialog.simActor instanceof SimSingleChild) { var child = ((SimSingleChild) dialog.simActor).getChild(); if (child != null) { edit = new EditWidget(main.getSkin(), "scene-selector"); edit.setFollowActor(child.previewActor); edit.setSimActorTarget(child); preview.add(edit); } } if (dialog.simActor instanceof SimMultipleChildren) { var children = ((SimMultipleChildren) dialog.simActor).getChildren(); for (var child : children) { edit = new EditWidget(main.getSkin(), "scene-selector"); edit.setFollowActor(child.previewActor); edit.setSimActorTarget(child); preview.add(edit); } } } } private void createPreviewWidgets() { for (var simActor : rootActor.children) { var actor = createPreviewWidget(simActor); if (actor != null) { preview.addActor(actor); } } } private Actor createPreviewWidget(SimActor simActor) { Actor actor = null; if (simActor instanceof SimTable) { var simTable = (SimTable) simActor; var table = new Table(); actor = table; table.setName(simTable.name); if (simTable.background != null) { table.setBackground(main.getAtlasData().getDrawablePairs().get(simTable.background)); } if (simTable.color != null) { table.setColor(simTable.color.color); } table.pad(simTable.padTop, simTable.padLeft, simTable.padBottom, simTable.padRight); table.align(simTable.alignment); table.setFillParent(simTable.fillParent); int row = 0; for (var simCell : simTable.cells) { if (simCell.row > row) { table.row(); row = simCell.row; } var child = createPreviewWidget(simCell.child); var cell = table.add(child).fill(simCell.fillX, simCell.fillY).expand(simCell.expandX, simCell.expandY); cell.pad(simCell.padTop, simCell.padLeft, simCell.padBottom, simCell.padRight); cell.space(simCell.spaceTop, simCell.spaceLeft, simCell.spaceBottom, simCell.spaceRight); cell.align(simCell.alignment).uniform(simCell.uniformX, simCell.uniformY).colspan(simCell.colSpan); if (simCell.minWidth >= 0) { cell.minWidth(simCell.minWidth); } if (simCell.minHeight >= 0) { cell.minHeight(simCell.minHeight); } if (simCell.maxWidth >= 0) { cell.maxWidth(simCell.maxWidth); } if (simCell.maxHeight >= 0) { cell.maxHeight(simCell.maxHeight); } if (simCell.preferredWidth >= 0) { cell.prefWidth(simCell.preferredWidth); } if (simCell.preferredHeight >= 0) { cell.prefHeight(simCell.preferredHeight); } } if (dialog.view == View.EDIT && table.getCells().size == 0) table.add().size(50, 50); } else if (simActor instanceof SimTextButton) { var simTextButton = (SimTextButton) simActor; if (simTextButton.style != null && simTextButton.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(TextButton.TextButtonStyle.class, simTextButton.style); var textButton = new TextButton(simTextButton.text == null ? "" : simTextButton.text, style); textButton.setName(simTextButton.name); textButton.setChecked(simTextButton.checked); textButton.setDisabled(simTextButton.disabled); if (simTextButton.color != null) { textButton.setColor(simTextButton.color.color); } textButton.pad(simTextButton.padTop, simTextButton.padLeft, simTextButton.padBottom, simTextButton.padRight); textButton.addListener(main.getHandListener()); actor = textButton; } } else if (simActor instanceof SimButton) { var simButton = (SimButton) simActor; if (simButton.style != null && simButton.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(Button.ButtonStyle.class, simButton.style); var button = new Button(style); button.setName(simButton.name); button.setChecked(simButton.checked); button.setDisabled(simButton.disabled); if (simButton.color != null) { button.setColor(simButton.color.color); } button.pad(simButton.padTop, simButton.padLeft, simButton.padBottom, simButton.padRight); button.addListener(main.getHandListener()); actor = button; } } else if (simActor instanceof SimImageButton) { var simImageButton = (SimImageButton) simActor; if (simImageButton.style != null && simImageButton.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(ImageButton.ImageButtonStyle.class, simImageButton.style); var imageButton = new ImageButton(style); imageButton.setName(simImageButton.name); imageButton.setChecked(simImageButton.checked); imageButton.setDisabled(simImageButton.disabled); if (simImageButton.color != null) { imageButton.setColor(simImageButton.color.color); } imageButton.pad(simImageButton.padTop, simImageButton.padLeft, simImageButton.padBottom, simImageButton.padRight); imageButton.addListener(main.getHandListener()); actor = imageButton; } } else if (simActor instanceof SimImageTextButton) { var simImageTextButton = (SimImageTextButton) simActor; if (simImageTextButton.style != null && simImageTextButton.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(ImageTextButton.ImageTextButtonStyle.class, simImageTextButton.style); var imageTextButton = new ImageTextButton(simImageTextButton.text == null ? "" : simImageTextButton.text, style); imageTextButton.setName(simImageTextButton.name); imageTextButton.setChecked(simImageTextButton.checked); imageTextButton.setDisabled(simImageTextButton.disabled); if (simImageTextButton.color != null) { imageTextButton.setColor(simImageTextButton.color.color); } imageTextButton.pad(simImageTextButton.padTop, simImageTextButton.padLeft, simImageTextButton.padBottom, simImageTextButton.padRight); imageTextButton.addListener(main.getHandListener()); actor = imageTextButton; } } else if (simActor instanceof SimCheckBox) { var simCheckBox = (SimCheckBox) simActor; if (simCheckBox.style != null && simCheckBox.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(CheckBox.CheckBoxStyle.class, simCheckBox.style); var checkBox = new CheckBox(simCheckBox.text == null ? "" : simCheckBox.text, style); checkBox.setName(simCheckBox.name); checkBox.setChecked(simCheckBox.checked); checkBox.setDisabled(simCheckBox.disabled); if (simCheckBox.color != null) { checkBox.setColor(simCheckBox.color.color); } checkBox.pad(simCheckBox.padTop, simCheckBox.padLeft, simCheckBox.padBottom, simCheckBox.padRight); checkBox.addListener(main.getHandListener()); actor = checkBox; } } else if (simActor instanceof SimImage) { var simImage = (SimImage) simActor; if (simImage.drawable != null) { var image = new Image(main.getAtlasData().getDrawablePairs().get(simImage.drawable)); image.setScaling(simImage.scaling); actor = image; } } else if (simActor instanceof SimLabel) { var simLabel = (SimLabel) simActor; if (simLabel.style != null && simLabel.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(Label.LabelStyle.class, simLabel.style); var label = new Label(simLabel.text == null ? "" : simLabel.text, style); label.setName(simLabel.name); label.setAlignment(simLabel.textAlignment); if (simLabel.ellipsis) { label.setEllipsis(simLabel.ellipsisString); } label.setWrap(simLabel.wrap); if (simLabel.color != null) label.setColor(simLabel.color.color); actor = label; } } else if (simActor instanceof SimList) { var simList = (SimList) simActor; if (simList.style != null && simList.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(List.ListStyle.class, simList.style); var list = new List<String>(style); list.setName(simList.name); list.setItems(simList.list); actor = list; } } else if (simActor instanceof SimProgressBar) { var sim = (SimProgressBar) simActor; if (sim.style != null && sim.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(ProgressBar.ProgressBarStyle.class, sim.style); var progressBar = new ProgressBar(sim.minimum, sim.maximum, sim.increment, sim.vertical, style); progressBar.setName(sim.name); progressBar.setDisabled(sim.disabled); progressBar.setValue(sim.value); progressBar.setAnimateDuration(sim.animationDuration); progressBar.setAnimateInterpolation(sim.animateInterpolation.interpolation); progressBar.setRound(sim.round); progressBar.setVisualInterpolation(sim.visualInterpolation.interpolation); actor = progressBar; } } else if (simActor instanceof SimSelectBox) { var sim = (SimSelectBox) simActor; if (sim.list.size > 0 && sim.style != null && sim.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(SelectBox.SelectBoxStyle.class, sim.style); var selectBox = new SelectBox<String>(style); selectBox.setName(sim.name); selectBox.setDisabled(sim.disabled); selectBox.setMaxListCount(sim.maxListCount); selectBox.setItems(sim.list); selectBox.setAlignment(sim.alignment); selectBox.setSelectedIndex(sim.selected); selectBox.setScrollingDisabled(sim.scrollingDisabled); actor = selectBox; } } else if (simActor instanceof SimSlider) { var sim = (SimSlider) simActor; if (sim.style != null && sim.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(Slider.SliderStyle.class, sim.style); var slider = new Slider(sim.minimum, sim.maximum, sim.increment, sim.vertical, style); slider.setName(sim.name); slider.setDisabled(sim.disabled); slider.setValue(sim.value); slider.setAnimateDuration(sim.animationDuration); slider.setAnimateInterpolation(sim.animateInterpolation.interpolation); slider.setRound(sim.round); slider.setVisualInterpolation(sim.visualInterpolation.interpolation); actor = slider; } } else if (simActor instanceof SimTextField) { var sim = (SimTextField) simActor; if (sim.style != null && sim.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(TextField.TextFieldStyle.class, sim.style); var textField = new TextField(sim.text == null ? "" : sim.text, style); textField.setName(sim.name); textField.setPasswordCharacter(sim.passwordCharacter); textField.setPasswordMode(sim.passwordMode); textField.setAlignment(sim.alignment); textField.setDisabled(sim.disabled); textField.setCursorPosition(sim.cursorPosition); if (sim.selectAll) { textField.setSelection(0, Math.max(textField.getText().length() - 1, 0)); } else { textField.setSelection(sim.selectionStart, sim.selectionEnd); } textField.setFocusTraversal(sim.focusTraversal); textField.setMaxLength(sim.maxLength); textField.setMessageText(sim.messageText); actor = textField; } } else if (simActor instanceof SimTextArea) { var sim = (SimTextArea) simActor; if (sim.style != null && sim.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(TextField.TextFieldStyle.class, sim.style); var textArea = new TextArea(sim.text == null ? "" : sim.text, style); textArea.setName(sim.name); textArea.setPasswordCharacter(sim.passwordCharacter); textArea.setPasswordMode(sim.passwordMode); textArea.setAlignment(sim.alignment); textArea.setDisabled(sim.disabled); textArea.setCursorPosition(sim.cursorPosition); if (sim.selectAll) { textArea.setSelection(0, textArea.getText().length() - 1); } else { textArea.setSelection(sim.selectionStart, sim.selectionEnd); } textArea.setFocusTraversal(sim.focusTraversal); textArea.setMaxLength(sim.maxLength); textArea.setMessageText(sim.messageText); textArea.setPrefRows(sim.preferredRows); actor = textArea; } } else if (simActor instanceof SimTouchPad) { var sim = (SimTouchPad) simActor; if (sim.style != null && sim.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(Touchpad.TouchpadStyle.class, sim.style); var touchPad = new Touchpad(sim.deadZone, style); touchPad.setResetOnTouchUp(sim.resetOnTouchUp); actor = touchPad; } } else if (simActor instanceof SimContainer) { var sim = (SimContainer) simActor; var container = new Container(); container.align(sim.alignment); if (sim.background != null) { container.setBackground(main.getAtlasData().drawablePairs.get(sim.background)); } container.fill(sim.fillX, sim.fillY); if (sim.minWidth > 0) container.minWidth(sim.minWidth); if (sim.minHeight > 0) container.minHeight(sim.minHeight); if (sim.maxWidth > 0) container.maxWidth(sim.maxWidth); if (sim.maxHeight > 0) container.maxHeight(sim.maxHeight); if (sim.preferredWidth > 0) container.prefWidth(sim.preferredWidth); if (sim.preferredHeight > 0) container.prefHeight(sim.preferredHeight); container.padLeft(sim.padLeft); container.padRight(sim.padRight); container.padTop(sim.padTop); container.padBottom(sim.padBottom); if (sim.child != null || dialog.view == View.EDIT) container.setActor(createPreviewWidget(sim.child)); actor = container; } else if (simActor instanceof SimHorizontalGroup) { var sim = (SimHorizontalGroup) simActor; var horizontalGroup = new HorizontalGroup(); horizontalGroup.align(sim.alignment); horizontalGroup.expand(sim.expand); horizontalGroup.fill(sim.fill ? 1f : 0f); horizontalGroup.padLeft(sim.padLeft); horizontalGroup.padRight(sim.padRight); horizontalGroup.padTop(sim.padTop); horizontalGroup.padBottom(sim.padBottom); horizontalGroup.reverse(sim.reverse); horizontalGroup.rowAlign(sim.rowAlignment); horizontalGroup.space(sim.space); horizontalGroup.wrap(sim.wrap); horizontalGroup.wrapSpace(sim.wrapSpace); for (var child : sim.children) { var widget = createPreviewWidget(child); if ( widget != null) { horizontalGroup.addActor(widget); } } if (dialog.view == View.EDIT && sim.children.size == 0) { var container = new Container(); container.prefSize(50); horizontalGroup.addActor(container); } actor = horizontalGroup; } else if (simActor instanceof SimScrollPane) { var sim = (SimScrollPane) simActor; if (sim.style != null && sim.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(ScrollPane.ScrollPaneStyle.class, sim.style); var scrollPane = new ScrollPane(createPreviewWidget(sim.child), style); scrollPane.setName(sim.name); scrollPane.setFadeScrollBars(sim.fadeScrollBars); scrollPane.setClamp(sim.clamp); scrollPane.setFlickScroll(sim.flickScroll); scrollPane.setFlingTime(sim.flingTime); scrollPane.setForceScroll(sim.forceScrollX, sim.forceScrollY); scrollPane.setOverscroll(sim.overScrollX, sim.overScrollY); scrollPane.setupOverscroll(sim.overScrollDistance, sim.overScrollSpeedMin, sim.overScrollSpeedMax); scrollPane.setScrollBarPositions(sim.scrollBarBottom, sim.scrollBarRight); scrollPane.setScrollbarsOnTop(sim.scrollBarsOnTop); scrollPane.setScrollbarsVisible(sim.scrollBarsVisible); scrollPane.setScrollBarTouch(sim.scrollBarTouch); scrollPane.setScrollingDisabled(sim.scrollingDisabledX, sim.scrollingDisabledY); scrollPane.setSmoothScrolling(sim.smoothScrolling); scrollPane.setVariableSizeKnobs(sim.variableSizeKnobs); actor = scrollPane; } } else if (simActor instanceof SimStack) { var sim = (SimStack) simActor; var stack = new Stack(); stack.setName(sim.name); for (var child : sim.children) { stack.add(createPreviewWidget(child)); } if (sim.children.size == 0) { var container = new Container(); container.prefSize(50); stack.add(container); } actor = stack; } else if (simActor instanceof SimSplitPane) { var sim = (SimSplitPane) simActor; if (sim.style != null && sim.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(SplitPane.SplitPaneStyle.class, sim.style); var splitPane = new SplitPane(createPreviewWidget(sim.childFirst), createPreviewWidget(sim.childSecond), sim.vertical, style); splitPane.setName(sim.name); splitPane.setSplitAmount(sim.split); splitPane.setMinSplitAmount(sim.splitMin); splitPane.setMaxSplitAmount(sim.splitMax); actor = splitPane; } } else if (simActor instanceof SimTree) { var sim = (SimTree) simActor; if (sim.style != null && sim.style.hasMandatoryFields()) { var style = main.getRootTable().createPreviewStyle(Tree.TreeStyle.class, sim.style); var tree = new Tree(style); tree.setName(sim.name); tree.setPadding(sim.padLeft, sim.padRight); tree.setIconSpacing(sim.iconSpaceLeft, sim.iconSpaceRight); tree.setIndentSpacing(sim.indentSpacing); tree.setYSpacing(sim.ySpacing); for (var child : sim.children) { Tree.Node node = createPreviewNode(child); if (node != null) { tree.add(node); } } if (sim.children.size == 0) { Tree.Node node = new GenericNode(); var container = new Container(); container.prefSize(50); node.setActor(container); tree.add(node); } actor = tree; } } else if (simActor instanceof SimVerticalGroup) { var sim = (SimVerticalGroup) simActor; var verticalGroup = new VerticalGroup(); verticalGroup.align(sim.alignment); verticalGroup.expand(sim.expand); verticalGroup.fill(sim.fill ? 1f : 0f); verticalGroup.padLeft(sim.padLeft); verticalGroup.padRight(sim.padRight); verticalGroup.padTop(sim.padTop); verticalGroup.padBottom(sim.padBottom); verticalGroup.reverse(sim.reverse); verticalGroup.columnAlign(sim.columnAlignment); verticalGroup.space(sim.space); verticalGroup.wrap(sim.wrap); verticalGroup.wrapSpace(sim.wrapSpace); for (var child : sim.children) { var widget = createPreviewWidget(child); if (widget != null) verticalGroup.addActor(widget); } if (dialog.view == View.EDIT && sim.children.size == 0) { var container = new Container(); container.prefSize(50); verticalGroup.addActor(container); } actor = verticalGroup; } else if (dialog.view == View.EDIT) { var container = new Container(); container.prefSize(50); actor = container; } if (simActor != null) simActor.previewActor = actor; return actor; } public Tree.Node createPreviewNode(SimNode simNode) { if (simNode.actor != null || dialog.view == View.EDIT) { var node = new GenericNode(); Actor actor = createPreviewWidget(simNode.actor == null && dialog.view == View.EDIT ? new SimActor() : simNode.actor); if (actor == null) return null; node.setActor(actor); if (simNode.icon != null) node.setIcon(main.getAtlasData().drawablePairs.get(simNode.icon)); node.setSelectable(simNode.selectable); for (var child : simNode.nodes) { Tree.Node newNode = createPreviewNode(child); if (newNode != null) { node.add(newNode); } } simNode.previewActor = actor; return node; } return null; } public class GenericNode extends Tree.Node { } public static void assignParentRecursive(SimActor parent) { if (parent instanceof SimSingleChild) { var child = ((SimSingleChild) parent).getChild(); if (child != null) { child.parent = parent; assignParentRecursive(child); } } if (parent instanceof SimMultipleChildren) { for (var child : ((SimMultipleChildren) parent).getChildren()) { child.parent = parent; assignParentRecursive(child); } } } public static class SimActor { public transient SimActor parent; public transient Actor previewActor; public boolean hasChildOfTypeRecursive(Class type) { boolean returnValue = false; if (this instanceof SimSingleChild) { SimActor child = ((SimSingleChild) this).getChild(); if (child != null) { returnValue = ClassReflection.isInstance(type, child) || child.hasChildOfTypeRecursive(type); } } if (!returnValue && this instanceof SimMultipleChildren) { for (var child : ((SimMultipleChildren) this).getChildren()) { if (child != null) { if (returnValue = ClassReflection.isInstance(type, child) || child.hasChildOfTypeRecursive(type)) { break; } } } } return returnValue; } } public interface SimSingleChild { SimActor getChild(); } public interface SimMultipleChildren { Array<? extends SimActor> getChildren(); void addChild(SimActor simActor); void removeChild(SimActor simActor); } public static class SimRootGroup extends SimActor implements SimMultipleChildren { public Array<SimActor> children = new Array<>(); public ColorData backgroundColor; public String skinPath = "skin.json"; public String packageString = "com.mygdx.game"; public String classString = "Core"; @Override public String toString() { return "Group"; } public void reset() { children.clear(); } @Override public Array<SimActor> getChildren() { return children; } @Override public void addChild(SimActor simActor) { children.add(simActor); } @Override public void removeChild(SimActor simActor) { children.removeValue(simActor, true); } } public static class SimTable extends SimActor implements SimMultipleChildren { public Array<SimCell> cells = new Array<>(); public String name; public DrawableData background; public ColorData color; public float padLeft; public float padRight; public float padTop; public float padBottom; public int alignment = Align.center; public boolean fillParent; @Override public String toString() { return name == null ? "Table" : name + " (Table)"; } public void reset() { cells.clear(); name = null; background = null; color = null; padLeft = 0; padRight = 0; padTop = 0; padBottom = 0; alignment = Align.center; } public void sort() { cells.sort((o1, o2) -> { if (o2.row < o1.row) { return 1; } else if (o2.row > o1.row) { return -1; } else if (o2.column < o1.column) { return 1; } else if (o2.column > o1.column) { return -1; } else { return 0; } }); } @Override public Array<SimCell> getChildren() { return cells; } @Override public void addChild(SimActor simActor) { cells.add((SimCell) simActor); } @Override public void removeChild(SimActor simActor) { cells.removeValue((SimCell) simActor, true); } } public static class SimCell extends SimActor implements SimSingleChild { public SimActor child; public int row; public int column; public float padLeft; public float padRight; public float padTop; public float padBottom; public float spaceLeft; public float spaceRight; public float spaceTop; public float spaceBottom; public boolean expandX; public boolean expandY; public boolean fillX; public boolean fillY; public boolean growX; public boolean growY; public int alignment = Align.center; public float minWidth = -1; public float minHeight = -1; public float maxWidth = -1; public float maxHeight = -1; public float preferredWidth = -1; public float preferredHeight = -1; public boolean uniformX; public boolean uniformY; public int colSpan = 1; @Override public String toString() { return "Cell (" + column + "," + row + ")"; } public void reset() { child = null; row = 0; column = 0; padLeft = 0; padRight = 0; padTop = 0; padBottom = 0; spaceLeft = 0; spaceRight = 0; spaceTop = 0; spaceBottom = 0; expandX = false; expandY = false; fillX = false; fillY = false; growX = false; growY = false; alignment = Align.center; minWidth = -1; minHeight = -1; maxWidth = -1; maxHeight = -1; preferredWidth = -1; preferredHeight = -1; uniformX = false; uniformY = false; colSpan = 1; } @Override public SimActor getChild() { return child; } } public static class SimButton extends SimActor { public String name; public StyleData style; public boolean checked; public boolean disabled; public ColorData color; public float padLeft; public float padRight; public float padTop; public float padBottom; public SimButton() { var styles = Main.main.getJsonData().getClassStyleMap().get(Button.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "Button" : name + " (Button)"; } public void reset() { name = null; style = null; var styles = Main.main.getJsonData().getClassStyleMap().get(Button.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } checked = false; disabled = false; color = null; padLeft = 0; padRight = 0; padTop = 0; padBottom = 0; } } public static class SimCheckBox extends SimActor { public String name; public StyleData style; public boolean disabled; public String text; public ColorData color; public float padLeft; public float padRight; public float padTop; public float padBottom; public boolean checked; public SimCheckBox() { var styles = Main.main.getJsonData().getClassStyleMap().get(CheckBox.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "CheckBox" : name + " (CheckBox)"; } public void reset() { name = null; style = null; var styles = Main.main.getJsonData().getClassStyleMap().get(CheckBox.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } disabled = false; text = null; color = null; padLeft = 0; padRight = 0; padTop = 0; padBottom = 0; checked = false; } } public static class SimImage extends SimActor { public String name; public DrawableData drawable; public Scaling scaling = Scaling.stretch; @Override public String toString() { return name == null ? "Image" : name + " (Image)"; } public void reset() { name = null; drawable = null; scaling = Scaling.stretch; } } public static class SimImageButton extends SimActor { public String name; public StyleData style; public boolean checked; public boolean disabled; public ColorData color; public float padLeft; public float padRight; public float padTop; public float padBottom; public SimImageButton() { var styles = Main.main.getJsonData().getClassStyleMap().get(ImageButton.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "ImageButton" : name + " (ImageButton)"; } public void reset() { name = null; style = null; checked = false; disabled = false; color = null; padLeft = 0; padRight = 0; padTop = 0; padBottom = 0; } } public static class SimImageTextButton extends SimActor { public String name; public String text; public StyleData style; public boolean checked; public boolean disabled; public ColorData color; public float padLeft; public float padRight; public float padTop; public float padBottom; public SimImageTextButton() { var styles = Main.main.getJsonData().getClassStyleMap().get(ImageTextButton.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "ImageTextButton" : name + " (ImageTextButton)"; } public void reset() { name = null; text = null; style = null; checked = false; disabled = false; color = null; padLeft = 0; padRight = 0; padTop = 0; padBottom = 0; } } public static class SimLabel extends SimActor { public String name; public StyleData style; public String text; public int textAlignment = Align.left; public boolean ellipsis; public String ellipsisString = "..."; public boolean wrap; public ColorData color; public SimLabel() { var styles = Main.main.getJsonData().getClassStyleMap().get(Label.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "Label" : name + " (Label)"; } public void reset() { name = null; style = null; var styles = Main.main.getJsonData().getClassStyleMap().get(Label.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } text = null; textAlignment = Align.left; ellipsis = false; ellipsisString = "..."; wrap = false; color = null; } } public static class SimList extends SimActor { public String name; public StyleData style; public Array<String> list = new Array<>(); public SimList() { var styles = Main.main.getJsonData().getClassStyleMap().get(List.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "List" : name + " (List)"; } public void reset() { name = null; style = null; var styles = Main.main.getJsonData().getClassStyleMap().get(List.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } list.clear(); } } public static class SimProgressBar extends SimActor { public String name; public StyleData style; public boolean disabled; public float value; public float minimum; public float maximum = 100; public float increment = 1; public boolean vertical; public float animationDuration; public Interpol animateInterpolation = Interpol.LINEAR; public boolean round = true; public Interpol visualInterpolation = Interpol.LINEAR; public SimProgressBar() { var styles = Main.main.getJsonData().getClassStyleMap().get(ProgressBar.class); for (var style : styles) { if (style.name.equals("default-horizontal")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "ProgressBar" : name + " (ProgressBar)"; } public void reset() { name = null; style = null; disabled = false; value = 0; minimum = 0; maximum = 100; increment = 1; vertical = false; animationDuration = 0; animateInterpolation = Interpol.LINEAR; round = true; visualInterpolation = Interpol.LINEAR; var styles = Main.main.getJsonData().getClassStyleMap().get(ProgressBar.class); for (var style : styles) { if (style.name.equals("default-horizontal")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } } public static class SimSelectBox extends SimActor { public String name; public StyleData style; public boolean disabled; public int maxListCount; public Array<String> list = new Array<>(); public int alignment = Align.center; public int selected; public boolean scrollingDisabled; public SimSelectBox() { var styles = Main.main.getJsonData().getClassStyleMap().get(SelectBox.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "SelectBox" : name + " (SelectBox)"; } public void reset() { name = null; style = null; disabled = false; maxListCount = 0; list.clear(); alignment = Align.center; selected = 0; scrollingDisabled = false; var styles = Main.main.getJsonData().getClassStyleMap().get(SelectBox.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } } public static class SimSlider extends SimActor { public String name; public StyleData style; public boolean disabled; public float value; public float minimum; public float maximum = 100; public float increment = 1; public boolean vertical; public float animationDuration; public Interpol animateInterpolation = Interpol.LINEAR; public boolean round = true; public Interpol visualInterpolation = Interpol.LINEAR; public SimSlider() { var styles = Main.main.getJsonData().getClassStyleMap().get(Slider.class); for (var style : styles) { if (style.name.equals("default-horizontal")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "Slider" : name + " (Slider)"; } public void reset() { name = null; style = null; disabled = false; value = 0; minimum = 0; maximum = 100; increment = 1; vertical = false; animationDuration = 0; animateInterpolation = Interpol.LINEAR; round = true; visualInterpolation = Interpol.LINEAR; var styles = Main.main.getJsonData().getClassStyleMap().get(Slider.class); for (var style : styles) { if (style.name.equals("default-horizontal")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } } public static class SimTextButton extends SimActor { public String name; public String text; public StyleData style; public boolean checked; public boolean disabled; public ColorData color; public float padLeft; public float padRight; public float padTop; public float padBottom; public SimTextButton() { var styles = Main.main.getJsonData().getClassStyleMap().get(TextButton.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "TextButton" : name + " (TextButton)"; } public void reset() { name = null; text = null; style = null; var styles = Main.main.getJsonData().getClassStyleMap().get(TextButton.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } checked = false; disabled = false; color = null; padLeft = 0; padRight = 0; padTop = 0; padBottom = 0; } } public static class SimTextField extends SimActor { public String name; public StyleData style; public String text; public char passwordCharacter = '•'; public boolean passwordMode; public int alignment = Align.center; public boolean disabled; public int cursorPosition; public int selectionStart; public int selectionEnd; public boolean selectAll; public boolean focusTraversal = true; public int maxLength; public String messageText; public SimTextField() { var styles = Main.main.getJsonData().getClassStyleMap().get(TextField.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "TextField" : name + " (TextField)"; } public void reset() { name = null; style = null; text = null; passwordCharacter = '•'; passwordMode = false; alignment = Align.center; disabled = false; cursorPosition = 0; selectionStart = 0; selectionEnd = 0; selectAll = false; focusTraversal = true; maxLength = 0; messageText = null; var styles = Main.main.getJsonData().getClassStyleMap().get(TextField.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } } public static class SimTextArea extends SimActor { public String name; public StyleData style; public String text; public char passwordCharacter = '•'; public boolean passwordMode; public int alignment = Align.center; public boolean disabled; public int cursorPosition; public int selectionStart; public int selectionEnd; public boolean selectAll; public boolean focusTraversal; public int maxLength; public String messageText; public int preferredRows; public SimTextArea() { var styles = Main.main.getJsonData().getClassStyleMap().get(TextField.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "TextArea" : name + " (TextArea)"; } public void reset() { name = null; style = null; text = null; passwordCharacter = '•'; passwordMode = false; alignment = Align.center; disabled = false; cursorPosition = 0; selectionStart = 0; selectionEnd = 0; selectAll = false; focusTraversal = false; maxLength = 0; messageText = null; preferredRows = 0; var styles = Main.main.getJsonData().getClassStyleMap().get(TextField.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } } public static class SimTouchPad extends SimActor { public String name; public StyleData style; public float deadZone; public boolean resetOnTouchUp = true; public SimTouchPad() { var styles = Main.main.getJsonData().getClassStyleMap().get(Touchpad.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "TouchPad" : name + " (TouchPad)"; } public void reset() { name = null; style = null; deadZone = 0; resetOnTouchUp = true; var styles = Main.main.getJsonData().getClassStyleMap().get(Touchpad.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } } public static class SimContainer extends SimActor implements SimSingleChild { public String name; public int alignment = Align.center; public DrawableData background; public boolean fillX; public boolean fillY; public float minWidth = -1; public float minHeight = -1; public float maxWidth = -1; public float maxHeight = -1; public float preferredWidth = -1; public float preferredHeight = -1; public float padLeft; public float padRight; public float padTop; public float padBottom; public SimActor child; public SimContainer() { } @Override public String toString() { return name == null ? "Container" : name + " (Container)"; } public void reset() { name = null; alignment = Align.center; background = null; fillX = false; fillY = false; minWidth = -1; minHeight = -1; maxWidth = -1; maxHeight = -1; preferredWidth = -1; preferredHeight = -1; padLeft = 0; padRight = 0; padTop = 0; padBottom = 0; child = null; } @Override public SimActor getChild() { return child; } } public static class SimHorizontalGroup extends SimActor implements SimMultipleChildren { public String name; public int alignment = Align.center; public boolean expand; public boolean fill; public float padLeft; public float padRight; public float padTop; public float padBottom; public boolean reverse; public int rowAlignment = Align.center; public float space; public boolean wrap; public float wrapSpace; public Array<SimActor> children = new Array<>(); public SimHorizontalGroup() { } @Override public String toString() { return name == null ? "HorizontalGroup" : name + " (HorizontalGroup)"; } public void reset() { name = null; alignment = Align.center; expand = false; fill = false; padLeft = 0; padRight = 0; padTop = 0; padBottom = 0; reverse = false; rowAlignment = Align.center; space = 0; wrap = false; wrapSpace = 0; children.clear(); } @Override public Array<SimActor> getChildren() { return children; } @Override public void addChild(SimActor simActor) { children.add(simActor); } @Override public void removeChild(SimActor simActor) { children.removeValue(simActor, true); } } public static class SimScrollPane extends SimActor implements SimSingleChild { public String name; public StyleData style; public boolean fadeScrollBars = true; public SimActor child; public boolean clamp; public boolean flickScroll = true; public float flingTime = 1f; public boolean forceScrollX; public boolean forceScrollY; public boolean overScrollX = true; public boolean overScrollY = true; public float overScrollDistance = 50; public float overScrollSpeedMin = 30; public float overScrollSpeedMax = 200; public boolean scrollBarBottom = true; public boolean scrollBarRight = true; public boolean scrollBarsOnTop; public boolean scrollBarsVisible = true; public boolean scrollBarTouch = true; public boolean scrollingDisabledX; public boolean scrollingDisabledY; public boolean smoothScrolling = true; public boolean variableSizeKnobs = true; public SimScrollPane() { var styles = Main.main.getJsonData().getClassStyleMap().get(ScrollPane.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "ScrollPane" : name + " (ScrollPane)"; } public void reset() { name = null; style = null; fadeScrollBars = true; child = null; clamp = false; flickScroll = true; flingTime = 1f; forceScrollX = false; forceScrollY = false; overScrollX = true; overScrollY = true; overScrollDistance = 50; overScrollSpeedMin = 30; overScrollSpeedMax = 200; scrollBarBottom = true; scrollBarRight = true; scrollBarsOnTop = false; scrollBarsVisible = true; scrollBarTouch = true; scrollingDisabledX = false; scrollingDisabledY = false; smoothScrolling = true; variableSizeKnobs = true; var styles = Main.main.getJsonData().getClassStyleMap().get(ScrollPane.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public SimActor getChild() { return child; } } public static class SimStack extends SimActor implements SimMultipleChildren { public String name; public Array<SimActor> children = new Array<>(); public SimStack() { } @Override public String toString() { return name == null ? "Stack" : name + " (Stack)"; } public void reset() { name = null; children.clear(); } @Override public Array<SimActor> getChildren() { return children; } @Override public void addChild(SimActor simActor) { children.add(simActor); } @Override public void removeChild(SimActor simActor) { children.removeValue(simActor, true); } } public static class SimSplitPane extends SimActor implements SimMultipleChildren { public String name; public StyleData style; public SimActor childFirst; public SimActor childSecond; public boolean vertical; public float split = .5f; public float splitMin; public float splitMax = 1; public transient Array<SimActor> tempChildren = new Array<>(); public SimSplitPane() { var styles = Main.main.getJsonData().getClassStyleMap().get(SplitPane.class); for (var style : styles) { if (style.name.equals("default-horizontal")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "SplitPane" : name + " (SplitPane)"; } public void reset() { name = null; style = null; childFirst = null; childSecond = null; vertical = false; split = .5f; splitMin = 0; splitMax = 1; tempChildren.clear(); var styles = Main.main.getJsonData().getClassStyleMap().get(Stack.class); for (var style : styles) { if (style.name.equals("default-horizontal")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public Array<SimActor> getChildren() { tempChildren.clear(); if (childFirst != null) { tempChildren.add(childFirst); } if (childSecond != null) { tempChildren.add(childSecond); } return tempChildren; } @Override public void addChild(SimActor simActor) { if (childFirst == null) childFirst = simActor; else if (childSecond == null) childSecond = simActor; } @Override public void removeChild(SimActor simActor) { if (childFirst == simActor) childFirst = null; else if (childSecond == simActor) childSecond = null; } } public static class SimNode extends SimActor implements SimMultipleChildren { public SimActor actor; public Array<SimNode> nodes = new Array<>(); public boolean expanded; public DrawableData icon; public boolean selectable = true; public SimNode() { } @Override public String toString() { return "Node"; } public void reset() { actor = null; nodes.clear(); expanded = false; icon = null; selectable = true; } @Override public Array<SimActor> getChildren() { Array<SimActor> actors = new Array<>(); actors.addAll(nodes); if (actor != null) actors.add(actor); return actors; } @Override public void addChild(SimActor simActor) { if (simActor instanceof SimNode) nodes.add((SimNode) simActor); else if (actor == null) actor = simActor; } @Override public void removeChild(SimActor simActor) { if (simActor instanceof SimNode) nodes.removeValue((SimNode) simActor, true); else if (actor == simActor) actor = null; } } public static class SimTree extends SimActor implements SimMultipleChildren { public String name; public StyleData style; public Array<SimNode> children = new Array<>(); public float padLeft; public float padRight; public float iconSpaceLeft = 2; public float iconSpaceRight = 2; public float indentSpacing; public float ySpacing = 4; public SimTree() { var styles = Main.main.getJsonData().getClassStyleMap().get(Tree.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public String toString() { return name == null ? "Tree" : name + " (Tree)"; } public void reset() { name = null; style = null; children.clear(); padLeft = 0; padRight = 0; iconSpaceLeft = 2; iconSpaceRight = 2; indentSpacing = 0; ySpacing = 4; var styles = Main.main.getJsonData().getClassStyleMap().get(Tree.class); for (var style : styles) { if (style.name.equals("default")) { if (style.hasMandatoryFields() && !style.hasAllNullFields()) { this.style = style; } } } } @Override public Array<SimNode> getChildren() { return children; } @Override public void addChild(SimActor simActor) { children.add((SimNode) simActor); } @Override public void removeChild(SimActor simActor) { children.removeValue((SimNode) simActor, true); } } public static class SimVerticalGroup extends SimActor implements SimMultipleChildren { public String name; public int alignment = Align.center; public boolean expand; public boolean fill; public float padLeft; public float padRight; public float padTop; public float padBottom; public boolean reverse; public int columnAlignment = Align.center; public float space; public boolean wrap; public float wrapSpace; public Array<SimActor> children = new Array<>(); public SimVerticalGroup() { } @Override public String toString() { return name == null ? "VerticalGroup" : name + " (VerticalGroup)"; } public void reset() { name = null; alignment = Align.center; expand = false; fill = false; padLeft = 0; padRight = 0; padTop = 0; padBottom = 0; reverse = false; columnAlignment = Align.center; space = 0; wrap = false; wrapSpace = 0; children.clear(); } @Override public Array<SimActor> getChildren() { return children; } @Override public void addChild(SimActor simActor) { children.add(simActor); } @Override public void removeChild(SimActor simActor) { children.removeValue(simActor, true); } } }
/* Generated By:JJTree: Do not edit this line. OFunctionCall.java Version 4.3 */ /* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package com.orientechnologies.orient.core.sql.parser; import com.orientechnologies.orient.core.command.OCommandContext; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.exception.OCommandExecutionException; import com.orientechnologies.orient.core.sql.OSQLEngine; import com.orientechnologies.orient.core.sql.executor.AggregationContext; import com.orientechnologies.orient.core.sql.executor.OFuncitonAggregationContext; import com.orientechnologies.orient.core.sql.executor.OResult; import com.orientechnologies.orient.core.sql.functions.OIndexableSQLFunction; import com.orientechnologies.orient.core.sql.functions.OSQLFunction; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; public class OFunctionCall extends SimpleNode { protected OIdentifier name; protected List<OExpression> params = new ArrayList<OExpression>(); public OFunctionCall(int id) { super(id); } public OFunctionCall(OrientSql p, int id) { super(p, id); } /** * Accept the visitor. * */ public Object jjtAccept(OrientSqlVisitor visitor, Object data) { return visitor.visit(this, data); } public boolean isStar() { if (this.params.size() != 1) { return false; } OExpression param = params.get(0); if (param.mathExpression == null || !(param.mathExpression instanceof OBaseExpression)) { return false; } OBaseExpression base = (OBaseExpression) param.mathExpression; if (base.identifier == null || base.identifier.suffix == null) { return false; } return base.identifier.suffix.star; } public List<OExpression> getParams() { return params; } public void setParams(List<OExpression> params) { this.params = params; } public void toString(Map<Object, Object> params, StringBuilder builder) { name.toString(params, builder); builder.append("("); boolean first = true; for (OExpression expr : this.params) { if (!first) { builder.append(", "); } expr.toString(params, builder); first = false; } builder.append(")"); } public Object execute(Object targetObjects, OCommandContext ctx) { return execute(targetObjects, ctx, name.getStringValue()); } private Object execute(Object targetObjects, OCommandContext ctx, String name) { List<Object> paramValues = new ArrayList<Object>(); for (OExpression expr : this.params) { Object current = ctx.getVariable("$current"); if (current instanceof OIdentifiable) { paramValues.add(expr.execute((OIdentifiable) current, ctx)); } else if (current instanceof OResult) { paramValues.add(expr.execute((OResult) current, ctx)); } else if (current == null) { paramValues.add(expr.execute((OResult) current, ctx)); } else { throw new OCommandExecutionException("Invalid value for $current: " + current); } } OSQLFunction function = OSQLEngine.getInstance().getFunction(name); if (function != null) { Object current = ctx.getVariable("$current"); if (current instanceof OIdentifiable) { return function.execute(targetObjects, (OIdentifiable) current, null, paramValues.toArray(), ctx); } else if (current instanceof OResult) { return function.execute(targetObjects, ((OResult) current).getElement(), null, paramValues.toArray(), ctx); } else if (current == null) { return function.execute(targetObjects, null, null, paramValues.toArray(), ctx); } else { throw new OCommandExecutionException("Invalid value for $current: " + current); } } throw new UnsupportedOperationException("finish OFunctionCall implementation!"); } public static ODatabaseDocumentInternal getDatabase() { return ODatabaseRecordThreadLocal.INSTANCE.get(); } public boolean isIndexedFunctionCall() { OSQLFunction function = OSQLEngine.getInstance().getFunction(name.getStringValue()); return (function instanceof OIndexableSQLFunction); } /** * see OIndexableSQLFunction.searchFromTarget() * * @param target * @param ctx * @param operator * @param rightValue * @return */ public Iterable<OIdentifiable> executeIndexedFunction(OFromClause target, OCommandContext ctx, OBinaryCompareOperator operator, Object rightValue) { OSQLFunction function = OSQLEngine.getInstance().getFunction(name.getStringValue()); if (function instanceof OIndexableSQLFunction) { return ((OIndexableSQLFunction) function) .searchFromTarget(target, operator, rightValue, ctx, this.getParams().toArray(new OExpression[] {})); } return null; } /** * @param target query target * @param ctx execution context * @param operator operator at the right of the function * @param rightValue value to compare to funciton result * @return the approximate number of items returned by the condition execution, -1 if the extimation cannot be executed */ public long estimateIndexedFunction(OFromClause target, OCommandContext ctx, OBinaryCompareOperator operator, Object rightValue) { OSQLFunction function = OSQLEngine.getInstance().getFunction(name.getStringValue()); if (function instanceof OIndexableSQLFunction) { return ((OIndexableSQLFunction) function) .estimate(target, operator, rightValue, ctx, this.getParams().toArray(new OExpression[] {})); } return -1; } /** * tests if current function is an indexed function AND that function can also be executed without using the index * * @param target the query target * @param context the execution context * @param operator * @param right * @return true if current function is an indexed funciton AND that function can also be executed without using the index, false otherwise */ public boolean canExecuteIndexedFunctionWithoutIndex(OFromClause target, OCommandContext context, OBinaryCompareOperator operator, Object right) { OSQLFunction function = OSQLEngine.getInstance().getFunction(name.getStringValue()); if (function instanceof OIndexableSQLFunction) { return ((OIndexableSQLFunction) function) .canExecuteWithoutIndex(target, operator, right, context, this.getParams().toArray(new OExpression[] {})); } return false; } /** * tests if current function is an indexed function AND that function can be used on this target * * @param target the query target * @param context the execution context * @param operator * @param right * @return true if current function is an indexed function AND that function can be used on this target, false otherwise */ public boolean allowsIndexedFunctionExecutionOnTarget(OFromClause target, OCommandContext context, OBinaryCompareOperator operator, Object right) { OSQLFunction function = OSQLEngine.getInstance().getFunction(name.getStringValue()); if (function instanceof OIndexableSQLFunction) { return ((OIndexableSQLFunction) function) .allowsIndexedExecution(target, operator, right, context, this.getParams().toArray(new OExpression[] {})); } return false; } /** * tests if current expression is an indexed function AND the function has also to be executed after the index search. * In some cases, the index search is accurate, so this condition can be excluded from further evaluation. In other cases * the result from the index is a superset of the expected result, so the function has to be executed anyway for further filtering * * @param target the query target * @param context the execution context * @return true if current expression is an indexed function AND the function has also to be executed after the index search. */ public boolean executeIndexedFunctionAfterIndexSearch(OFromClause target, OCommandContext context, OBinaryCompareOperator operator, Object right) { OSQLFunction function = OSQLEngine.getInstance().getFunction(name.getStringValue()); if (function instanceof OIndexableSQLFunction) { return ((OIndexableSQLFunction) function) .shouldExecuteAfterSearch(target, operator, right, context, this.getParams().toArray(new OExpression[] {})); } return false; } public boolean isExpand() { return name.getStringValue().equals("expand"); } public boolean needsAliases(Set<String> aliases) { for (OExpression param : params) { if (param.needsAliases(aliases)) { return true; } } return false; } public boolean isAggregate() { if (isAggregateFunction()) { return true; } for (OExpression exp : params) { if (exp.isAggregate()) { return true; } } return false; } public SimpleNode splitForAggregation(AggregateProjectionSplit aggregateProj) { if (isAggregate()) { OFunctionCall newFunct = new OFunctionCall(-1); newFunct.name = this.name; OIdentifier functionResultAlias = aggregateProj.getNextAlias(); if (isAggregateFunction()) { if (isStar()) { for (OExpression param : params) { newFunct.getParams().add(param); } } else { for (OExpression param : params) { if (param.isAggregate()) { throw new OCommandExecutionException( "Cannot calculate an aggregate function of another aggregate function " + toString()); } OIdentifier nextAlias = aggregateProj.getNextAlias(); OProjectionItem paramItem = new OProjectionItem(-1); paramItem.alias = nextAlias; paramItem.expression = param; aggregateProj.getPreAggregate().add(paramItem); newFunct.params.add(new OExpression(nextAlias)); } } aggregateProj.getAggregate().add(createProjection(newFunct, functionResultAlias)); return new OExpression(functionResultAlias); } else { if (isStar()) { for (OExpression param : params) { newFunct.getParams().add(param); } } else { for (OExpression param : params) { newFunct.getParams().add(param.splitForAggregation(aggregateProj)); } } } return newFunct; } return this; } private boolean isAggregateFunction() { OSQLFunction function = OSQLEngine.getInstance().getFunction(name.getStringValue()); function.config(this.params.toArray()); return function.aggregateResults(); } private OProjectionItem createProjection(OFunctionCall newFunct, OIdentifier alias) { OLevelZeroIdentifier l0 = new OLevelZeroIdentifier(-1); l0.functionCall = newFunct; OBaseIdentifier l1 = new OBaseIdentifier(-1); l1.levelZero = l0; OBaseExpression l2 = new OBaseExpression(-1); l2.identifier = l1; OExpression l3 = new OExpression(-1); l3.mathExpression = l2; OProjectionItem item = new OProjectionItem(-1); item.alias = alias; item.expression = l3; return item; } public boolean isEarlyCalculated() { for (OExpression param : params) { if (!param.isEarlyCalculated()) { return false; } } return true; } public AggregationContext getAggregationContext(OCommandContext ctx) { OSQLFunction function = OSQLEngine.getInstance().getFunction(name.getStringValue()); function.config(this.params.toArray()); OFuncitonAggregationContext result = new OFuncitonAggregationContext(function, this.params); return result; } public OFunctionCall copy() { OFunctionCall result = new OFunctionCall(-1); result.name = name; result.params = params.stream().map(x -> x.copy()).collect(Collectors.toList()); return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OFunctionCall that = (OFunctionCall) o; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (params != null ? !params.equals(that.params) : that.params != null) return false; return true; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (params != null ? params.hashCode() : 0); return result; } public boolean refersToParent() { if (params != null) { for (OExpression param : params) { if (param != null && param.refersToParent()) { return true; } } } return false; } public OIdentifier getName() { return name; } } /* JavaCC - OriginalChecksum=290d4e1a3f663299452e05f8db718419 (do not edit this line) */
package de.danoeh.antennapod.core.service.download; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaMetadataRetriever; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.support.annotation.NonNull; import android.support.annotation.VisibleForTesting; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import android.util.Log; import android.util.Pair; import android.webkit.URLUtil; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.xml.parsers.ParserConfigurationException; import de.danoeh.antennapod.core.ClientConfig; import de.danoeh.antennapod.core.R; import de.danoeh.antennapod.core.event.DownloadEvent; import de.danoeh.antennapod.core.event.FeedItemEvent; import de.danoeh.antennapod.core.feed.Feed; import de.danoeh.antennapod.core.feed.FeedImage; import de.danoeh.antennapod.core.feed.FeedItem; import de.danoeh.antennapod.core.feed.FeedMedia; import de.danoeh.antennapod.core.feed.FeedPreferences; import de.danoeh.antennapod.core.gpoddernet.model.GpodnetEpisodeAction; import de.danoeh.antennapod.core.gpoddernet.model.GpodnetEpisodeAction.Action; import de.danoeh.antennapod.core.preferences.GpodnetPreferences; import de.danoeh.antennapod.core.preferences.UserPreferences; import de.danoeh.antennapod.core.service.GpodnetSyncService; import de.danoeh.antennapod.core.storage.DBReader; import de.danoeh.antennapod.core.storage.DBTasks; import de.danoeh.antennapod.core.storage.DBWriter; import de.danoeh.antennapod.core.storage.DownloadRequestException; import de.danoeh.antennapod.core.storage.DownloadRequester; import de.danoeh.antennapod.core.syndication.handler.FeedHandler; import de.danoeh.antennapod.core.syndication.handler.FeedHandlerResult; import de.danoeh.antennapod.core.syndication.handler.UnsupportedFeedtypeException; import de.danoeh.antennapod.core.util.ChapterUtils; import de.danoeh.antennapod.core.util.DownloadError; import de.danoeh.antennapod.core.util.InvalidFeedException; import de.greenrobot.event.EventBus; /** * Manages the download of feedfiles in the app. Downloads can be enqueued via the startService intent. * The argument of the intent is an instance of DownloadRequest in the EXTRA_REQUEST field of * the intent. * After the downloads have finished, the downloaded object will be passed on to a specific handler, depending on the * type of the feedfile. */ public class DownloadService extends Service { private static final String TAG = "DownloadService"; /** * Cancels one download. The intent MUST have an EXTRA_DOWNLOAD_URL extra that contains the download URL of the * object whose download should be cancelled. */ public static final String ACTION_CANCEL_DOWNLOAD = "action.de.danoeh.antennapod.core.service.cancelDownload"; /** * Cancels all running downloads. */ public static final String ACTION_CANCEL_ALL_DOWNLOADS = "action.de.danoeh.antennapod.core.service.cancelAllDownloads"; /** * Extra for ACTION_CANCEL_DOWNLOAD */ public static final String EXTRA_DOWNLOAD_URL = "downloadUrl"; /** * Extra for ACTION_ENQUEUE_DOWNLOAD intent. */ public static final String EXTRA_REQUEST = "request"; /** * Contains all completed downloads that have not been included in the report yet. */ private List<DownloadStatus> reportQueue; private ExecutorService syncExecutor; private CompletionService<Downloader> downloadExecutor; private FeedSyncThread feedSyncThread; /** * Number of threads of downloadExecutor. */ private static final int NUM_PARALLEL_DOWNLOADS = 6; private DownloadRequester requester; private NotificationCompat.Builder notificationCompatBuilder; private int NOTIFICATION_ID = 2; private int REPORT_ID = 3; /** * Currently running downloads. */ private List<Downloader> downloads; /** * Number of running downloads. */ private AtomicInteger numberOfDownloads; /** * True if service is running. */ public static boolean isRunning = false; private Handler handler; private NotificationUpdater notificationUpdater; private ScheduledFuture<?> notificationUpdaterFuture; private static final int SCHED_EX_POOL_SIZE = 1; private ScheduledThreadPoolExecutor schedExecutor; private Handler postHandler = new Handler(); private final IBinder mBinder = new LocalBinder(); public class LocalBinder extends Binder { public DownloadService getService() { return DownloadService.this; } } private Thread downloadCompletionThread = new Thread() { private static final String TAG = "downloadCompletionThd"; @Override public void run() { Log.d(TAG, "downloadCompletionThread was started"); while (!isInterrupted()) { try { Downloader downloader = downloadExecutor.take().get(); Log.d(TAG, "Received 'Download Complete' - message."); removeDownload(downloader); DownloadStatus status = downloader.getResult(); boolean successful = status.isSuccessful(); final int type = status.getFeedfileType(); if (successful) { if (type == Feed.FEEDFILETYPE_FEED) { handleCompletedFeedDownload(downloader.getDownloadRequest()); } else if (type == FeedMedia.FEEDFILETYPE_FEEDMEDIA) { handleCompletedFeedMediaDownload(status, downloader.getDownloadRequest()); } } else { numberOfDownloads.decrementAndGet(); if (!status.isCancelled()) { if (status.getReason() == DownloadError.ERROR_UNAUTHORIZED) { postAuthenticationNotification(downloader.getDownloadRequest()); } else if (status.getReason() == DownloadError.ERROR_HTTP_DATA_ERROR && Integer.parseInt(status.getReasonDetailed()) == 416) { Log.d(TAG, "Requested invalid range, restarting download from the beginning"); FileUtils.deleteQuietly(new File(downloader.getDownloadRequest().getDestination())); DownloadRequester.getInstance().download(DownloadService.this, downloader.getDownloadRequest()); } else { Log.e(TAG, "Download failed"); saveDownloadStatus(status); handleFailedDownload(status, downloader.getDownloadRequest()); if (type == FeedMedia.FEEDFILETYPE_FEEDMEDIA) { long id = status.getFeedfileId(); FeedMedia media = DBReader.getFeedMedia(id); FeedItem item; if (media == null || (item = media.getItem()) == null) { return; } boolean httpNotFound = status.getReason() == DownloadError.ERROR_HTTP_DATA_ERROR && String.valueOf(HttpURLConnection.HTTP_NOT_FOUND).equals(status.getReasonDetailed()); boolean forbidden = status.getReason() == DownloadError.ERROR_FORBIDDEN && String.valueOf(HttpURLConnection.HTTP_FORBIDDEN).equals(status.getReasonDetailed()); boolean notEnoughSpace = status.getReason() == DownloadError.ERROR_NOT_ENOUGH_SPACE; boolean wrongFileType = status.getReason() == DownloadError.ERROR_FILE_TYPE; if (httpNotFound || forbidden || notEnoughSpace || wrongFileType) { DBWriter.saveFeedItemAutoDownloadFailed(item).get(); } // to make lists reload the failed item, we fake an item update EventBus.getDefault().post(FeedItemEvent.updated(item)); } } } else { // if FeedMedia download has been canceled, fake FeedItem update // so that lists reload that it if (status.getFeedfileType() == FeedMedia.FEEDFILETYPE_FEEDMEDIA) { FeedMedia media = DBReader.getFeedMedia(status.getFeedfileId()); FeedItem item; if (media == null || (item = media.getItem()) == null) { return; } EventBus.getDefault().post(FeedItemEvent.updated(item)); } } queryDownloadsAsync(); } } catch (InterruptedException e) { Log.e(TAG, "DownloadCompletionThread was interrupted"); } catch (ExecutionException e) { Log.e(TAG, "ExecutionException in DownloadCompletionThread: " + e.getMessage()); numberOfDownloads.decrementAndGet(); } } Log.d(TAG, "End of downloadCompletionThread"); } }; @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent.getParcelableExtra(EXTRA_REQUEST) != null) { onDownloadQueued(intent); } else if (numberOfDownloads.get() == 0) { stopSelf(); } return Service.START_NOT_STICKY; } @Override public void onCreate() { Log.d(TAG, "Service started"); isRunning = true; handler = new Handler(); reportQueue = Collections.synchronizedList(new ArrayList<>()); downloads = Collections.synchronizedList(new ArrayList<>()); numberOfDownloads = new AtomicInteger(0); IntentFilter cancelDownloadReceiverFilter = new IntentFilter(); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_ALL_DOWNLOADS); cancelDownloadReceiverFilter.addAction(ACTION_CANCEL_DOWNLOAD); registerReceiver(cancelDownloadReceiver, cancelDownloadReceiverFilter); syncExecutor = Executors.newSingleThreadExecutor(r -> { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; }); Log.d(TAG, "parallel downloads: " + UserPreferences.getParallelDownloads()); downloadExecutor = new ExecutorCompletionService<>( Executors.newFixedThreadPool(UserPreferences.getParallelDownloads(), r -> { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; } ) ); schedExecutor = new ScheduledThreadPoolExecutor(SCHED_EX_POOL_SIZE, r -> { Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY); return t; }, (r, executor) -> Log.w(TAG, "SchedEx rejected submission of new task") ); downloadCompletionThread.start(); feedSyncThread = new FeedSyncThread(); feedSyncThread.start(); setupNotificationBuilders(); requester = DownloadRequester.getInstance(); } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public void onDestroy() { Log.d(TAG, "Service shutting down"); isRunning = false; if (ClientConfig.downloadServiceCallbacks.shouldCreateReport() && UserPreferences.showDownloadReport()) { updateReport(); } postHandler.removeCallbacks(postDownloaderTask); EventBus.getDefault().postSticky(DownloadEvent.refresh(Collections.emptyList())); stopForeground(true); NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); nm.cancel(NOTIFICATION_ID); downloadCompletionThread.interrupt(); syncExecutor.shutdown(); schedExecutor.shutdown(); feedSyncThread.shutdown(); cancelNotificationUpdater(); unregisterReceiver(cancelDownloadReceiver); // if this was the initial gpodder sync, i.e. we just synced the feeds successfully, // it is now time to sync the episode actions if (GpodnetPreferences.loggedIn() && GpodnetPreferences.getLastSubscriptionSyncTimestamp() > 0 && GpodnetPreferences.getLastEpisodeActionsSyncTimestamp() == 0) { GpodnetSyncService.sendSyncActionsIntent(this); } // start auto download in case anything new has shown up DBTasks.autodownloadUndownloadedItems(getApplicationContext()); } private void setupNotificationBuilders() { Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.stat_notify_sync); notificationCompatBuilder = new NotificationCompat.Builder(this) .setOngoing(true) .setContentIntent(ClientConfig.downloadServiceCallbacks.getNotificationContentIntent(this)) .setLargeIcon(icon) .setSmallIcon(R.drawable.stat_notify_sync) .setVisibility(Notification.VISIBILITY_PUBLIC); Log.d(TAG, "Notification set up"); } /** * Updates the contents of the service's notifications. Should be called * before setupNotificationBuilders. */ private Notification updateNotifications() { if (notificationCompatBuilder == null) { return null; } String contentTitle = getString(R.string.download_notification_title); int numDownloads = requester.getNumberOfDownloads(); String downloadsLeft = (numDownloads > 0) ? getResources().getQuantityString(R.plurals.downloads_left, numDownloads, numDownloads) : getString(R.string.downloads_processing); String bigText = compileNotificationString(downloads); notificationCompatBuilder.setContentTitle(contentTitle); notificationCompatBuilder.setContentText(downloadsLeft); notificationCompatBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText)); return notificationCompatBuilder.build(); } private Downloader getDownloader(String downloadUrl) { for (Downloader downloader : downloads) { if (downloader.getDownloadRequest().getSource().equals(downloadUrl)) { return downloader; } } return null; } private BroadcastReceiver cancelDownloadReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (TextUtils.equals(intent.getAction(), ACTION_CANCEL_DOWNLOAD)) { String url = intent.getStringExtra(EXTRA_DOWNLOAD_URL); if (url == null) { throw new IllegalArgumentException("ACTION_CANCEL_DOWNLOAD intent needs download url extra"); } Log.d(TAG, "Cancelling download with url " + url); Downloader d = getDownloader(url); if (d != null) { d.cancel(); } else { Log.e(TAG, "Could not cancel download with url " + url); } postDownloaders(); } else if (TextUtils.equals(intent.getAction(), ACTION_CANCEL_ALL_DOWNLOADS)) { for (Downloader d : downloads) { d.cancel(); Log.d(TAG, "Cancelled all downloads"); } postDownloaders(); } queryDownloads(); } }; private void onDownloadQueued(Intent intent) { Log.d(TAG, "Received enqueue request"); DownloadRequest request = intent.getParcelableExtra(EXTRA_REQUEST); if (request == null) { throw new IllegalArgumentException( "ACTION_ENQUEUE_DOWNLOAD intent needs request extra"); } Downloader downloader = getDownloader(request); if (downloader != null) { numberOfDownloads.incrementAndGet(); // smaller rss feeds before bigger media files if (request.getFeedfileType() == Feed.FEEDFILETYPE_FEED) { downloads.add(0, downloader); } else { downloads.add(downloader); } downloadExecutor.submit(downloader); postDownloaders(); } queryDownloads(); } private Downloader getDownloader(DownloadRequest request) { if (!URLUtil.isHttpUrl(request.getSource()) && !URLUtil.isHttpsUrl(request.getSource())) { Log.e(TAG, "Could not find appropriate downloader for " + request.getSource()); return null; } return new HttpDownloader(request); } /** * Remove download from the DownloadRequester list and from the * DownloadService list. */ private void removeDownload(final Downloader d) { handler.post(() -> { Log.d(TAG, "Removing downloader: " + d.getDownloadRequest().getSource()); boolean rc = downloads.remove(d); Log.d(TAG, "Result of downloads.remove: " + rc); DownloadRequester.getInstance().removeDownload(d.getDownloadRequest()); postDownloaders(); }); } /** * Adds a new DownloadStatus object to the list of completed downloads and * saves it in the database * * @param status the download that is going to be saved */ private void saveDownloadStatus(DownloadStatus status) { reportQueue.add(status); DBWriter.addDownloadStatus(status); } /** * Creates a notification at the end of the service lifecycle to notify the * user about the number of completed downloads. A report will only be * created if there is at least one failed download excluding images */ private void updateReport() { // check if report should be created boolean createReport = false; int successfulDownloads = 0; int failedDownloads = 0; // a download report is created if at least one download has failed // (excluding failed image downloads) for (DownloadStatus status : reportQueue) { if (status.isSuccessful()) { successfulDownloads++; } else if (!status.isCancelled()) { if (status.getFeedfileType() != FeedImage.FEEDFILETYPE_FEEDIMAGE) { createReport = true; } failedDownloads++; } } if (createReport) { Log.d(TAG, "Creating report"); // create notification object Notification notification = new NotificationCompat.Builder(this) .setTicker(getString(R.string.download_report_title)) .setContentTitle(getString(R.string.download_report_content_title)) .setContentText( String.format( getString(R.string.download_report_content), successfulDownloads, failedDownloads) ) .setSmallIcon(R.drawable.stat_notify_sync_error) .setLargeIcon( BitmapFactory.decodeResource(getResources(), R.drawable.stat_notify_sync_error) ) .setContentIntent( ClientConfig.downloadServiceCallbacks.getReportNotificationContentIntent(this) ) .setAutoCancel(true) .setVisibility(Notification.VISIBILITY_PUBLIC) .build(); NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(REPORT_ID, notification); } else { Log.d(TAG, "No report is created"); } reportQueue.clear(); } /** * Calls query downloads on the services main thread. This method should be used instead of queryDownloads if it is * used from a thread other than the main thread. */ void queryDownloadsAsync() { handler.post(DownloadService.this::queryDownloads); } /** * Check if there's something else to download, otherwise stop */ void queryDownloads() { Log.d(TAG, numberOfDownloads.get() + " downloads left"); if (numberOfDownloads.get() <= 0 && DownloadRequester.getInstance().hasNoDownloads()) { Log.d(TAG, "Number of downloads is " + numberOfDownloads.get() + ", attempting shutdown"); stopSelf(); } else { setupNotificationUpdater(); startForeground(NOTIFICATION_ID, updateNotifications()); } } private void postAuthenticationNotification(final DownloadRequest downloadRequest) { handler.post(() -> { final String resourceTitle = (downloadRequest.getTitle() != null) ? downloadRequest.getTitle() : downloadRequest.getSource(); NotificationCompat.Builder builder = new NotificationCompat.Builder(DownloadService.this); builder.setTicker(getText(R.string.authentication_notification_title)) .setContentTitle(getText(R.string.authentication_notification_title)) .setContentText(getText(R.string.authentication_notification_msg)) .setStyle(new NotificationCompat.BigTextStyle().bigText(getText(R.string.authentication_notification_msg) + ": " + resourceTitle)) .setSmallIcon(R.drawable.ic_stat_authentication) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_authentication)) .setAutoCancel(true) .setContentIntent(ClientConfig.downloadServiceCallbacks.getAuthentificationNotificationContentIntent(DownloadService.this, downloadRequest)) .setVisibility(Notification.VISIBILITY_PUBLIC); Notification n = builder.build(); NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(downloadRequest.getSource().hashCode(), n); }); } /** * Is called whenever a Feed is downloaded */ private void handleCompletedFeedDownload(DownloadRequest request) { Log.d(TAG, "Handling completed Feed Download"); feedSyncThread.submitCompletedDownload(request); } /** * Is called whenever a FeedMedia is downloaded. */ private void handleCompletedFeedMediaDownload(DownloadStatus status, DownloadRequest request) { Log.d(TAG, "Handling completed FeedMedia Download"); syncExecutor.execute(new MediaHandlerThread(status, request)); } private void handleFailedDownload(DownloadStatus status, DownloadRequest request) { Log.d(TAG, "Handling failed download"); syncExecutor.execute(new FailedDownloadHandler(status, request)); } /** * Takes a single Feed, parses the corresponding file and refreshes * information in the manager */ class FeedSyncThread extends Thread { private static final String TAG = "FeedSyncThread"; private BlockingQueue<DownloadRequest> completedRequests = new LinkedBlockingDeque<>(); private CompletionService<Pair<DownloadRequest, FeedHandlerResult>> parserService = new ExecutorCompletionService<>(Executors.newSingleThreadExecutor()); private ExecutorService dbService = Executors.newSingleThreadExecutor(); private Future<?> dbUpdateFuture; private volatile boolean isActive = true; private volatile boolean isCollectingRequests = false; private final long WAIT_TIMEOUT = 3000; /** * Waits for completed requests. Once the first request has been taken, the method will wait WAIT_TIMEOUT ms longer to * collect more completed requests. * * @return Collected feeds or null if the method has been interrupted during the first waiting period. */ private List<Pair<DownloadRequest, FeedHandlerResult>> collectCompletedRequests() { List<Pair<DownloadRequest, FeedHandlerResult>> results = new LinkedList<>(); DownloadRequester requester = DownloadRequester.getInstance(); int tasks = 0; try { DownloadRequest request = completedRequests.take(); parserService.submit(new FeedParserTask(request)); tasks++; } catch (InterruptedException e) { Log.e(TAG, "FeedSyncThread was interrupted"); return null; } tasks += pollCompletedDownloads(); isCollectingRequests = true; if (requester.isDownloadingFeeds()) { // wait for completion of more downloads long startTime = System.currentTimeMillis(); long currentTime = startTime; while (requester.isDownloadingFeeds() && (currentTime - startTime) < WAIT_TIMEOUT) { try { Log.d(TAG, "Waiting for " + (startTime + WAIT_TIMEOUT - currentTime) + " ms"); sleep(startTime + WAIT_TIMEOUT - currentTime); } catch (InterruptedException e) { Log.d(TAG, "interrupted while waiting for more downloads"); tasks += pollCompletedDownloads(); } finally { currentTime = System.currentTimeMillis(); } } tasks += pollCompletedDownloads(); } isCollectingRequests = false; for (int i = 0; i < tasks; i++) { try { Pair<DownloadRequest, FeedHandlerResult> result = parserService.take().get(); if (result != null) { results.add(result); } } catch (InterruptedException e) { Log.e(TAG, "FeedSyncThread was interrupted"); } catch (ExecutionException e) { Log.e(TAG, "ExecutionException in FeedSyncThread: " + e.getMessage()); } } return results; } private int pollCompletedDownloads() { int tasks = 0; while (!completedRequests.isEmpty()) { parserService.submit(new FeedParserTask(completedRequests.poll())); tasks++; } return tasks; } @Override public void run() { while (isActive) { final List<Pair<DownloadRequest, FeedHandlerResult>> results = collectCompletedRequests(); if (results == null) { continue; } Log.d(TAG, "Bundling " + results.size() + " feeds"); for (Pair<DownloadRequest, FeedHandlerResult> result : results) { removeDuplicateImages(result.second.feed); // duplicate images have to removed because the DownloadRequester does not accept two downloads with the same download URL yet. } // Save information of feed in DB if (dbUpdateFuture != null) { try { dbUpdateFuture.get(); } catch (InterruptedException e) { Log.e(TAG, "FeedSyncThread was interrupted"); } catch (ExecutionException e) { Log.e(TAG, "ExecutionException in FeedSyncThread: " + e.getMessage()); } } dbUpdateFuture = dbService.submit(() -> { Feed[] savedFeeds = DBTasks.updateFeed(DownloadService.this, getFeeds(results)); for (int i = 0; i < savedFeeds.length; i++) { Feed savedFeed = savedFeeds[i]; // If loadAllPages=true, check if another page is available and queue it for download final boolean loadAllPages = results.get(i).first.getArguments().getBoolean(DownloadRequester.REQUEST_ARG_LOAD_ALL_PAGES); final Feed feed = results.get(i).second.feed; if (loadAllPages && feed.getNextPageLink() != null) { try { feed.setId(savedFeed.getId()); DBTasks.loadNextPageOfFeed(DownloadService.this, savedFeed, true); } catch (DownloadRequestException e) { Log.e(TAG, "Error trying to load next page", e); } } ClientConfig.downloadServiceCallbacks.onFeedParsed(DownloadService.this, savedFeed); numberOfDownloads.decrementAndGet(); } queryDownloadsAsync(); }); } if (dbUpdateFuture != null) { try { dbUpdateFuture.get(); } catch (InterruptedException e) { Log.e(TAG, "interrupted while updating the db"); } catch (ExecutionException e) { Log.e(TAG, "ExecutionException while updating the db: " + e.getMessage()); } } Log.d(TAG, "Shutting down"); } /** * Helper method */ private Feed[] getFeeds(List<Pair<DownloadRequest, FeedHandlerResult>> results) { Feed[] feeds = new Feed[results.size()]; for (int i = 0; i < results.size(); i++) { feeds[i] = results.get(i).second.feed; } return feeds; } private class FeedParserTask implements Callable<Pair<DownloadRequest, FeedHandlerResult>> { private DownloadRequest request; private FeedParserTask(DownloadRequest request) { this.request = request; } @Override public Pair<DownloadRequest, FeedHandlerResult> call() throws Exception { return parseFeed(request); } } private Pair<DownloadRequest, FeedHandlerResult> parseFeed(DownloadRequest request) { Feed feed = new Feed(request.getSource(), request.getLastModified()); feed.setFile_url(request.getDestination()); feed.setId(request.getFeedfileId()); feed.setDownloaded(true); feed.setPreferences(new FeedPreferences(0, true, FeedPreferences.AutoDeleteAction.GLOBAL, request.getUsername(), request.getPassword())); feed.setPageNr(request.getArguments().getInt(DownloadRequester.REQUEST_ARG_PAGE_NR, 0)); DownloadError reason = null; String reasonDetailed = null; boolean successful = true; FeedHandler feedHandler = new FeedHandler(); FeedHandlerResult result = null; try { result = feedHandler.parseFeed(feed); Log.d(TAG, feed.getTitle() + " parsed"); if (!checkFeedData(feed)) { throw new InvalidFeedException(); } } catch (SAXException | IOException | ParserConfigurationException e) { successful = false; e.printStackTrace(); reason = DownloadError.ERROR_PARSER_EXCEPTION; reasonDetailed = e.getMessage(); } catch (UnsupportedFeedtypeException e) { e.printStackTrace(); successful = false; reason = DownloadError.ERROR_UNSUPPORTED_TYPE; reasonDetailed = e.getMessage(); } catch (InvalidFeedException e) { e.printStackTrace(); successful = false; reason = DownloadError.ERROR_PARSER_EXCEPTION; reasonDetailed = e.getMessage(); } finally { File feedFile = new File(request.getDestination()); if (feedFile.exists()) { boolean deleted = feedFile.delete(); Log.d(TAG, "Deletion of file '" + feedFile.getAbsolutePath() + "' " + (deleted ? "successful" : "FAILED")); } } if (successful) { // we create a 'successful' download log if the feed's last refresh failed List<DownloadStatus> log = DBReader.getFeedDownloadLog(feed); if (log.size() > 0 && !log.get(0).isSuccessful()) { saveDownloadStatus( new DownloadStatus(feed, feed.getHumanReadableIdentifier(), DownloadError.SUCCESS, successful, reasonDetailed)); } return Pair.create(request, result); } else { numberOfDownloads.decrementAndGet(); saveDownloadStatus( new DownloadStatus(feed, feed.getHumanReadableIdentifier(), reason, successful, reasonDetailed)); return null; } } /** * Checks if the feed was parsed correctly. */ private boolean checkFeedData(Feed feed) { if (feed.getTitle() == null) { Log.e(TAG, "Feed has no title."); return false; } if (!hasValidFeedItems(feed)) { Log.e(TAG, "Feed has invalid items"); return false; } return true; } private boolean hasValidFeedItems(Feed feed) { for (FeedItem item : feed.getItems()) { if (item.getTitle() == null) { Log.e(TAG, "Item has no title"); return false; } if (item.getPubDate() == null) { Log.e(TAG, "Item has no pubDate. Using current time as pubDate"); if (item.getTitle() != null) { Log.e(TAG, "Title of invalid item: " + item.getTitle()); } item.setPubDate(new Date()); } } return true; } /** * Delete files that aren't needed anymore */ private void cleanup(Feed feed) { if (feed.getFile_url() != null) { if (new File(feed.getFile_url()).delete()) { Log.d(TAG, "Successfully deleted cache file."); } else { Log.e(TAG, "Failed to delete cache file."); } feed.setFile_url(null); } else { Log.d(TAG, "Didn't delete cache file: File url is not set."); } } public void shutdown() { isActive = false; if (isCollectingRequests) { interrupt(); } } public void submitCompletedDownload(DownloadRequest request) { completedRequests.offer(request); if (isCollectingRequests) { interrupt(); } } } /** * Handles failed downloads. * <p/> * If the file has been partially downloaded, this handler will set the file_url of the FeedFile to the location * of the downloaded file. * <p/> * Currently, this handler only handles FeedMedia objects, because Feeds and FeedImages are deleted if the download fails. */ class FailedDownloadHandler implements Runnable { private DownloadRequest request; private DownloadStatus status; FailedDownloadHandler(DownloadStatus status, DownloadRequest request) { this.request = request; this.status = status; } @Override public void run() { if (request.getFeedfileType() == Feed.FEEDFILETYPE_FEED) { DBWriter.setFeedLastUpdateFailed(request.getFeedfileId(), true); } else if (request.isDeleteOnFailure()) { Log.d(TAG, "Ignoring failed download, deleteOnFailure=true"); } else { File dest = new File(request.getDestination()); if (dest.exists() && request.getFeedfileType() == FeedMedia.FEEDFILETYPE_FEEDMEDIA) { Log.d(TAG, "File has been partially downloaded. Writing file url"); FeedMedia media = DBReader.getFeedMedia(request.getFeedfileId()); media.setFile_url(request.getDestination()); try { DBWriter.setFeedMedia(media).get(); } catch (InterruptedException e) { Log.e(TAG, "FailedDownloadHandler was interrupted"); } catch (ExecutionException e) { Log.e(TAG, "ExecutionException in FailedDownloadHandler: " + e.getMessage()); } } } } } /** * Handles a completed media download. */ class MediaHandlerThread implements Runnable { private DownloadRequest request; private DownloadStatus status; public MediaHandlerThread(@NonNull DownloadStatus status, @NonNull DownloadRequest request) { this.status = status; this.request = request; } @Override public void run() { FeedMedia media = DBReader.getFeedMedia(request.getFeedfileId()); if (media == null) { Log.e(TAG, "Could not find downloaded media object in database"); return; } media.setDownloaded(true); media.setFile_url(request.getDestination()); media.checkEmbeddedPicture(); // enforce check // check if file has chapters ChapterUtils.loadChaptersFromFileUrl(media); // Get duration MediaMetadataRetriever mmr = new MediaMetadataRetriever(); mmr.setDataSource(media.getFile_url()); String durationStr = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); try { media.setDuration(Integer.parseInt(durationStr)); Log.d(TAG, "Duration of file is " + media.getDuration()); } catch (NumberFormatException e) { Log.d(TAG, "Invalid file duration: " + durationStr); } finally { if (mmr != null) { mmr.release(); } } final FeedItem item = media.getItem(); try { // we've received the media, we don't want to autodownload it again if (item != null) { item.setAutoDownload(false); DBWriter.setFeedItem(item).get(); } DBWriter.setFeedMedia(media).get(); if (item != null && UserPreferences.enqueueDownloadedEpisodes() && !DBTasks.isInQueue(DownloadService.this, item.getId())) { DBWriter.addQueueItem(DownloadService.this, item).get(); } } catch (InterruptedException e) { Log.e(TAG, "MediaHandlerThread was interrupted"); } catch (ExecutionException e) { Log.e(TAG, "ExecutionException in MediaHandlerThread: " + e.getMessage()); status = new DownloadStatus(media, media.getEpisodeTitle(), DownloadError.ERROR_DB_ACCESS_ERROR, false, e.getMessage()); } saveDownloadStatus(status); if (GpodnetPreferences.loggedIn() && item != null) { GpodnetEpisodeAction action = new GpodnetEpisodeAction.Builder(item, Action.DOWNLOAD) .currentDeviceId() .currentTimestamp() .build(); GpodnetPreferences.enqueueEpisodeAction(action); } numberOfDownloads.decrementAndGet(); queryDownloadsAsync(); } } /** * Schedules the notification updater task if it hasn't been scheduled yet. */ private void setupNotificationUpdater() { Log.d(TAG, "Setting up notification updater"); if (notificationUpdater == null) { notificationUpdater = new NotificationUpdater(); notificationUpdaterFuture = schedExecutor.scheduleAtFixedRate( notificationUpdater, 5L, 5L, TimeUnit.SECONDS); } } private void cancelNotificationUpdater() { boolean result = false; if (notificationUpdaterFuture != null) { result = notificationUpdaterFuture.cancel(true); } notificationUpdater = null; notificationUpdaterFuture = null; Log.d(TAG, "NotificationUpdater cancelled. Result: " + result); } private class NotificationUpdater implements Runnable { public void run() { handler.post(() -> { Notification n = updateNotifications(); if (n != null) { NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(NOTIFICATION_ID, n); } }); } } private long lastPost = 0; final Runnable postDownloaderTask = new Runnable() { @Override public void run() { List<Downloader> list = Collections.unmodifiableList(downloads); EventBus.getDefault().postSticky(DownloadEvent.refresh(list)); postHandler.postDelayed(postDownloaderTask, 1500); } }; private void postDownloaders() { long now = System.currentTimeMillis(); if (now - lastPost >= 250) { postHandler.removeCallbacks(postDownloaderTask); postDownloaderTask.run(); lastPost = now; } } /** * Checks if the FeedItems of this feed have images that point to the same URL. If two FeedItems * have an image that points to the same URL, the reference of the second item is removed, so * that every image reference is unique. */ @VisibleForTesting public static void removeDuplicateImages(Feed feed) { Set<String> known = new HashSet<String>(); for (FeedItem item : feed.getItems()) { String url = item.hasItemImage() ? item.getImage().getDownload_url() : null; if (url != null) { if (known.contains(url)) { item.setImage(null); } else { known.add(url); } } } } private static String compileNotificationString(List<Downloader> downloads) { List<String> lines = new ArrayList<>(downloads.size()); for (Downloader downloader : downloads) { StringBuilder line = new StringBuilder("\u2022 "); DownloadRequest request = downloader.getDownloadRequest(); switch (request.getFeedfileType()) { case Feed.FEEDFILETYPE_FEED: if (request.getTitle() != null) { line.append(request.getTitle()); } break; case FeedMedia.FEEDFILETYPE_FEEDMEDIA: if (request.getTitle() != null) { line.append(request.getTitle()) .append(" (") .append(request.getProgressPercent()) .append("%)"); } break; default: line.append("Unknown: ").append(request.getFeedfileType()); } lines.add(line.toString()); } return StringUtils.join(lines, '\n'); } }
package org.multibit.hd.hardware.core.messages; /** * <p>Enum to provide the following to application:</p> * <ul> * <li>Identification of protocol messages</li> * </ul> * * <p>These messages are considered to be common across all hardware wallets * supported through MultiBit Hardware.</p> * * @since 0.0.1 * */ public enum ProtocolMessageType { // Connection INITALIZE, PING, // Generic responses SUCCESS, FAILURE, // Setup CHANGE_PIN, WIPE_DEVICE, FIRMWARE_ERASE, FIRMWARE_UPLOAD, // Entropy GET_ENTROPY, ENTROPY, // Key passing GET_PUBLIC_KEY, PUBLIC_KEY, // Load and reset LOAD_DEVICE, RESET_DEVICE, // Signing SIGN_TX, SIMPLE_SIGN_TX, FEATURES, // PIN PIN_MATRIX_REQUEST, PIN_MATRIX_ACK, CANCEL, // Transactions TX_REQUEST, TX_ACK, // Cipher key CIPHER_KEY_VALUE, CLEAR_SESSION, // Settings APPLY_SETTINGS, // Buttons BUTTON_REQUEST, BUTTON_ACK, // Address GET_ADDRESS, ADDRESS, ENTROPY_REQUEST, ENTROPY_ACK, // Message signing SIGN_MESSAGE, VERIFY_MESSAGE, MESSAGE_SIGNATURE, // Message encryption ENCRYPT_MESSAGE, DECRYPT_MESSAGE, // Passphrase PASSPHRASE_REQUEST, PASSPHRASE_ACK, // Transaction size ESTIMATE_TX_SIZE, TX_SIZE, // Recovery RECOVERY_DEVICE, // Word WORD_REQUEST, WORD_ACK, // Debugging messages DEBUG_LINK_DECISION, DEBUG_LINK_GET_STATE, DEBUG_LINK_STATE, DEBUG_LINK_STOP, DEBUG_LINK_LOG, // End of enum ; }
package roart.database.cassandra; import java.util.HashSet; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.io.IOException; import roart.common.config.NodeConfig; import roart.common.constants.Constants; import roart.common.model.FileLocation; import roart.common.model.IndexFiles; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Cluster.Builder; import com.datastax.driver.core.CodecRegistry; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.datastax.driver.core.TypeCodec; import com.datastax.driver.core.UDTValue; import com.datastax.driver.core.UserType; public class CassandraIndexFiles { private Logger log = LoggerFactory.getLogger(CassandraIndexFiles.class); private CassandraConfig config; private static final String TABLE_FILES_NAME = "files"; private static final String TABLE_INDEXFILES_NAME = "indexfiles"; private Session session; public Session getSession() { return session; } /* public void setSession(Session session) { this.session = session; } */ public void createKeyspace( String keyspaceName, String replicationStrategy, int replicationFactor) { StringBuilder sb = new StringBuilder("CREATE KEYSPACE IF NOT EXISTS ") .append(keyspaceName).append(" WITH replication = {") .append("'class':'").append(replicationStrategy) .append("','replication_factor':").append(replicationFactor) .append("};"); String query = sb.toString(); session.execute(query); session.execute("use " + keyspaceName + ";"); } public void createType() { try { StringBuilder sb = new StringBuilder("CREATE TYPE filelocation ( ") .append("node text,") .append("filename text);"); String query = sb.toString(); session.execute(query); } catch (Exception e) { log.error(Constants.EXCEPTION, e); } CodecRegistry codecRegistry = session.getCluster().getConfiguration().getCodecRegistry(); UserType addressType = session.getCluster().getMetadata().getKeyspace("library").getUserType("filelocation"); TypeCodec<UDTValue> addressTypeCodec = codecRegistry.codecFor(addressType); FilelocationCodec myJsonCodec = new FilelocationCodec(addressTypeCodec, FileLocation.class); codecRegistry.register(myJsonCodec); /* JsonCodec<FileLocation> myJsonCodec = new JsonCodec<>(FileLocation.class); CodecRegistry myCodecRegistry = session.getCluster().getConfiguration().getCodecRegistry(); myCodecRegistry.register(myJsonCodec); */ } public void createTable() { StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS ") .append(TABLE_FILES_NAME).append("(") .append("filename text PRIMARY KEY, ") .append("md5 text);"); String query = sb.toString(); System.out.println("q1"); try { session.execute(query); } catch (Exception e) { e.printStackTrace(); } System.out.println("q2"); StringBuilder sb2 = new StringBuilder("CREATE TABLE IF NOT EXISTS ") .append(TABLE_INDEXFILES_NAME).append("(") .append("md5 text PRIMARY KEY, ") .append("indexed text, ") .append("timestamp text, ") .append("timeindex text, ") .append("timeclass text, ") .append("classification text, ") .append("convertsw text, ") .append("converttime text, ") .append("failed int, ") .append("failedreason text, ") .append("timeoutreason text, ") .append("noindexreason text, ") .append("language text, ") .append("node text, ") .append("filename text, ") .append("filelocation set<frozen<filelocation>>);"); String query2 = sb2.toString(); System.out.println("q3"); try { session.execute(query2); } catch (Exception e) { e.printStackTrace(); } System.out.println("q4"); } // column families private final String indexcf = "if"; private final String flcf = "fl"; private final String filescf = "fi"; // column qualifiers private final String md5q = "md5"; private final String indexedq = "indexed"; private final String timestampq = "timestamp"; private final String timeindexq = "timeindex"; private final String timeclassq = "timeclass"; private final String classificationq = "classification"; private final String convertswq = "convertsw"; private final String converttimeq = "converttime"; private final String failedq = "failed"; private final String failedreasonq = "failedreason"; private final String timeoutreasonq = "timeoutreason"; private final String noindexreasonq = "noindexreason"; private final String languageq = "language"; private final String nodeq = "node"; private final String filenameq = "filename"; private final String filelocationq = "filelocation"; public CassandraIndexFiles(Session session, String nodename, NodeConfig nodeConf) { String port = "9042"; String host = "localhost"; if (session == null) { port = nodeConf.getCassandraPort(); host = nodeConf.getCassandraHost(); } config = new CassandraConfig(); if (session != null) { this.session = session; } else { Cluster cluster; Builder b = Cluster.builder().addContactPoint(host); if (port != null) { b.withPort(Integer.valueOf(port)); } log.info("Cluster build"); cluster = b.build(); log.info("Cluster built"); this.session = cluster.connect(); log.info("Cluster connected"); log.info("Session {}", this.session.getCluster().getClusterName()); } config.setSession(this.session); config.setNodename(nodename); System.out.println("ct1"); try { createKeyspace("library", "SimpleStrategy", 1); createType(); createTable(); } catch (Exception e) { e.printStackTrace(); } System.out.println("ct2"); } public void put(IndexFiles ifile) throws Exception { StringBuilder sb = new StringBuilder("BEGIN BATCH ") .append("UPDATE ").append(TABLE_INDEXFILES_NAME).append(" set "); if (ifile.getIndexed() != null) { sb.append(indexedq + " = '" + ifile.getIndexed() + "', "); } if (ifile.getTimestamp() != null) { sb.append(timestampq + " = '" + ifile.getTimestamp() + "', "); } if (ifile.getTimeindex() != null) { sb.append(timeindexq + " = '" + ifile.getTimeindex() + "', "); } if (ifile.getTimeclass() != null) { sb.append(timeclassq + " = '" + ifile.getTimeclass() + "', "); } if (ifile.getClassification() != null) { sb.append(classificationq + " = '" + ifile.getClassification() + "', "); } if (ifile.getConvertsw() != null) { sb.append(convertswq + " = '" + ifile.getConvertsw() + "', "); } if (ifile.getConverttime() != null) { sb.append(converttimeq + " = '" + ifile.getConverttime() + "', "); } if (ifile.getFailed() != null) { sb.append(failedq + " = " +"" + ifile.getFailed() + ", "); } if (ifile.getFailedreason() != null) { sb.append(failedreasonq + " = '" +ifile.getFailedreason() + "', "); } if (ifile.getTimeoutreason() != null) { sb.append(timeoutreasonq + " = '" +ifile.getTimeoutreason() + "', "); } if (ifile.getNoindexreason() != null) { sb.append(noindexreasonq + " = '" +ifile.getNoindexreason() + "', "); } if (ifile.getLanguage() != null) { sb.append(languageq + " = '" +ifile.getLanguage() + "', "); } if (ifile.getFilelocations() != null) { sb.append(filelocationq + " = ? "); } sb.append("where " + md5q + " = '" + ifile.getMd5() + "'; apply batch;"); //log.info("hbase " + ifile.getMd5()); int i = -1; /* for (FileLocation file : ifile.getFilelocations()) { StringBuilder sb2 = new StringBuilder("BEGIN BATCH ") .append("UPDATE ").append(TABLE_FILES_NAME).append(" set "); sb2.append(md5q + " = " + ifile.getMd5() + ", "); if (file.getFilename() != null) { sb2.append(md5q + " = " + file.getFilename() + ", "); } session.execute(sb2.toString()); i++; } */ String str = sb.toString(); System.out.println("put1" + sb.toString()); PreparedStatement prepared = session.prepare(str); BoundStatement bound = prepared.bind(ifile.getFilelocations()); session.execute(bound); System.out.println("put2"); /* // now, delete the rest (or we would get some old historic content) for (; i < ifile.getMaxfilelocations(); i++) { StringBuilder sb3 = new StringBuilder("BEGIN BATCH ") .append("DELETE FROM ").append(TABLE_INDEXFILES_NAME).append(" where ") .append(md5q + " = " + ifile.getMd5()); session.execute(sb3.toString()); } System.out.println("put3"); */ put(ifile.getMd5(), ifile.getFilelocations()); // or if still to slow, simply get current (old) indexfiles Set<FileLocation> curfls = getFilelocationsByMd5(ifile.getMd5()); curfls.removeAll(ifile.getFilelocations()); // delete the files no longer associated to the md5 for (FileLocation fl : curfls) { if (!fl.isLocal(config.getNodename())) { continue; } String name = fl.toString(); log.info("Cassandra delete {}", name); StringBuilder sb3 = new StringBuilder("BEGIN BATCH ") .append("DELETE FROM ").append(TABLE_FILES_NAME).append(" where ") .append(filenameq + " = '" + name + "';apply batch;"); System.out.println("del " + sb3.toString()); session.execute(sb3.toString()); } System.out.println("put4"); } public void put(String md5, Set<FileLocation> files) throws Exception { //HTable /*Interface*/ filesTable = new HTable(conf, "index"); for (FileLocation file : files) { System.out.println("files put " + md5 + " " + file); String filename = getFile(file); StringBuilder sb = new StringBuilder("BEGIN BATCH ") .append("UPDATE ").append(TABLE_FILES_NAME).append(" set "); sb.append(md5q + " = '" + md5 + "' "); sb.append("where " + filenameq + " = '" + filename + "'; apply batch;"); String str = sb.toString(); System.out.println("put1" + sb.toString()); session.execute(str); } } public IndexFiles get(Row row) { String md5 = row.getString(md5q); IndexFiles ifile = new IndexFiles(md5); //ifile.setMd5(bytesToString(index.getValue(indexcf, md5q))); ifile.setIndexed(new Boolean(row.getString(indexedq))); ifile.setTimeindex(row.getString(timeindexq)); ifile.setTimestamp(row.getString(timestampq)); ifile.setTimeclass(row.getString(timeclassq)); ifile.setClassification(row.getString(classificationq)); ifile.setConvertsw(row.getString(convertswq)); ifile.setConverttime(row.getString(converttimeq)); ifile.setFailed(row.getInt(failedq)); ifile.setFailedreason(row.getString(failedreasonq)); ifile.setTimeoutreason(row.getString(timeoutreasonq)); ifile.setNoindexreason(row.getString(noindexreasonq)); ifile.setLanguage(row.getString(languageq)); ifile.setFilelocations(row.getSet(filelocationq, FileLocation.class)); ifile.setUnchanged(); return ifile; } public Map<String, IndexFiles> get(Set<String> md5s) { Map<String, IndexFiles> indexFilesMap = new HashMap<>(); for (String md5 : md5s) { IndexFiles indexFile = get(md5); if (indexFile != null) { indexFilesMap.put(md5, indexFile); } } return indexFilesMap; } public IndexFiles get(String md5) { StringBuilder sb3 = new StringBuilder("SELECT * FROM ").append(TABLE_INDEXFILES_NAME).append(" where ") .append(md5q + " = '" + md5).append("';"); System.out.println(sb3.toString()); ResultSet resultSet = session.execute(sb3.toString()); for (Row row : resultSet) { return get(row); } return null; } public IndexFiles getIndexByFilelocation(FileLocation fl) { String md5 = getMd5ByFilelocation(fl); if (md5.length() == 0) { return null; } return get(md5); } public String getMd5ByFilelocation(FileLocation fl) { String name = getFile(fl); Set<FileLocation> flset = new HashSet<>(); StringBuilder sb3 = new StringBuilder("SELECT * FROM ").append(TABLE_FILES_NAME).append(" where ") .append(filenameq + " = '" + name + "';"); ResultSet resultSet = session.execute(sb3.toString()); for (Row row : resultSet) { return row.getString(md5q); } return null; } public Set<FileLocation> getFilelocationsByMd5(String md5) throws Exception { Set<FileLocation> flset = new HashSet<>(); StringBuilder sb3 = new StringBuilder("") .append("SELECT * FROM ").append(TABLE_FILES_NAME).append(" where ") .append(md5q + " = '" + md5 + "' ALLOW FILTERING;"); System.out.println("sb3 " + sb3.toString()); ResultSet resultSet = session.execute(sb3.toString()); //System.out.println("h0 " + resultSet.all().size()); for (Row row : resultSet) { System.out.println("h1 " + row); FileLocation fl = getFileLocation(row.getString(filenameq)); if (fl != null) { flset.add(fl); } } return flset; } public List<IndexFiles> getAll() throws Exception { StringBuilder sb = new StringBuilder("SELECT * FROM ") .append(TABLE_INDEXFILES_NAME).append(";"); String query = sb.toString(); ResultSet resultSet = session.execute(query); List<IndexFiles> retlist = new ArrayList<>(); for (Row row : resultSet) { retlist.add(get(row)); } return retlist; } public IndexFiles ensureExistenceNot(String md5) throws Exception { try { //HTable /*Interface*/ filesTable = new HTable(conf, "index"); //Put put = new Put(md5)); //indexTable.put(put); } catch (Exception e) { log.error(Constants.EXCEPTION, e); } IndexFiles i = new IndexFiles(md5); //i.setMd5(md5); return i; } public String getFile(FileLocation fl) { if (fl == null) { return null; } return fl.toString(); } public FileLocation getFileLocation(String fl) { if (fl == null) { return null; } return new FileLocation(fl, config.getNodename(), null); } private String convertNullNot(String s) { if (s == null) { return ""; } return s; } private String convert0(String s) { if (s == null) { return "0"; } return s; } public void flush() throws Exception { } public void commit() throws Exception { } public void close() throws Exception { log.info("closing db"); session.close(); } public Set<String> getAllMd5() throws Exception { Set<String> md5s = new HashSet<String>(); StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_INDEXFILES_NAME); ResultSet resultSet = session.execute(sb.toString()); for (Row row : resultSet.all()) { String md5 = row.getString(md5q); md5s.add(md5); } return md5s; } public Set<String> getLanguages() throws Exception { StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_INDEXFILES_NAME); ResultSet resultSet = session.execute(sb.toString()); Set<String> languages = new HashSet<>(); for (Row row : resultSet.all()) { String lang = row.getString("language"); languages.add(lang); } return languages; } public void delete(IndexFiles index) throws Exception { StringBuilder sb = new StringBuilder("BEGIN BATCH ") .append("DELETE FROM ").append(TABLE_INDEXFILES_NAME).append(" where ") .append(md5q + " = '" + index.getMd5()).append("'; apply batch;"); session.execute(sb.toString()); Set<FileLocation> curfls = getFilelocationsByMd5(index.getMd5()); System.out.println("curfls " + curfls.size()); //curfls.removeAll(index.getFilelocations()); //System.out.println("curfls " + curfls.size()); // delete the files no longer associated to the md5 for (FileLocation fl : curfls) { String name = fl.toString(); log.info("Cassandra delete {}", name); StringBuilder sb3 = new StringBuilder("BEGIN BATCH ") .append("DELETE FROM ").append(TABLE_FILES_NAME).append(" where ") .append(filenameq + " = '" + name + "'; apply batch;"); session.execute(sb3.toString()); } } public void destroy() throws Exception { config.getSession().close(); } }
package org.md2k.datakitapi.source.datasource; public class DataSourceType { public static final String ACCELEROMETER = "ACCELEROMETER"; public static final String GYROSCOPE = "GYROSCOPE"; public static final String COMPASS = "COMPASS"; public static final String AMBIENT_LIGHT = "AMBIENT_LIGHT"; public static final String PRESSURE = "PRESSURE"; public static final String PROXIMITY = "PROXIMITY"; public static final String LOCATION = "LOCATION"; public static final String DISTANCE = "DISTANCE"; public static final String HEART_RATE = "HEART_RATE"; public static final String SPEED = "SPEED"; public static final String STEP_COUNT = "STEP_COUNT"; public static final String PACE = "PACE"; public static final String MOTION_TYPE = "MOTION_TYPE"; public static final String ULTRA_VIOLET_RADIATION = "ULTRA_VIOLET_RADIATION"; public static final String BAND_CONTACT = "BAND_CONTACT"; public static final String CALORY_BURN = "CALORY_BURN"; public static final String ECG = "ECG"; public static final String RESPIRATION = "RESPIRATION"; public static final String GALVANIC_SKIN_RESPONSE = "GALVANIC_SKIN_RESPONSE"; public static final String ALTIMETER = "ALTIMETER"; public static final String AIR_PRESSURE = "AIR_PRESSURE"; public static final String RR_INTERVAL = "RR_INTERVAL"; public static final String AMBIENT_TEMPERATURE = "AMBIENT_TEMPERATURE"; public static final String SKIN_TEMPERATURE = "SKIN_TEMPERATURE"; public static final String BATTERY = "BATTERY"; public static final String CPU = "CPU"; public static final String MEMORY = "MEMORY"; public static final String AUTOSENSE = "AUTOSENSE"; public static final String ACCELEROMETER_X = "ACCELEROMETER_X"; public static final String ACCELEROMETER_Y = "ACCELEROMETER_Y"; public static final String ACCELEROMETER_Z = "ACCELEROMETER_Z"; public static final String GYROSCOPE_X = "GYROSCOPE_X"; public static final String GYROSCOPE_Y = "GYROSCOPE_Y"; public static final String GYROSCOPE_Z = "GYROSCOPE_Z"; public static final String EMA = "EMA"; public static final String STATUS = "STATUS"; public static final String LOG="LOG"; public static final String TIMEZONE = "TIMEZONE"; public static final String PRIVACY = "PRIVACY"; public static final String STUDY_INFO = "STUDY_INFO"; public static final String USER_INFO = "USER_INFO"; public static final String SLEEP = "SLEEP"; public static final String WAKEUP = "WAKEUP"; public static final String DAY_START="DAY_START"; public static final String DAY_END="DAY_END"; public static final String STRESS_PROBABILITY="STRESS_PROBABILITY"; public static final String STRESS_LABEL="STRESS_LABEL"; public static final String STUDY_START="STUDY_START"; public static final String STUDY_END="STUDY_END"; public static final String STRESS_ACTIVITY = "STRESS_ACTIVITY"; public static final String CSTRESS_FEATURE_VECTOR = "CSTRESS_FEATURE_VECTOR"; public static final String ORG_MD2K_CSTRESS_DATA_RIP_QUALITY = "ORG_MD2K_CSTRESS_DATA_RIP_QUALITY"; public static final String ORG_MD2K_CSTRESS_DATA_ECG_QUALITY = "ORG_MD2K_CSTRESS_DATA_ECG_QUALITY"; public static final String ORG_MD2K_CSTRESS_STRESS_EPISODE_CLASSIFICATION = "ORG_MD2K_CSTRESS_STRESS_EPISODE_CLASSIFICATION"; public static final String CSTRESS_FEATURE_VECTOR_RIP = "CSTRESS_FEATURE_VECTOR_RIP"; public static final String STRESS_RIP_PROBABILITY = "STRESS_RIP_PROBABILITY"; public static final String STRESS_RIP_LABEL = "STRESS_RIP_LABEL"; public static final String ACTIVITY = "ACCELEROMETER_ACTIVITY_DEVIATION"; public static final String PUFF_PROBABILITY = "PUFF_PROBABILITY"; public static final String PUFF_LABEL = "PUFF_LABEL"; public static final String PUFFMARKER_FEATURE_VECTOR = "PUFFMARKER_FEATURE_VECTOR"; public static final String PUFFMARKER_SMOKING_EPISODE = "PUFFMARKER_SMOKING_EPISODE"; public static final String NOTIFICATION_REQUEST = "NOTIFICATION_REQUEST"; public static final String NOTIFICATION_DELIVER = "NOTIFICATION_DELIVER"; public static final String NOTIFICATION_ACKNOWLEDGE = "NOTIFICATION_ACKNOWLEDGE"; public static final String DATA_QUALITY="DATA_QUALITY"; public static final String TYPE_OF_DAY="TYPE_OF_DAY"; public static final String EVENT="EVENT"; public static final String INCENTIVE="INCENTIVE"; }
package com.github.dandelion.datatables.jsp.tag; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dandelion.datatables.core.aggregator.ResourceAggregator; import com.github.dandelion.datatables.core.asset.CssResource; import com.github.dandelion.datatables.core.asset.JsResource; import com.github.dandelion.datatables.core.asset.ResourceType; import com.github.dandelion.datatables.core.asset.WebResources; import com.github.dandelion.datatables.core.cache.AssetCache; import com.github.dandelion.datatables.core.compressor.ResourceCompressor; import com.github.dandelion.datatables.core.configuration.Configuration; import com.github.dandelion.datatables.core.constants.CdnConstants; import com.github.dandelion.datatables.core.exception.AttributeProcessingException; import com.github.dandelion.datatables.core.exception.BadConfigurationException; import com.github.dandelion.datatables.core.exception.CompressionException; import com.github.dandelion.datatables.core.exception.DataNotFoundException; import com.github.dandelion.datatables.core.exception.ExportException; import com.github.dandelion.datatables.core.export.ExportDelegate; import com.github.dandelion.datatables.core.export.ExportProperties; import com.github.dandelion.datatables.core.export.ExportType; import com.github.dandelion.datatables.core.generator.WebResourceGenerator; import com.github.dandelion.datatables.core.html.HtmlTable; import com.github.dandelion.datatables.core.util.DandelionUtils; import com.github.dandelion.datatables.core.util.RequestHelper; import com.github.dandelion.datatables.core.util.StringUtils; /** * <p> * Tag used to generate a HTML table. * * @author Thibault Duchateau * @since 0.1.0 */ public class TableTag extends AbstractTableTag { private static final long serialVersionUID = 4528524566511084446L; // Logger private static Logger logger = LoggerFactory.getLogger(TableTag.class); private final static char[] DISALLOWED_CHAR = {'-'}; public TableTag(){ localConf = new HashMap<Configuration, Object>(); } /** * {@inheritDoc} */ public int doStartTag() throws JspException { // We must ensure that the chosen table id doesn't contain any of the // disallowed character because a Javascript variable will be created // using this name if(StringUtils.containsAny(id, DISALLOWED_CHAR)){ throw new JspException("The 'id' attribute cannot contain one of the following characters: " + String.valueOf(DISALLOWED_CHAR)); } // Init the table with its DOM id and a generated random number table = new HtmlTable(id, (HttpServletRequest) pageContext.getRequest(), confGroup); try { Configuration.applyConfiguration(table.getTableConfiguration(), localConf); } catch (AttributeProcessingException e) { throw new JspException(e); } // Just used to identify the first row (header) iterationNumber = 1; // The table data are loaded using AJAX source if ("AJAX".equals(this.loadingType)) { this.table.addFooterRow(); this.table.addHeaderRow(); this.table.addRow(); return EVAL_BODY_BUFFERED; } // The table data are loaded using a DOM source (Collection) else if ("DOM".equals(this.loadingType)) { this.table.addFooterRow(); this.table.addHeaderRow(); return processIteration(); } // Never reached return SKIP_BODY; } /** * {@inheritDoc} */ public int doAfterBody() throws JspException { this.iterationNumber++; return processIteration(); } /** * {@inheritDoc} */ public int doEndTag() throws JspException { // The table is being exported if (RequestHelper.isTableBeingExported(pageContext.getRequest(), table)) { return setupExport(); } // The table must be generated and displayed else { return setupHtmlGeneration(); } } /** * Set up the export properties, before the filter intercepts the response. * * @return allways SKIP_PAGE, because the export filter will override the * response with the exported data instead of displaying the page. * @throws JspException * if something went wrong during export. */ private int setupExport() throws JspException { HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); HttpServletResponse response = (HttpServletResponse) pageContext.getResponse(); // Init the export properties ExportProperties exportProperties = new ExportProperties(); ExportType currentExportType = getCurrentExportType(); exportProperties.setCurrentExportType(currentExportType); exportProperties.setExportConf(table.getTableConfiguration().getExportConf(currentExportType)); exportProperties.setFileName(table.getTableConfiguration().getExportConf(currentExportType).getFileName()); this.table.getTableConfiguration().setExportProperties(exportProperties); this.table.getTableConfiguration().setExporting(true); try { // Call the export delegate ExportDelegate exportDelegate = new ExportDelegate(table, exportProperties, request); exportDelegate.launchExport(); } catch (ExportException e) { logger.error("Something went wront with the Dandelion export configuration."); throw new JspException(e); } catch (BadConfigurationException e) { logger.error("Something went wront with the Dandelion configuration."); throw new JspException(e); } response.reset(); return SKIP_PAGE; } /** * Set up the HTML table generation. * * @return allways EVAL_PAGE to keep evaluating the page. * @throws JspException * if something went wrong during the processing. */ private int setupHtmlGeneration() throws JspException { HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); WebResources webResources = null; this.table.getTableConfiguration().setExporting(false); // TODO retirer cette fonction // Register all activated features registerFeatures(); try { // First we check if the DataTables configuration already exist in the cache String keyToTest = RequestHelper.getCurrentURIWithParameters(request) + "|" + table.getId(); if(DandelionUtils.isDevModeEnabled() || !AssetCache.cache.containsKey(keyToTest)){ logger.debug("No asset for the key {}. Generating...", keyToTest); // Init the web resources generator WebResourceGenerator contentGenerator = new WebResourceGenerator(); // Generate the web resources (JS, CSS) and wrap them into a // WebResources POJO webResources = contentGenerator.generateWebResources(table); logger.debug("Web content generated successfully"); AssetCache.cache.put(keyToTest, webResources); logger.debug("Cache updated with new web resources"); } else{ logger.debug("Asset(s) already exist, retrieving content from cache..."); webResources = (WebResources) AssetCache.cache.get(keyToTest); } // Aggregation if (table.getTableConfiguration().getMainAggregatorEnable() != null && table.getTableConfiguration().getMainAggregatorEnable()) { logger.debug("Aggregation enabled"); ResourceAggregator.processAggregation(webResources, table); } // Compression if (table.getTableConfiguration().getMainCompressorEnable() != null && table.getTableConfiguration().getMainCompressorEnable()) { logger.debug("Compression enabled"); ResourceCompressor.processCompression(webResources, table); } // <link> HTML tag generation if (table.getTableConfiguration().getExtraCdn()) { generateLinkTag(CdnConstants.CDN_DATATABLES_CSS); } for (Entry<String, CssResource> entry : webResources.getStylesheets().entrySet()) { if(entry.getValue().getType().equals(ResourceType.EXTERNAL)){ generateLinkTag(entry.getValue().getLocation()); } else{ String src = RequestHelper.getAssetSource(entry.getKey(), this.table, request, false); generateLinkTag(src); } } // HTML generation pageContext.getOut().println(this.table.toHtml()); // <script> HTML tag generation if (table.getTableConfiguration().getExtraCdn()) { generateScriptTag(CdnConstants.CDN_DATATABLES_JS_MIN); } for (Entry<String, JsResource> entry : webResources.getJavascripts().entrySet()) { String src = RequestHelper.getAssetSource(entry.getKey(), this.table, request, false); generateScriptTag(src); } // Main Javascript file String src = RequestHelper.getAssetSource(webResources.getMainJsFile().getName(), this.table, request, true); generateScriptTag(src); } catch (IOException e) { logger.error("Something went wront with the datatables tag"); throw new JspException(e); } catch (CompressionException e) { logger.error("Something went wront with the compressor."); throw new JspException(e); } catch (BadConfigurationException e) { logger.error("Something went wront with the Dandelion configuration. Please check your Dandelion.properties file"); throw new JspException(e); } catch (DataNotFoundException e) { logger.error("Something went wront with the data provider."); throw new JspException(e); } return EVAL_PAGE; } /** * TODO */ public void release() { // TODO Auto-generated method stub super.release(); // TODO } public void setAutoWidth(Boolean autoWidth) { localConf.put(Configuration.FEATURE_AUTOWIDTH, autoWidth); } public void setDeferRender(String deferRender) { localConf.put(Configuration.AJAX_DEFERRENDER, deferRender); } public void setFilter(Boolean filterable) { localConf.put(Configuration.FEATURE_FILTERABLE, filterable); } public void setInfo(Boolean info) { localConf.put(Configuration.FEATURE_INFO, info); } public void setPaginate(Boolean paginate) { localConf.put(Configuration.FEATURE_PAGINATE, paginate); } public void setLengthChange(Boolean lengthChange) { localConf.put(Configuration.FEATURE_LENGTHCHANGE, lengthChange); } public void setProcessing(Boolean processing) { localConf.put(Configuration.AJAX_PROCESSING, processing); } public void setServerSide(Boolean serverSide) { localConf.put(Configuration.AJAX_SERVERSIDE, serverSide); } public void setPaginationType(String paginationType) { localConf.put(Configuration.FEATURE_PAGINATIONTYPE, paginationType); } public void setSort(Boolean sort) { localConf.put(Configuration.FEATURE_SORT, sort); } public void setStateSave(String stateSave) { localConf.put(Configuration.FEATURE_STATESAVE, stateSave); } public void setFixedHeader(String fixedHeader) { localConf.put(Configuration.PLUGIN_FIXEDHEADER, fixedHeader); } public void setScroller(String scroller) { localConf.put(Configuration.PLUGIN_SCROLLER, scroller); } public void setColReorder(String colReorder) { localConf.put(Configuration.PLUGIN_COLREORDER, colReorder); } public void setScrollY(String scrollY) { localConf.put(Configuration.FEATURE_SCROLLY, scrollY); } public void setScrollCollapse(String scrollCollapse) { localConf.put(Configuration.FEATURE_SCROLLCOLLAPSE, scrollCollapse); } public void setFixedPosition(String fixedPosition) { localConf.put(Configuration.PLUGIN_FIXEDPOSITION, fixedPosition); } public void setLabels(String labels) { localConf.put(Configuration.EXTRA_LABELS, labels); } public void setOffsetTop(Integer fixedOffsetTop) { localConf.put(Configuration.PLUGIN_FIXEDOFFSETTOP, fixedOffsetTop); } public void setCdn(Boolean cdn) { localConf.put(Configuration.EXTRA_CDN, cdn); } public void setExport(String export) { localConf.put(Configuration.EXPORT_TYPES, export); } public String getLoadingType() { return this.loadingType; } public void setUrl(String url) { localConf.put(Configuration.AJAX_SOURCE, url); this.loadingType = "AJAX"; this.url = url; } public void setJqueryUI(String jqueryUI) { localConf.put(Configuration.FEATURE_JQUERYUI, jqueryUI); } public void setPipelining(String pipelining) { localConf.put(Configuration.AJAX_PIPELINING, pipelining); } public void setPipeSize(Integer pipeSize){ localConf.put(Configuration.AJAX_PIPESIZE, pipeSize); } public void setExportLinks(String exportLinks) { localConf.put(Configuration.EXPORT_LINKS, exportLinks); } public void setTheme(String theme) { localConf.put(Configuration.EXTRA_THEME, theme); } public void setThemeOption(String themeOption) { localConf.put(Configuration.EXTRA_THEMEOPTION, themeOption); } public void setFooter(String footer) { this.footer = footer; } public void setAppear(String appear) { localConf.put(Configuration.EXTRA_APPEAR, appear); } public void setLengthMenu(String lengthMenu){ localConf.put(Configuration.FEATURE_LENGTHMENU, lengthMenu); } public void setCssStripes(String cssStripesClasses){ localConf.put(Configuration.CSS_STRIPECLASSES, cssStripesClasses); } public void setServerData(String serverData) { localConf.put(Configuration.AJAX_SERVERDATA, serverData); } public void setServerParams(String serverParams) { localConf.put(Configuration.AJAX_SERVERPARAM, serverParams); } public void setServerMethod(String serverMethod) { localConf.put(Configuration.AJAX_SERVERMETHOD, serverMethod); } public void setDisplayLength(Integer displayLength) { localConf.put(Configuration.FEATURE_DISPLAYLENGTH, displayLength); } public void setDom(String dom) { localConf.put(Configuration.FEATURE_DOM, dom); } public void setFeatures(String customFeatures) { localConf.put(Configuration.EXTRA_CUSTOMFEATURES, customFeatures); } public void setPlugins(String customPlugins) { localConf.put(Configuration.EXTRA_CUSTOMPLUGINS, customPlugins); } public void setConfGroup(String confGroup) { this.confGroup = confGroup; } public void setData(Collection<Object> data) { this.loadingType = "DOM"; this.data = data; Collection<Object> dataTmp = (Collection<Object>) data; if (dataTmp != null && dataTmp.size() > 0) { iterator = dataTmp.iterator(); } else { // TODO afficher un message d'erreur // TODO afficher une alerte javascript iterator = null; currentObject = null; } } public void setRowIdBase(String rowIdBase) { this.rowIdBase = rowIdBase; } public void setRowIdPrefix(String rowIdPrefix) { this.rowIdPrefix = rowIdPrefix; } public void setRowIdSufix(String rowIdSufix) { this.rowIdSufix = rowIdSufix; } public void setCssStyle(String cssStyle) { localConf.put(Configuration.CSS_STYLE, cssStyle); } public void setCssClass(String cssClass) { localConf.put(Configuration.CSS_CLASS, cssClass); } }
//$HeadURL: svn+ssh://lbuesching@svn.wald.intevation.de/deegree/base/trunk/resources/eclipse/files_template.xml $ package org.deegree.client.generic; import static org.deegree.commons.utils.CollectionUtils.unzipPair; import static org.deegree.commons.utils.JavaUtils.generateToString; import static org.deegree.services.controller.FrontControllerStats.getKVPRequests; import static org.slf4j.LoggerFactory.getLogger; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeSet; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.event.AjaxBehaviorEvent; import javax.faces.model.SelectItem; import javax.faces.model.SelectItemGroup; import lombok.Getter; import lombok.Setter; import org.apache.commons.httpclient.HttpException; import org.deegree.commons.utils.net.HttpUtils; import org.slf4j.Logger; @ManagedBean @SessionScoped public class RequestBean implements Serializable { private static final long serialVersionUID = 293894352421399345L; private static final Logger LOG = getLogger( RequestBean.class ); @Getter @Setter private String targetUrl; @Getter @Setter private String selectedService; @Getter @Setter private String selectedReqProfile; @Getter @Setter private String selectedRequest; @Getter private List<String> services; private List<String> requestProfiles; private List<SelectItem> requests; private String request; @Getter private String kvpRequestSel; private TreeSet<String> originalKvpRequests = new TreeSet<String>( (Collection) unzipPair( (Collection) getKVPRequests() ).second ); @Getter private TreeSet<String> kvpRequests = new TreeSet<String>( originalKvpRequests ); @Getter private boolean kvpRequestIsImage = false; @Getter @Setter private String requestFilter; @Getter private String response; // SERVICE // -- PROFILE private HashMap<String, Map<String, Map<String, List<String>>>> allRequests = new HashMap<String, Map<String, Map<String, List<String>>>>(); @PostConstruct public void init() { ExternalContext ctx = FacesContext.getCurrentInstance().getExternalContext(); URL url; try { url = new URL( ctx.getRequestScheme(), ctx.getRequestServerName(), ctx.getRequestServerPort(), ctx.getRequestContextPath() ); this.targetUrl = url.toExternalForm() + "/services"; } catch ( MalformedURLException e ) { LOG.debug( "Constructing the url was a problem..." ); LOG.trace( "Stack trace:", e ); } initRequestMap(); List<String> services = new ArrayList<String>(); for ( String service : allRequests.keySet() ) { services.add( service ); } this.services = services; if ( services.size() > 0 ) this.selectedService = services.get( 0 ); setReqestProfiles(); if ( requestProfiles.size() > 0 ) this.selectedReqProfile = requestProfiles.get( 0 ); setRequests(); if ( requests.size() > 0 ) { for ( SelectItem sel : requests ) { if ( !( sel instanceof SelectItemGroup ) ) { this.selectedRequest = (String) sel.getValue(); } } } loadExample(); } public void sendRequest() { LOG.debug( "Try to send the following request to " + targetUrl + " : \n" + request ); if ( targetUrl != null && targetUrl.length() > 0 && request != null && request.length() > 0 ) { Map<String, String> header = new HashMap<String, String>(); InputStream is = new ByteArrayInputStream( request.getBytes() ); try { this.response = HttpUtils.post( HttpUtils.UTF8STRING, targetUrl, is, header ); } catch ( HttpException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } } public List<String> getRequestProfiles() { setReqestProfiles(); return requestProfiles; } public List<SelectItem> getRequests() { setRequests(); return requests; } public void setRequest( String request ) { this.request = request; } public String getRequest() { loadExample(); return request; } private void initRequestMap() { // TODO: replace with user directory, if available String realPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath( "/requests" ); File requestsBaseDir = new File( realPath ); String[] serviceTypes = requestsBaseDir.list(); if ( serviceTypes != null && serviceTypes.length > 0 ) { Arrays.sort( serviceTypes ); for ( String serviceType : serviceTypes ) { if ( ignoreFile( serviceType ) ) { continue; } // for each service subdir (wfs, wms, etc.) File serviceDir = new File( requestsBaseDir, serviceType ); String[] profileDirs = serviceDir.list(); Map<String, Map<String, List<String>>> requestProfiles = new HashMap<String, Map<String, List<String>>>(); if ( profileDirs != null && profileDirs.length > 0 ) { Arrays.sort( profileDirs ); for ( String profile : profileDirs ) { if ( ignoreFile( profile ) ) { continue; } // for each profile subdir (demo, philosopher, etc.) File profileDir = new File( serviceDir, profile ); String[] requestTypeDirs = profileDir.list(); Map<String, List<String>> requestTypes = new HashMap<String, List<String>>(); if ( requestTypeDirs != null && requestTypeDirs.length > 0 ) { Arrays.sort( requestTypeDirs ); for ( String requestType : requestTypeDirs ) { if ( ignoreFile( requestType ) ) { continue; } // for each request type subdir (GetCapabilities, GetFeature, etc.) File requestTypeDir = new File( profileDir, requestType + File.separator + "xml" ); String[] requests = requestTypeDir.list( new FilenameFilter() { public boolean accept( File dir, String name ) { if ( name.toLowerCase().endsWith( ".xml" ) ) { return true; } return false; } } ); List<String> requestUrls = new ArrayList<String>(); if ( requests != null && requests.length > 0 ) { Arrays.sort( requests ); for ( int l = 0; l < requests.length; l++ ) { String requestUrl = "requests/" + serviceType + "/" + profile + "/" + requestType + "/xml/" + requests[l]; // for each request example requestUrls.add( requestUrl ); } } requestTypes.put( requestType, requestUrls ); } } requestProfiles.put( profile, requestTypes ); } } allRequests.put( serviceType, requestProfiles ); } } } boolean ignoreFile( String name ) { return name.endsWith( "CVS" ) || name.startsWith( ".svn" ); } private void setReqestProfiles() { List<String> profiles = new ArrayList<String>(); if ( selectedService != null ) { for ( String s : allRequests.keySet() ) { if ( selectedService.equals( s ) ) { for ( String profile : allRequests.get( s ).keySet() ) { profiles.add( profile ); } } } } this.requestProfiles = profiles; } private void setRequests() { selectedRequest = null; List<SelectItem> types = new ArrayList<SelectItem>(); for ( String s : allRequests.keySet() ) { if ( selectedService != null && selectedService.equals( s ) ) { for ( String p : allRequests.get( s ).keySet() ) { if ( selectedReqProfile != null && selectedReqProfile.equals( p ) ) { Map<String, List<String>> ts = allRequests.get( s ).get( p ); for ( String t : ts.keySet() ) { SelectItem[] urls = new SelectItem[ts.get( t ).size()]; int i = 0; for ( String url : ts.get( t ) ) { String fileName = url.substring( url.lastIndexOf( File.separator ) + 1, url.length() ); urls[i++] = new SelectItem( url, fileName ); if ( selectedRequest == null ) selectedRequest = url; } SelectItemGroup typeGrp = new SelectItemGroup( t, "", false, urls ); types.add( typeGrp ); } } } } } this.requests = types; } private void loadExample() { if ( selectedRequest != null ) { LOG.debug( "load request " + selectedRequest ); String realPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath( selectedRequest ); try { BufferedReader reader = new BufferedReader( new FileReader( realPath ) ); String req = ""; String line = null; while ( ( line = reader.readLine() ) != null ) { req += line; } setRequest( req ); } catch ( FileNotFoundException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } // try { // String realPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath( selectedRequest ); // XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader( new FileReader( realPath ) // StAXOMBuilder builder = new StAXOMBuilder( reader ); // OMElement rootElement = builder.getDocumentElement(); // StringWriter writer = new StringWriter(); // XMLOutputFactory factory = XMLOutputFactory.newInstance(); // factory.setProperty( "javax.xml.stream.isRepairingNamespaces", Boolean.TRUE ); // XMLStreamWriter xmlWriter = new FormattingXMLStreamWriter( factory.createXMLStreamWriter( writer ) ); // rootElement.serialize( xmlWriter ); // request = writer.toString(); // } catch ( FileNotFoundException e ) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch ( XMLStreamException e ) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch ( FactoryConfigurationError e ) { // // TODO Auto-generated catch block // e.printStackTrace(); } } public void sendKVPRequest() { LOG.debug( "Try to send the following request to " + targetUrl + " : \n" + kvpRequestSel ); if ( targetUrl != null && targetUrl.length() > 0 && kvpRequestSel != null && kvpRequestSel.length() > 0 ) { Map<String, String> header = new HashMap<String, String>(); try { if ( !kvpRequestIsImage ) { this.response = HttpUtils.get( HttpUtils.UTF8STRING, targetUrl + "?" + kvpRequestSel, header ); } else { this.response = ""; } } catch ( HttpException e ) { // TODO Auto-generated catch block e.printStackTrace(); } catch ( IOException e ) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * @param kvpRequestSel */ public void setKvpRequestSel( String kvpRequestSel ) { this.kvpRequestSel = kvpRequestSel; this.kvpRequestIsImage = kvpRequestSel.toLowerCase().indexOf( "request=getmap" ) != -1; } /** * @param evt * */ public void applyRequestFilter( AjaxBehaviorEvent evt ) { if ( requestFilter != null && !requestFilter.isEmpty() ) { kvpRequests.clear(); for ( String req : originalKvpRequests ) { if ( req.indexOf( requestFilter ) != -1 ) { kvpRequests.add( req ); } } } } @Override public String toString() { return generateToString( this ); } }
package com.gurkensalat.osm.repository; import com.gurkensalat.osm.entity.DitibPlace; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static org.apache.commons.collections4.CollectionUtils.isNotEmpty; import static org.apache.commons.collections4.ListUtils.emptyIfNull; import static org.apache.commons.io.IOUtils.closeQuietly; public class DitibRepositoryImpl implements DitibRepository { private static final Logger LOGGER = LoggerFactory.getLogger(DitibRepositoryImpl.class); private final String CSS_PATH = "td.body_text2"; public List<DitibPlace> parse(File resourceFile) { List<DitibPlace> result = new ArrayList<DitibPlace>(); try { Document document = Jsoup.parse(resourceFile, "UTF-8", "http: Elements selection = document.select(CSS_PATH); LOGGER.debug("Found {} matching elements", selection.size()); if (isNotEmpty(selection)) { int hitNumber = 0; for (Element element : selection) { LOGGER.debug(" LOGGER.debug("Found: {}, {}", hitNumber++, element); Elements rows = selection.select("tbody > tr"); if (isNotEmpty(rows)) { DitibPlace place = new DitibPlace(); int rowNumber = 0; for (Element row : rows) { LOGGER.debug(" qw qw qw String foo = element.toString(); LOGGER.debug(" qw qw qw {}", rowNumber, element); switch (rowNumber) { case 0: place = extractPlaceName(row, place); break; default: break; } rowNumber++; } result.add(place); } } } } catch (IOException ioe) { LOGGER.error("While parsing {}", resourceFile, ioe); } result = emptyIfNull(result); return result; } protected DitibPlace extractPlaceName(Element block, DitibPlace place) { LOGGER.debug("extractPlaceName()"); // fsck css, just run indexOf :-( String data = block.toString(); int from = data.lastIndexOf("<strong>"); int to = data.lastIndexOf("</strong>"); if (from != -1 && to != -1) { data = data.substring(from + 8, to); data = data.replaceAll("&nbsp;", ""); place.setDitibCode(data); } return place; } public void prettify(File target, File resourceFile) { try { Document document = Jsoup.parse(resourceFile, "UTF-8", "http: String pretty = document.toString(); File output = new File(target, "parsed-" + resourceFile.getName()); FileOutputStream fos = new FileOutputStream(output); try { fos.write(pretty.getBytes()); } finally { closeQuietly(fos); } Elements selection = document.select(CSS_PATH); LOGGER.debug("Found {} matching elements", selection.size()); int hitNumber = 0; for (Element element : selection) { File output2 = new File(target, "parsed-" + hitNumber + "-" + resourceFile.getName()); FileOutputStream fos2 = new FileOutputStream(output2); try { pretty = element.toString(); fos2.write(pretty.getBytes()); } finally { closeQuietly(fos2); } hitNumber++; } } catch (IOException ioe) { LOGGER.error("While parsing {}", resourceFile, ioe); } } private List<DitibPlace> extractData(Element data) { List<DitibPlace> result = new ArrayList<DitibPlace>(); LOGGER.debug("About to extract data from {}", data.toString()); result = emptyIfNull(result); return result; } }
package org.opencds.cqf.cql.engine.elm.execution; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.cqframework.cql.elm.execution.Expression; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @Type(value = AbsEvaluator.class, name = "Abs"), @Type(value = AddEvaluator.class, name = "Add"), @Type(value = AfterEvaluator.class, name = "After"), @Type(value = AliasRefEvaluator.class, name = "AliasRef"), @Type(value = AllTrueEvaluator.class, name = "AllTrue"), @Type(value = AndEvaluator.class, name = "And"), @Type(value = AnyInValueSetEvaluator.class, name = "AnyInValueSet"), @Type(value = AnyTrueEvaluator.class, name = "AnyTrue"), @Type(value = AsEvaluator.class, name = "As"), @Type(value = AvgEvaluator.class, name = "Avg"), @Type(value = BeforeEvaluator.class, name = "Before"), @Type(value = CalculateAgeEvaluator.class, name = "CalculateAge"), @Type(value = CalculateAgeAtEvaluator.class, name = "CalculateAgeAt"), @Type(value = CaseEvaluator.class, name = "Case"), @Type(value = CeilingEvaluator.class, name = "Ceiling"), @Type(value = ChildrenEvaluator.class, name = "Children"), @Type(value = CoalesceEvaluator.class, name = "Coalesce"), @Type(value = CodeEvaluator.class, name = "Code"), @Type(value = CodeDefEvaluator.class, name = "CodeDef"), @Type(value = CodeRefEvaluator.class, name = "CodeRef"), @Type(value = CodeSystemDefEvaluator.class, name = "CodeSystemDef"), @Type(value = CodeSystemRefEvaluator.class, name = "CodeSystemRef"), @Type(value = CollapseEvaluator.class, name = "Collapse"), @Type(value = CombineEvaluator.class, name = "Combine"), @Type(value = ConcatenateEvaluator.class, name = "Concatenate"), @Type(value = ConceptEvaluator.class, name = "Concept"), @Type(value = ConceptDefEvaluator.class, name = "ConceptDef"), @Type(value = ConceptRefEvaluator.class, name = "ConceptRef"), @Type(value = ContainsEvaluator.class, name = "Contains"), @Type(value = ConvertEvaluator.class, name = "Convert"), @Type(value = ConvertQuantityEvaluator.class, name = "ConvertQuantity"), @Type(value = ConvertsToBooleanEvaluator.class, name = "ConvertsToBoolean"), @Type(value = ConvertsToDateEvaluator.class, name = "ConvertsToDate"), @Type(value = ConvertsToDateTimeEvaluator.class, name = "ConvertsToDateTime"), @Type(value = ConvertsToDecimalEvaluator.class, name = "ConvertsToDecimal"), @Type(value = ConvertsToIntegerEvaluator.class, name = "ConvertsToInteger"), @Type(value = ConvertsToLongEvaluator.class, name = "ConvertsToLong"), @Type(value = ConvertsToQuantityEvaluator.class, name = "ConvertsToQuantity"), @Type(value = ConvertsToStringEvaluator.class, name = "ConvertsToString"), @Type(value = ConvertsToTimeEvaluator.class, name = "ConvertsToTime"), @Type(value = CountEvaluator.class, name = "Count"), @Type(value = DateEvaluator.class, name = "Date"), @Type(value = DateFromEvaluator.class, name = "DateFrom"), @Type(value = DateTimeEvaluator.class, name = "DateTime"), @Type(value = DateTimeComponentFromEvaluator.class, name = "DateTimeComponentFrom"), @Type(value = DescendentsEvaluator.class, name = "Descendents"), @Type(value = DifferenceBetweenEvaluator.class, name = "DifferenceBetween"), @Type(value = DistinctEvaluator.class, name = "Distinct"), @Type(value = DivideEvaluator.class, name = "Divide"), @Type(value = DurationBetweenEvaluator.class, name = "DurationBetween"), @Type(value = EndEvaluator.class, name = "End"), @Type(value = EndsEvaluator.class, name = "Ends"), @Type(value = EndsWithEvaluator.class, name = "EndsWith"), @Type(value = EqualEvaluator.class, name = "Equal"), @Type(value = EquivalentEvaluator.class, name = "Equivalent"), @Type(value = ExceptEvaluator.class, name = "Except"), @Type(value = ExistsEvaluator.class, name = "Exists"), @Type(value = ExpEvaluator.class, name = "Exp"), @Type(value = ExpandEvaluator.class, name = "Expand"), @Type(value = ExpressionRefEvaluator.class, name = "ExpressionRef"), @Type(value = FilterEvaluator.class, name = "Filter"), @Type(value = FirstEvaluator.class, name = "First"), @Type(value = FlattenEvaluator.class, name = "Flatten"), @Type(value = FloorEvaluator.class, name = "Floor"), @Type(value = ForEachEvaluator.class, name = "ForEach"), @Type(value = FunctionRefEvaluator.class, name = "FunctionRef"), @Type(value = GeometricMeanEvaluator.class, name = "GeometricMean"), @Type(value = GreaterEvaluator.class, name = "Greater"), @Type(value = GreaterOrEqualEvaluator.class, name = "GreaterOrEqual"), @Type(value = HighBoundaryEvaluator.class, name = "HighBoundary"), @Type(value = IdentifierRefEvaluator.class, name = "IdentifierRef"), @Type(value = IfEvaluator.class, name = "If"), @Type(value = ImpliesEvaluator.class, name = "Implies"), @Type(value = InEvaluator.class, name = "In"), @Type(value = IncludedInEvaluator.class, name = "IncludedIn"), @Type(value = IncludesEvaluator.class, name = "Includes"), @Type(value = InCodeSystemEvaluator.class, name = "InCodeSystem"), @Type(value = IndexerEvaluator.class, name = "Indexer"), @Type(value = IndexOfEvaluator.class, name = "IndexOf"), @Type(value = InstanceEvaluator.class, name = "Instance"), @Type(value = IntersectEvaluator.class, name = "Intersect"), @Type(value = IntervalEvaluator.class, name = "Interval"), @Type(value = InValueSetEvaluator.class, name = "InValueSet"), @Type(value = IsEvaluator.class, name = "Is"), @Type(value = IsFalseEvaluator.class, name = "IsFalse"), @Type(value = IsNullEvaluator.class, name = "IsNull"), @Type(value = IsTrueEvaluator.class, name = "IsTrue"), @Type(value = LastEvaluator.class, name = "Last"), @Type(value = LastPositionOfEvaluator.class, name = "LastPositionOf"), @Type(value = LengthEvaluator.class, name = "Length"), @Type(value = LessEvaluator.class, name = "Less"), @Type(value = LessOrEqualEvaluator.class, name = "LessOrEqual"), @Type(value = ListEvaluator.class, name = "List"), @Type(value = LiteralEvaluator.class, name = "Literal"), @Type(value = LnEvaluator.class, name = "Ln"), @Type(value = LogEvaluator.class, name = "Log"), @Type(value = LowBoundaryEvaluator.class, name = "LowBoundary"), @Type(value = LowerEvaluator.class, name = "Lower"), @Type(value = MatchesEvaluator.class, name = "Matches"), @Type(value = MaxEvaluator.class, name = "Max"), @Type(value = MaxValueEvaluator.class, name = "MaxValue"), @Type(value = MedianEvaluator.class, name = "Median"), @Type(value = MeetsEvaluator.class, name = "Meets"), @Type(value = MeetsAfterEvaluator.class, name = "MeetsAfter"), @Type(value = MeetsBeforeEvaluator.class, name = "MeetsBefore"), @Type(value = MessageEvaluator.class, name = "Message"), @Type(value = MinEvaluator.class, name = "Min"), @Type(value = MinValueEvaluator.class, name = "MinValue"), @Type(value = ModeEvaluator.class, name = "Mode"), @Type(value = ModuloEvaluator.class, name = "Modulo"), @Type(value = MultiplyEvaluator.class, name = "Multiply"), @Type(value = NegateEvaluator.class, name = "Negate"), @Type(value = NotEvaluator.class, name = "Not"), @Type(value = NotEqualEvaluator.class, name = "NotEqual"), @Type(value = NowEvaluator.class, name = "Now"), @Type(value = NullEvaluator.class, name = "Null"), @Type(value = OperandRefEvaluator.class, name = "OperandRef"), @Type(value = OrEvaluator.class, name = "Or"), @Type(value = OverlapsEvaluator.class, name = "Overlaps"), @Type(value = OverlapsAfterEvaluator.class, name = "OverlapsAfter"), @Type(value = OverlapsBeforeEvaluator.class, name = "OverlapsBefore"), @Type(value = ParameterRefEvaluator.class, name = "ParameterRef"), @Type(value = PointFromEvaluator.class, name = "PointFrom"), @Type(value = PopulationStdDevEvaluator.class, name = "PopulationStdDev"), @Type(value = PopulationVarianceEvaluator.class, name = "PopulationVariance"), @Type(value = PositionOfEvaluator.class, name = "PositionOf"), @Type(value = PowerEvaluator.class, name = "Power"), @Type(value = PrecisionEvaluator.class, name = "Precision"), @Type(value = PredecessorEvaluator.class, name = "Predecessor"), @Type(value = ProductEvaluator.class, name = "Product"), @Type(value = ProperContainsEvaluator.class, name = "ProperContains"), @Type(value = ProperInEvaluator.class, name = "ProperIn"), @Type(value = ProperIncludedInEvaluator.class, name = "ProperIncludedIn"), @Type(value = ProperIncludesEvaluator.class, name = "ProperIncludes"), @Type(value = PropertyEvaluator.class, name = "Property"), @Type(value = QuantityEvaluator.class, name = "Quantity"), @Type(value = QueryEvaluator.class, name = "Query"), @Type(value = QueryLetRefEvaluator.class, name = "QueryLetRef"), @Type(value = RatioEvaluator.class, name = "Ratio"), @Type(value = RepeatEvaluator.class, name = "Repeat"), @Type(value = ReplaceMatchesEvaluator.class, name = "ReplaceMatches"), @Type(value = RetrieveEvaluator.class, name = "Retrieve"), @Type(value = RoundEvaluator.class, name = "Round"), @Type(value = SameAsEvaluator.class, name = "SameAs"), @Type(value = SameOrAfterEvaluator.class, name = "SameOrAfter"), @Type(value = SameOrBeforeEvaluator.class, name = "SameOrBefore"), @Type(value = SingletonFromEvaluator.class, name = "SingletonFrom"), @Type(value = SizeEvaluator.class, name = "Size"), @Type(value = SliceEvaluator.class, name = "Slice"), @Type(value = SplitEvaluator.class, name = "Split"), @Type(value = SplitOnMatchesEvaluator.class, name = "SplitOnMatches"), @Type(value = StartEvaluator.class, name = "Start"), @Type(value = StartsEvaluator.class, name = "Starts"), @Type(value = StartsWithEvaluator.class, name = "StartsWith"), @Type(value = StdDevEvaluator.class, name = "StdDev"), @Type(value = SubstringEvaluator.class, name = "Substring"), @Type(value = SubtractEvaluator.class, name = "Subtract"), @Type(value = SuccessorEvaluator.class, name = "Successor"), @Type(value = SumEvaluator.class, name = "Sum"), @Type(value = TimeEvaluator.class, name = "Time"), @Type(value = TimeFromEvaluator.class, name = "TimeFrom"), @Type(value = TimeOfDayEvaluator.class, name = "TimeOfDay"), @Type(value = TimezoneFromEvaluator.class, name = "TimezoneFrom"), @Type(value = TimezoneOffsetFromEvaluator.class, name = "TimezoneOffsetFrom"), @Type(value = ToBooleanEvaluator.class, name = "ToBoolean"), @Type(value = ToConceptEvaluator.class, name = "ToConcept"), @Type(value = ToDateEvaluator.class, name = "ToDate"), @Type(value = ToDateTimeEvaluator.class, name = "ToDateTime"), @Type(value = TodayEvaluator.class, name = "Today"), @Type(value = ToDecimalEvaluator.class, name = "ToDecimal"), @Type(value = ToIntegerEvaluator.class, name = "ToInteger"), @Type(value = ToListEvaluator.class, name = "ToList"), @Type(value = ToLongEvaluator.class, name = "ToLong"), @Type(value = ToQuantityEvaluator.class, name = "ToQuantity"), @Type(value = ToRatioEvaluator.class, name = "ToRatio"), @Type(value = ToStringEvaluator.class, name = "ToString"), @Type(value = ToTimeEvaluator.class, name = "ToTime"), @Type(value = TruncateEvaluator.class, name = "Truncate"), @Type(value = TruncatedDivideEvaluator.class, name = "TruncatedDivide"), @Type(value = TupleEvaluator.class, name = "Tuple"), @Type(value = UnionEvaluator.class, name = "Union"), @Type(value = UpperEvaluator.class, name = "Upper"), @Type(value = ValueSetRefEvaluator.class, name = "ValueSetRef"), @Type(value = VarianceEvaluator.class, name = "Variance"), @Type(value = WidthEvaluator.class, name = "Width"), @Type(value = XorEvaluator.class, name = "Xor"), }) public class ExpressionMixin extends Expression { }
package com.tvd12.ezyfox.bean.impl; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.List; import java.util.Map; import com.tvd12.ezyfox.bean.EzyBeanContext; import com.tvd12.ezyfox.bean.EzyPropertyFetcher; import com.tvd12.ezyfox.bean.EzySingletonFactory; import com.tvd12.ezyfox.bean.exception.EzyNewSingletonException; import com.tvd12.ezyfox.reflect.EzyClass; import com.tvd12.ezyfox.reflect.EzyField; import com.tvd12.ezyfox.reflect.EzyMethod; import com.tvd12.ezyfox.reflect.EzySetterMethod; @SuppressWarnings("rawtypes") public abstract class EzySimpleSingletonLoader extends EzySimpleObjectBuilder implements EzySingletonLoader { protected final Object configurator; protected final Map<Class<?>, EzyMethod> methodsByType; protected EzySimpleSingletonLoader(EzyClass clazz) { this(clazz, null, new HashMap<>()); } protected EzySimpleSingletonLoader( EzyClass clazz, Object configurator, Map<Class<?>, EzyMethod> methodsByType) { super(clazz); this.configurator = configurator; this.methodsByType = methodsByType; } @Override public final Object load(EzyBeanContext context) { try { return process(context); } catch(EzyNewSingletonException e) { throw e; } catch(Exception e) { throw new IllegalStateException("can not create singleton of class " + clazz, e); } } protected Class<?> getSingletonClass() { return clazz.getClazz(); } private Object process(EzyBeanContext context) throws Exception { EzySingletonFactory factory = context.getSingletonFactory(); Class[] parameterTypes = getConstructorParameterTypes(); StringBuilder log = new StringBuilder().append(getSingletonClass()); detectCircularDependency(parameterTypes, log); String name = getSingletonName(); Object singleton = getOrCreateSingleton(context, name, parameterTypes); Map properties = getAnnotationProperties(); Object answer = factory.addSingleton(name, singleton, properties); setPropertiesToFields(singleton, context); setPropertiesToMethods(singleton, context); setValueToBindingFields(answer, context); setValueToBindingMethods(answer, context); callPostInit(answer); return answer; } private Object getOrCreateSingleton( EzyBeanContext context, String name, Class[] parameterTypes) throws Exception { EzySingletonFactory factory = context.getSingletonFactory(); Object singleton = factory.getSingleton(name, getSingletonClass()); if(singleton == null) { singleton = newSingletonByConstructor(context, parameterTypes); getLogger().debug("add singleton with name {} of {}, object = {}", name, singleton.getClass(), singleton); } return singleton; } protected String getSingletonName() { return EzyBeanNameParser.getSingletonName(getSingletonClass()); } protected Map getAnnotationProperties() { return EzyKeyValueParser.getSingletonProperties(getSingletonClass()); } protected abstract Object newSingletonByConstructor( EzyBeanContext context, Class[] parameterTypes) throws Exception; private void setPropertiesToFields(Object singleton, EzyPropertyFetcher fetcher) { for(EzyField field : propertyFields) setValueToPropertyField(field, singleton, fetcher); } @SuppressWarnings("unchecked") private void setValueToPropertyField(EzyField field, Object singleton, EzyPropertyFetcher fetcher) { String propertyName = getPropertyName(field); if(fetcher.containsProperty(propertyName)) field.set(singleton, fetcher.getProperty(propertyName, field.getType())); } private void setPropertiesToMethods(Object singleton, EzyPropertyFetcher fetcher) { for(EzySetterMethod method : propertyMethods) setValueToPropertyMethod(method, singleton, fetcher); } @SuppressWarnings("unchecked") private void setValueToPropertyMethod(EzySetterMethod method, Object singleton, EzyPropertyFetcher fetcher) { String propertyName = getPropertyName(method); if(fetcher.containsProperty(propertyName)) method.invoke(singleton, fetcher.getProperty(propertyName, method.getType())); } private void setValueToBindingFields(Object singleton, EzyBeanContext context) { for(EzyField field : bindingFields) setValueToBindingField(field, singleton, context); } private void setValueToBindingField(EzyField field, Object singleton, EzyBeanContext context) { Object value = getOrCreateSingleton( field.getType(), getBeanName(field), context); field.set(singleton, value); getLogger().debug("{} set field: {} with value: {}", clazz, field.getName(), value); } private void setValueToBindingMethods(Object singleton, EzyBeanContext context) { for(EzySetterMethod method : bindingMethods) setValueToBindingMethod(method, singleton, context); } private void setValueToBindingMethod( EzySetterMethod method, Object singleton, EzyBeanContext context) { Object value = getOrCreateSingleton( method.getType(), getBeanName(method), context); method.invoke(singleton, value); getLogger().debug("{} invoke method: {} with value: {}", singleton, method.getName(), value); } private void callPostInit(Object singleton) { List<EzyMethod> methods = getPostInitMethods(); methods.forEach(m -> m.invoke(singleton)); } protected final Object[] getArguments(Class[] parameterTypes, EzyBeanContext context) { Object[] arguments = new Object[parameterTypes.length]; String[] argumentNames = getConstructorArgumentNames(); for(int i = 0 ; i < parameterTypes.length ; i++) { arguments[i] = getOrCreateSingleton(parameterTypes[i], argumentNames[i], context); } return arguments; } private Object getOrCreateSingleton( Class type, String beanName, EzyBeanContext context) { EzySingletonFactory factory = context.getSingletonFactory(); Object singleton = factory.getSingleton(beanName, type); if(singleton == null) singleton = createNewSingleton(type, beanName, context); return singleton; } private Object createNewSingleton( Class paramType, String beanName, EzyBeanContext context) { EzyMethod method = methodsByType.remove(paramType); if(method != null) { getLogger().debug("add singleton of {} with method {}", paramType, method); return new EzyByMethodSingletonLoader(method, configurator, methodsByType).load(context); } if(isAbstractClass(paramType)) { throw new EzyNewSingletonException(getSingletonClass(), paramType, beanName); } return new EzyByConstructorSingletonLoader(new EzyClass(paramType)).load(context); } protected void detectCircularDependency(Class[] parameterTypes, StringBuilder log) { for(Class paramType : parameterTypes) { log.append(" => ").append(paramType); if(paramType.equals(clazz.getClazz())) { throw new IllegalStateException("circular dependency detected, " + log); } else { detectCircularDependency(getConstructorParameterTypes(paramType), log); } } } protected Class[] getConstructorParameterTypes(Class clazz) { try { Constructor constructor = getConstructor(new EzyClass(clazz)); return constructor.getParameterTypes(); } catch(Exception e) { return new Class[0]; } } }
package org.fcrepo.integration.api; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.codehaus.jackson.map.ObjectMapper; import org.fcrepo.Transaction; import org.fcrepo.Transaction.State; import org.junit.Test; public class FedoraTransactionsIT extends AbstractResourceIT { @Test public void testCreateAndGetTransaction() throws Exception { /* create a tx */ HttpPost createTx = new HttpPost(serverAddress + "fcr:tx"); HttpResponse resp = execute(createTx); assertTrue(resp.getStatusLine().getStatusCode() == 200); ObjectMapper mapper = new ObjectMapper(); Transaction tx = mapper.readValue(resp.getEntity().getContent(), Transaction.class); assertNotNull(tx); assertNotNull(tx.getId()); assertNotNull(tx.getState()); assertNotNull(tx.getCreated()); assertTrue(tx.getState() == State.NEW); /* fetch the create dtx from the endpoint */ HttpGet getTx = new HttpGet(serverAddress + "fcr:tx/" + tx.getId()); resp = execute(getTx); Transaction fetched = mapper.readValue(resp.getEntity().getContent(), Transaction.class); assertEquals(tx.getId(), fetched.getId()); assertEquals(tx.getState(), fetched.getState()); assertEquals(tx.getCreated(), fetched.getCreated()); } @Test public void testCreateAndCommitTransaction() throws Exception { /* create a tx */ HttpPost createTx = new HttpPost(serverAddress + "fcr:tx"); HttpResponse resp = execute(createTx); assertTrue(resp.getStatusLine().getStatusCode() == 200); ObjectMapper mapper = new ObjectMapper(); Transaction tx = mapper.readValue(resp.getEntity().getContent(), Transaction.class); assertNotNull(tx); assertNotNull(tx.getId()); assertNotNull(tx.getState()); assertNotNull(tx.getCreated()); assertTrue(tx.getState() == State.NEW); /* commit the tx */ HttpPost commitTx = new HttpPost(serverAddress + "fcr:tx/" + tx.getId() + "/fcr:commit"); resp = execute(commitTx); Transaction committed = mapper.readValue(resp.getEntity().getContent(), Transaction.class); assertEquals(committed.getState(), State.COMMITED); } @Test public void testCreateAndRollbackTransaction() throws Exception { /* create a tx */ HttpPost createTx = new HttpPost(serverAddress + "fcr:tx"); HttpResponse resp = execute(createTx); assertTrue(resp.getStatusLine().getStatusCode() == 200); ObjectMapper mapper = new ObjectMapper(); Transaction tx = mapper.readValue(resp.getEntity().getContent(), Transaction.class); assertNotNull(tx); assertNotNull(tx.getId()); assertNotNull(tx.getState()); assertNotNull(tx.getCreated()); assertTrue(tx.getState() == State.NEW); /* and rollback */ HttpPost rollbackTx = new HttpPost(serverAddress + "fcr:tx/" + tx.getId() + "/fcr:rollback"); resp = execute(rollbackTx); Transaction rolledBack = mapper.readValue(resp.getEntity().getContent(), Transaction.class); assertEquals(rolledBack.getId(),tx.getId()); assertTrue(rolledBack.getState() == State.ROLLED_BACK); } }
package edu.umd.cs.findbugs.detect; import java.util.HashSet; import java.util.Set; import org.apache.bcel.classfile.Attribute; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.ClassAnnotation; import edu.umd.cs.findbugs.MethodAnnotation; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.XClass; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.internalAnnotations.DottedClassName; import edu.umd.cs.findbugs.util.ClassName; import edu.umd.cs.findbugs.util.EditDistance; public class UncallableMethodOfAnonymousClass extends BytecodeScanningDetector { BugReporter bugReporter; public UncallableMethodOfAnonymousClass(BugReporter bugReporter) { this.bugReporter = bugReporter; } XMethod potentialSuperCall; @Override public void visitJavaClass(JavaClass obj) { try { obj.getSuperClass(); } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); return; } String superclassName2 = getSuperclassName(); boolean weird = superclassName2.equals("java.lang.Object") && obj.getInterfaceIndices().length == 0; boolean hasAnonymousName = ClassName.isAnonymous(obj.getClassName()); boolean isAnonymousInnerClass = hasAnonymousName && !weird; if (isAnonymousInnerClass) super.visitJavaClass(obj); } boolean definedInThisClassOrSuper(JavaClass clazz, String method) throws ClassNotFoundException { if (clazz == null) return false; // System.out.println("Checking to see if " + method + " is defined in " // + clazz.getClassName()); for (Method m : clazz.getMethods()) { String key = m.getName() + ":" + m.getSignature(); if (!m.isStatic() && method.equals(key)) return true; } return definedInSuperClassOrInterface(clazz, method); } @Override public void sawOpcode(int seen) { if (seen == INVOKESPECIAL) { XMethod m = getXMethodOperand(); if (m == null) return; XClass c = getXClass(); int nameDistance = EditDistance.editDistance(m.getName(), getMethodName()); if (nameDistance < 4 && c.findMatchingMethod(m.getMethodDescriptor()) == null && !m.isFinal()) potentialSuperCall = m; } } boolean definedInSuperClassOrInterface(JavaClass clazz, String method) throws ClassNotFoundException { if (clazz == null) return false; JavaClass superClass = clazz.getSuperClass(); if (definedInThisClassOrSuper(superClass, method)) return true; for (JavaClass i : clazz.getInterfaces()) if (definedInThisClassOrSuper(i, method)) return true; return false; } Set<String> definedInClass(JavaClass clazz) { HashSet<String> result = new HashSet<String>(); for (Method m : clazz.getMethods()) { if (!skip(m)) result.add(m.getName() + m.getSignature()); } return result; } private boolean skip(Method obj) { if (obj.isSynthetic()) return true; if (obj.isPrivate()) return true; if (obj.isAbstract()) return true; String methodName = obj.getName(); String sig = obj.getSignature(); if (methodName.equals("<init>")) return true; if (methodName.equals("<clinit>")) return true; if (sig.equals("()Ljava/lang/Object;") && (methodName.equals("readResolve") || methodName.equals("writeReplace"))) return true; if (methodName.startsWith("access$")) return true; if (methodName.length() < 2 || methodName.indexOf('$') >= 0) return true; XMethod m = getXMethod(); for (ClassDescriptor c : m.getAnnotationDescriptors()) if (c.getClassName().indexOf("inject") >= 0) return true; return false; } BugInstance pendingBug; @Override public void doVisitMethod(Method obj) { super.doVisitMethod(obj); if (pendingBug != null) { if (potentialSuperCall == null) { String role = ClassAnnotation.SUPERCLASS_ROLE; @DottedClassName String superclassName = ClassName.toDottedClassName(getSuperclassName()); if (superclassName.equals("java.lang.Object")) { try { JavaClass interfaces[] = getThisClass().getInterfaces(); if (interfaces.length == 1) { superclassName = interfaces[0].getClassName(); role = ClassAnnotation.IMPLEMENTED_INTERFACE_ROLE; } } catch (ClassNotFoundException e) { AnalysisContext.reportMissingClass(e); } } pendingBug.addClass(superclassName).describe(role); try { XClass from = Global.getAnalysisCache().getClassAnalysis(XClass.class, DescriptorFactory.createClassDescriptorFromDottedClassName(superclassName)); XMethod potentialMatch = null; for(XMethod m : from.getXMethods()) if (!m.isStatic() && !m.isPrivate() && m.getName().toLowerCase().equals(obj.getName().toLowerCase())) { if (potentialMatch == null) potentialMatch = m; else { // multiple matches; ignore all potentialMatch = null; break; } } if (potentialMatch != null) pendingBug.addMethod(potentialMatch) .describe(MethodAnnotation.METHOD_DID_YOU_MEAN_TO_OVERRIDE); } catch (CheckedAnalysisException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { pendingBug.setPriority(pendingBug.getPriority() - 1); pendingBug.addMethod(potentialSuperCall).describe(MethodAnnotation.METHOD_DID_YOU_MEAN_TO_OVERRIDE); } bugReporter.reportBug(pendingBug); pendingBug = null; potentialSuperCall = null; } } @Override public void visit(Code obj) { if (pendingBug != null) super.visit(obj); } @Override public void visit(Method obj) { try { if (skip(obj)) return; JavaClass clazz = getThisClass(); XMethod xmethod = XFactory.createXMethod(clazz, obj); XFactory factory = AnalysisContext.currentXFactory(); String key = obj.getName() + ":" + obj.getSignature(); if (!factory.isCalled(xmethod) && (obj.isStatic() || !definedInSuperClassOrInterface(clazz, key))) { int priority = NORMAL_PRIORITY; JavaClass superClass = clazz.getSuperClass(); String superClassName = superClass.getClassName(); if (superClassName.equals("java.lang.Object")) { priority = NORMAL_PRIORITY; } else if (definedInClass(superClass).containsAll(definedInClass(clazz))) priority = NORMAL_PRIORITY; else priority = HIGH_PRIORITY; Code code = null; for (Attribute a : obj.getAttributes()) if (a instanceof Code) { code = (Code) a; break; } if (code != null && code.getLength() == 1) priority++; pendingBug = new BugInstance(this, "UMAC_UNCALLABLE_METHOD_OF_ANONYMOUS_CLASS", priority).addClassAndMethod(this); potentialSuperCall = null; } } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } } }
package org.fedorahosted.flies.rest.service; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.fedorahosted.flies.core.dao.ResourceDAO; import org.fedorahosted.flies.core.dao.TextFlowTargetDAO; import org.fedorahosted.flies.repository.model.HContainer; import org.fedorahosted.flies.repository.model.HDataHook; import org.fedorahosted.flies.repository.model.HDocument; import org.fedorahosted.flies.repository.model.HParentResource; import org.fedorahosted.flies.repository.model.HProjectContainer; import org.fedorahosted.flies.repository.model.HReference; import org.fedorahosted.flies.repository.model.HDocumentResource; import org.fedorahosted.flies.repository.model.HSimpleComment; import org.fedorahosted.flies.repository.model.HTextFlow; import org.fedorahosted.flies.repository.model.HTextFlowHistory; import org.fedorahosted.flies.repository.model.HTextFlowTarget; import org.fedorahosted.flies.rest.MediaTypes; import org.fedorahosted.flies.rest.dto.Container; import org.fedorahosted.flies.rest.dto.DataHook; import org.fedorahosted.flies.rest.dto.Document; import org.fedorahosted.flies.rest.dto.Link; import org.fedorahosted.flies.rest.dto.Reference; import org.fedorahosted.flies.rest.dto.Relationships; import org.fedorahosted.flies.rest.dto.DocumentResource; import org.fedorahosted.flies.rest.dto.SimpleComment; import org.fedorahosted.flies.rest.dto.TextFlow; import org.fedorahosted.flies.rest.dto.TextFlowTarget; import org.fedorahosted.flies.rest.dto.TextFlowTargets; import org.fedorahosted.flies.rest.dto.TextFlowTarget.ContentState; import org.hibernate.Session; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; @AutoCreate @Scope(ScopeType.STATELESS) @Name("documentConverter") public class DocumentConverter { @In private ResourceDAO resourceDAO; @In private TextFlowTargetDAO textFlowTargetDAO; @In private Session session; /** * Recursively copies from the source Document to the destination HDocument * @param fromDoc source Document * @param toHDoc destination HDocument * @param replaceResourceTree should probably always be true */ public void copy(Document fromDoc, HDocument toHDoc, boolean replaceResourceTree) { toHDoc.setDocId(fromDoc.getId()); toHDoc.setName(fromDoc.getName()); toHDoc.setPath(fromDoc.getPath()); toHDoc.setContentType(fromDoc.getContentType()); toHDoc.setLocale(fromDoc.getLang()); // toHDoc.setRevision(fromDoc.getRevision()); // TODO increment revision on modify only // TODO handle doc extensions, especially containers if (fromDoc.hasResources()) { List<DocumentResource> docResources = fromDoc.getResources(); List<HDocumentResource> hResources; if (replaceResourceTree) { hResources = new ArrayList<HDocumentResource>(docResources.size()); // this should cause any obsolete HResources (and their // children) to be deleted when we save // TODO mark them obsolete instead toHDoc.setResources(hResources); } else { hResources = toHDoc.getResources(); } for (DocumentResource res : docResources) { HDocumentResource hRes = null; if (session.contains(toHDoc)) // FIXME make sure getById can find pre-existing docs (we broke the link from HDoc to its HResources above) hRes = resourceDAO.getById(toHDoc, res.getId()); if (hRes == null) { hRes = HDocument.create(res); } else { // resurrect the resource hRes.setObsolete(false); } hResources.add(hRes); hRes.setDocument(toHDoc); hRes.setResId(res.getId()); copy(res, hRes, toHDoc); } } } /** * Creates an HDocument from the Document, with the field 'project' * pointing to container * @param document * @param container * @return */ public HDocument create(Document document, HProjectContainer container){ HDocument hDocument = new HDocument(); hDocument.setDocId(document.getId()); hDocument.setDocId(document.getId()); hDocument.setName(document.getName()); hDocument.setPath(document.getPath()); hDocument.setContentType(document.getContentType()); hDocument.setLocale(document.getLang()); hDocument.setRevision(1); hDocument.setProject(container); if(document.hasResources()) { createChildren(document, hDocument, 1); } return hDocument; } /** * Creates the children of the Document in the HDocument * @param document * @param hDocument * @param newRevision */ public void createChildren(Document document, HDocument hDocument, int newRevision) { for(DocumentResource resource : document.getResources()) { HDocumentResource hResource = create(resource, hDocument, null); hDocument.getResources().add(hResource); } } public void merge(Document document, HDocument hDocument){ int newRevision = hDocument.getRevision() +1; hDocument.setRevision(newRevision); hDocument.setDocId(document.getId()); hDocument.setName(document.getName()); hDocument.setPath(document.getPath()); hDocument.setContentType(document.getContentType()); hDocument.setLocale(document.getLang()); if(document.hasResources() ) { mergeChildren(document, hDocument); } } public void mergeChildren(Document document, HDocument hDocument){ Map<String, HDocumentResource> existingResources = toMap(hDocument.getResources()); List<HDocumentResource> finalHResources = hDocument.getResources(); finalHResources.clear(); for(DocumentResource resource: document.getResources()){ // check existing resources first HDocumentResource hResource = existingResources.remove(resource.getId()); if(hResource == null) { hResource = resourceDAO.getObsoleteById(hDocument, resource.getId()); } if(hResource != null) { // need to delete and recreate if same ids but conflicting types if(!areOfSameType(resource, hResource)){ if(hResource instanceof HTextFlow){ session.delete(hResource); } else{ deleteOrObsolete(hResource); } hResource = create(resource, hResource.getDocument(), null); } hResource.setObsolete(false); merge(resource, hResource, hDocument.getRevision()); finalHResources.add(hResource); continue; } hResource = create(resource, hDocument, null); // finally insert finalHResources.add(hResource); } // clean up resources we didn't process in this for(HDocumentResource hResource : existingResources.values()) { deleteOrObsolete(hResource); } } public void mergeChildren(Container container, HParentResource hParentResource, int newRevision){ Map<String, HDocumentResource> existingResources = toMap(hParentResource.getResources()); List<HDocumentResource> finalHResources = hParentResource.getResources(); finalHResources.clear(); for(DocumentResource resource: container.getResources()){ // check existing resources first HDocumentResource hResource = existingResources.remove(resource.getId()); if(hResource == null) { hResource = resourceDAO.getObsoleteById(hParentResource.getDocument(), resource.getId()); } if(hResource != null) { // need to delete and recreate if same ids but conflicting types if(!areOfSameType(resource, hResource)){ if(hResource instanceof HTextFlow){ session.delete(hResource); } else{ deleteOrObsolete(hResource); } hResource = create(resource, hResource.getDocument(), hParentResource); } hResource.setObsolete(false); merge(resource, hResource, newRevision); finalHResources.add(hResource); continue; } // finally insert finalHResources.add( create(resource, hResource.getDocument(), hParentResource)); } // clean up resources we didn't process in this for(HDocumentResource hResource : existingResources.values()) { deleteOrObsolete(hResource); } } private boolean areOfSameType(DocumentResource resource, HDocumentResource hResource){ return (resource instanceof TextFlow && hResource instanceof HTextFlow) || (resource instanceof Container && hResource instanceof HContainer) || (resource instanceof DataHook && hResource instanceof HDataHook) || (resource instanceof Reference && hResource instanceof HReference); } public void merge(DocumentResource resource, HDocumentResource hResource, int newRevision){ if(!areOfSameType(resource, hResource)) throw new IllegalArgumentException("Resource and HResource must be of same type"); if(resource instanceof TextFlow) merge( (TextFlow) resource, (HTextFlow) hResource, newRevision); else if(resource instanceof Container) merge( (Container) resource, (HContainer) hResource, newRevision); else if(resource instanceof DataHook) merge( (DataHook) resource, (HDataHook) hResource, newRevision); else if(resource instanceof Reference) merge( (Reference) resource, (HReference) hResource, newRevision); else throw new RuntimeException("missing type - programming error"); } public void merge(TextFlow textFlow, HTextFlow hTextFlow, int newRevision){ if(!hTextFlow.getContent().equals(textFlow.getContent())){ // save old version to history HTextFlowHistory history = new HTextFlowHistory(hTextFlow); hTextFlow.getHistory().put(hTextFlow.getRevision(), history); // make sure to set the status of any targets to NeedReview for(HTextFlowTarget target :hTextFlow.getTargets().values()){ // TODO not sure if this is the correct state target.setState(ContentState.ForReview); } hTextFlow.setRevision(newRevision); hTextFlow.setContent(textFlow.getContent()); } TextFlowTargets targets = textFlow.getTargets(); if(targets != null) { for(TextFlowTarget textFlowTarget : targets.getTargets()) { if(hTextFlow.getTargets().containsKey(textFlowTarget.getLang())){ merge(textFlowTarget, hTextFlow.getTargets().get(textFlowTarget.getLang()), newRevision); } else{ HTextFlowTarget hTextFlowTarget = create(textFlowTarget, newRevision); hTextFlow.getTargets().put(textFlowTarget.getLang(), hTextFlowTarget); } } } } public void merge(TextFlowTarget textFlowTarget, HTextFlowTarget hTextFlowTarget, int newRevision) { if( !hTextFlowTarget.getContent().equals(textFlowTarget.getContent())){ } } public HTextFlowTarget create(TextFlowTarget textFlowTarget, int newRevision){ return null; } public void merge(Container container, HContainer hContainer, int newRevision){ mergeChildren(container, hContainer, newRevision); // if a child is updated, we update the container version as well for(HDocumentResource child: hContainer.getResources()) { if(newRevision == child.getRevision()){ hContainer.setRevision(newRevision); } } } public void merge(DataHook dataHook, HDataHook hDataHook, int newRevision){ } public void merge(Reference reference, HReference hReference, int newRevision){ if(!hReference.getRef().equals(reference.getRelationshipId())){ hReference.setRevision(newRevision); hReference.setRef(reference.getRelationshipId()); } } /** * Creates the Hibernate equivalent of the DocumentResource 'resource', * setting parent to 'parent', setting document to hDocument, * inheriting hDocument's revision. * @param resource * @param hDocument * @param parent * @return */ public HDocumentResource create(DocumentResource resource, HDocument hDocument, HParentResource parent){ if(resource instanceof TextFlow) return create( (TextFlow) resource, hDocument, parent); else if(resource instanceof Container) return create( (Container) resource, hDocument, parent); else if(resource instanceof DataHook) return create( (DataHook) resource, hDocument, parent); else if(resource instanceof Reference) return create( (Reference) resource, hDocument, parent); else throw new RuntimeException("missing type - programming error"); } /** * Creates the Hibernate equivalent of the TextFlow, * setting parent to 'parent', setting document to hDocument, * inheriting hDocument's revision. */ public HTextFlow create(TextFlow textFlow, HDocument hDocument, HParentResource parent){ HTextFlow hTextFlow = new HTextFlow(); hTextFlow.setDocument(hDocument); hTextFlow.setParent(parent); hTextFlow.setResId(textFlow.getId()); hTextFlow.setRevision(hDocument.getRevision()); hTextFlow.setContent(textFlow.getContent()); return hTextFlow; } /** * Creates an HContainer for the Container, creates child * HDocumentResources for the Container's DocumentResources, and * sets the HContainer's parent to 'parent', setting document to hDocument, * inheriting hDocument's revision. * @param container * @param hDocument * @param parent * @return */ public HContainer create(Container container, HDocument hDocument, HParentResource parent){ HContainer hContainer = new HContainer(); hContainer.setDocument(hDocument); hContainer.setParent(parent); hContainer.setResId(container.getId()); hContainer.setRevision(hDocument.getRevision()); createChildren(container, hDocument, hContainer); return hContainer; } /** * creates child HDocumentResources for the Container's DocumentResources, * and adds them to the parent (HContainer) * @param container * @param hDocument * @param parent */ public void createChildren(Container container, HDocument hDocument, HParentResource parent) { for(DocumentResource resource : container.getResources()) { HDocumentResource hResource = create(resource, hDocument, parent); parent.getResources().add(hResource); } } /** * Creates the Hibernate equivalent of the DataHook, * setting parent to 'parent', setting document to hDocument, * inheriting hDocument's revision. */ public HDataHook create(DataHook dataHook, HDocument hDocument, HParentResource parent){ HDataHook hDataHook = new HDataHook(); hDataHook.setDocument(hDocument); hDataHook.setParent(parent); hDataHook.setResId(dataHook.getId()); hDataHook.setRevision(hDocument.getRevision()); return hDataHook; } /** * Creates the Hibernate equivalent of the Reference, * setting parent to 'parent', setting document to hDocument, * inheriting hDocument's revision. */ public HReference create(Reference reference, HDocument hDocument, HParentResource parent){ HReference hReference = new HReference(); hReference.setDocument(hDocument); hReference.setParent(parent); hReference.setResId(reference.getId()); hReference.setRevision(hDocument.getRevision()); hReference.setRef(reference.getRelationshipId()); return hReference; } public void deleteOrObsolete(HDocumentResource hResource) { // process leafs first if(hResource instanceof HParentResource) { HParentResource hParentResource = (HParentResource) hResource; for(HDocumentResource hChildResource : hParentResource.getResources()) { deleteOrObsolete(hChildResource); } hParentResource.getResources().clear(); } if(hResource instanceof HTextFlow) { // we only keep TextFlow obsoletes hResource.setObsolete(true); hResource.setParent(null); } else{ session.delete(hResource); } } private static Map<String, HDocumentResource> toMap(List<HDocumentResource> resources) { Map<String, HDocumentResource> map = new HashMap<String, HDocumentResource>(resources.size()); for(HDocumentResource res : resources) { map.put(res.getResId(), res); } return map; } // copy res to hRes recursively, maintaining docTargets private void copy(DocumentResource res, HDocumentResource hRes, HDocument hDoc) { hRes.setDocument(hDoc); if (res instanceof TextFlow) { copy((TextFlow)res, (HTextFlow)hRes); } else { // FIXME handle other Resource types throw new RuntimeException("Unknown Resource type "+res.getClass()); } } private void copy(TextFlow tf, HTextFlow htf) { htf.setContent(tf.getContent()); List<Object> extensions = tf.getExtensions(); if (extensions != null) { for (Object ext : extensions) { if (ext instanceof TextFlowTargets) { TextFlowTargets targets = (TextFlowTargets) ext; for (TextFlowTarget target : targets.getTargets()) { HTextFlowTarget hTarget = null; if (session.contains(htf)) { hTarget = textFlowTargetDAO.getByNaturalId(htf, target.getLang()); } if (hTarget == null) { hTarget = new HTextFlowTarget(); hTarget.setLocale(target.getLang()); hTarget.setTextFlow(htf); hTarget.setResourceRevision(htf.getRevision()); hTarget.setState(target.getState()); // hTarget.setRevision(revision); // TODO hTarget.setContent(target.getContent()); } copy(target, hTarget, htf); htf.getTargets().put(target.getLang(), hTarget); } } else if (ext instanceof SimpleComment) { SimpleComment simpleComment = (SimpleComment) ext; HSimpleComment hComment = htf.getComment(); if (hComment == null) { hComment = new HSimpleComment(); htf.setComment(hComment); } hComment.setComment(simpleComment.getValue()); } else { throw new RuntimeException("Unknown TextFlow extension "+ext.getClass()); } } } } private void copy(TextFlowTarget target, HTextFlowTarget hTarget, HTextFlow htf) { hTarget.setContent(target.getContent()); hTarget.setLocale(target.getLang()); hTarget.setResourceRevision(htf.getRevision()); hTarget.setRevision(target.getRevision()); hTarget.setState(target.getState()); hTarget.setTextFlow(htf); if(target.hasComment()) { HSimpleComment hComment = hTarget.getComment(); if (hComment == null) { hComment = new HSimpleComment(); hTarget.setComment(hComment); } hComment.setComment(target.getComment().getValue()); } } public void addLinks(Document doc, URI docUri, URI iterationUri) { // add self relation Link link = new Link(docUri, Relationships.SELF); doc.getLinks().add(link); // add container relation link = new Link( iterationUri, Relationships.DOCUMENT_CONTAINER, MediaTypes.APPLICATION_FLIES_PROJECT_ITERATION_XML); doc.getLinks().add(link); } }
package ca.uhn.fhir.rest.param; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import java.util.Date; import java.util.TimeZone; import org.junit.Test; import ca.uhn.fhir.model.dstu.valueset.QuantityCompararatorEnum; import ca.uhn.fhir.model.primitive.DateTimeDt; import ca.uhn.fhir.model.primitive.InstantDt; public class DateParamTest { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(DateParamTest.class); @SuppressWarnings("deprecation") @Test public void testConstructors() { new DateParam(); new DateParam("2011-01-02"); new DateParam(ParamPrefixEnum.GREATERTHAN, new Date()); new DateParam(ParamPrefixEnum.GREATERTHAN, new DateTimeDt("2011-01-02")); new DateParam(ParamPrefixEnum.GREATERTHAN, InstantDt.withCurrentTime()); new DateParam(ParamPrefixEnum.GREATERTHAN, "2011-01-02"); new DateParam(QuantityCompararatorEnum.GREATERTHAN, new Date()); new DateParam(QuantityCompararatorEnum.GREATERTHAN, new DateTimeDt("2011-01-02")); new DateParam(QuantityCompararatorEnum.GREATERTHAN, InstantDt.withCurrentTime()); new DateParam(QuantityCompararatorEnum.GREATERTHAN, "2011-01-02"); } @Test public void testParse() { Date date = new Date(); DateParam param = new DateParam(); param.setValueAsString("gt2016-06-09T20:38:14.591-05:00"); assertEquals(ParamPrefixEnum.GREATERTHAN, param.getPrefix()); assertEquals("2016-06-09T20:38:14.591-05:00", param.getValueAsString()); ourLog.info("PRE: " + param.getValue()); ourLog.info("PRE: " + param.getValue().getTime()); InstantDt dt = new InstantDt(new Date(param.getValue().getTime())); dt.setTimeZone(TimeZone.getTimeZone("America/Toronto")); ourLog.info("POST: " + dt.getValue()); assertEquals("2016-06-09T21:38:14.591-04:00", dt.getValueAsString()); } @Test public void testParseMinutePrecision() { DateParam param = new DateParam(); param.setValueAsString("2016-06-09T20:38Z"); assertEquals(null, param.getPrefix()); assertEquals("2016-06-09T20:38Z", param.getValueAsString()); ourLog.info("PRE: " + param.getValue()); ourLog.info("PRE: " + param.getValue().getTime()); InstantDt dt = new InstantDt(new Date(param.getValue().getTime())); dt.setTimeZone(TimeZone.getTimeZone("America/Toronto")); ourLog.info("POST: " + dt.getValue()); assertEquals("2016-06-09T16:38:00.000-04:00", dt.getValueAsString()); } @Test public void testParseMinutePrecisionWithoutTimezone() { DateParam param = new DateParam(); param.setValueAsString("2016-06-09T20:38"); assertEquals(null, param.getPrefix()); assertEquals("2016-06-09T20:38", param.getValueAsString()); ourLog.info("PRE: " + param.getValue()); ourLog.info("PRE: " + param.getValue().getTime()); InstantDt dt = new InstantDt(new Date(param.getValue().getTime())); dt.setTimeZone(TimeZone.getTimeZone("America/Toronto")); ourLog.info("POST: " + dt.getValue()); assertThat(dt.getValueAsString(), startsWith("2016-06-09T")); assertThat(dt.getValueAsString(), endsWith("8:00.000-04:00")); } @Test public void testParseMinutePrecisionWithPrefix() { DateParam param = new DateParam(); param.setValueAsString("gt2016-06-09T20:38Z"); assertEquals(ParamPrefixEnum.GREATERTHAN, param.getPrefix()); assertEquals("2016-06-09T20:38Z", param.getValueAsString()); ourLog.info("PRE: " + param.getValue()); ourLog.info("PRE: " + param.getValue().getTime()); InstantDt dt = new InstantDt(new Date(param.getValue().getTime())); dt.setTimeZone(TimeZone.getTimeZone("America/Toronto")); ourLog.info("POST: " + dt.getValue()); assertEquals("2016-06-09T16:38:00.000-04:00", dt.getValueAsString()); } }
package com.facebook.cache.disk; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; import android.content.Context; import com.facebook.binaryresource.BinaryResource; import com.facebook.cache.common.CacheErrorLogger; import com.facebook.cache.common.CacheEvent; import com.facebook.cache.common.CacheEventAssert; import com.facebook.cache.common.CacheEventListener; import com.facebook.cache.common.CacheKey; import com.facebook.cache.common.MultiCacheKey; import com.facebook.cache.common.SimpleCacheKey; import com.facebook.cache.common.WriterCallback; import com.facebook.cache.common.WriterCallbacks; import com.facebook.common.disk.DiskTrimmableRegistry; import com.facebook.common.internal.ByteStreams; import com.facebook.common.internal.Supplier; import com.facebook.common.internal.Suppliers; import com.facebook.common.time.SystemClock; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareOnlyThisForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; /** * Test for {@link DiskStorageCache} */ @RunWith(RobolectricTestRunner.class) @PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" }) @PrepareOnlyThisForTest({SystemClock.class}) public class DiskStorageCacheTest { @Rule public PowerMockRule rule = new PowerMockRule(); private static final String CACHE_TYPE = "media_test"; private static final int TESTCACHE_VERSION_START_OF_VERSIONING = 1; private static final int TESTCACHE_CURRENT_VERSION = TESTCACHE_VERSION_START_OF_VERSIONING; private static final int TESTCACHE_NEXT_VERSION = TESTCACHE_CURRENT_VERSION + 1; private File mCacheDirectory; private DiskStorage mStorage; private DiskStorageCache mCache; private DiskTrimmableRegistry mDiskTrimmableRegistry; private CacheEventListener mCacheEventListener; private InOrder mCacheEventListenerInOrder; private SystemClock mClock; @Before public void setUp() { mClock = mock(SystemClock.class); PowerMockito.mockStatic(SystemClock.class); PowerMockito.when(SystemClock.get()).thenReturn(mClock); mDiskTrimmableRegistry = mock(DiskTrimmableRegistry.class); mCacheEventListener = mock(CacheEventListener.class); mCacheEventListenerInOrder = inOrder(mCacheEventListener); // we know the directory will be this mCacheDirectory = new File(RuntimeEnvironment.application.getCacheDir(), CACHE_TYPE); mCacheDirectory.mkdirs(); if (!mCacheDirectory.exists()) { throw new RuntimeException( String.format( (Locale) null, "Cannot create cache dir: %s: directory %s", mCacheDirectory.getAbsolutePath(), mCacheDirectory.exists() ? "already exists" : "does not exist")); } mStorage = createDiskStorage(TESTCACHE_VERSION_START_OF_VERSIONING); mCache = createDiskCache(mStorage); mCache.clearAll(); verify(mDiskTrimmableRegistry).registerDiskTrimmable(mCache); } // The threshold (in bytes) for the size of file cache private static final long FILE_CACHE_MAX_SIZE_HIGH_LIMIT = 200; private static final long FILE_CACHE_MAX_SIZE_LOW_LIMIT = 200; private static DiskStorage createDiskStorage(int version) { return new DiskStorageWithReadFailures( version, Suppliers.of(RuntimeEnvironment.application.getApplicationContext().getCacheDir()), CACHE_TYPE, mock(CacheErrorLogger.class)); } private DiskStorageCache createDiskCache(DiskStorage diskStorage) { DiskStorageCache.Params diskStorageCacheParams = new DiskStorageCache.Params( 0, FILE_CACHE_MAX_SIZE_LOW_LIMIT, FILE_CACHE_MAX_SIZE_HIGH_LIMIT); Context context = RuntimeEnvironment.application.getApplicationContext(); return new DiskStorageCache( diskStorage, new DefaultEntryEvictionComparatorSupplier(), diskStorageCacheParams, mCacheEventListener, mock(CacheErrorLogger.class), mDiskTrimmableRegistry, context); } @Test public void testCacheEventListener() throws Exception { // 1. Add first cache file CacheKey key1 = new SimpleCacheKey("foo"); int value1Size = 101; byte[] value1 = new byte[value1Size]; value1[80] = 'c'; // just so it's not all zeros for the equality test below. BinaryResource resource1 = mCache.insert(key1, WriterCallbacks.from(value1)); verifyListenerOnWriteAttempt(key1); String resourceId1 = verifyListenerOnWriteSuccessAndGetResourceId(key1, value1Size); BinaryResource resource1Again = mCache.getResource(key1); assertEquals(resource1, resource1Again); verifyListenerOnHit(key1, resourceId1); BinaryResource resource1Again2 = mCache.getResource(key1); assertEquals(resource1, resource1Again2); verifyListenerOnHit(key1, resourceId1); SimpleCacheKey missingKey = new SimpleCacheKey("nonexistent_key"); BinaryResource res2 = mCache.getResource(missingKey); assertNull(res2); verifyListenerOnMiss(missingKey); verifyNoMoreInteractions(mCacheEventListener); } private BinaryResource getResource( DiskStorage storage, final CacheKey key) throws IOException { return storage.getResource(mCache.getFirstResourceId(key), key); } private BinaryResource getResource(final CacheKey key) throws IOException { return mStorage.getResource(mCache.getFirstResourceId(key), key); } private byte[] getContents(BinaryResource resource) throws IOException { return ByteStreams.toByteArray(resource.openStream()); } /** * Tests size based file eviction of cache files. Also tests that unexpected * files (which are not in the format expected by the cache) do not count * towards the cache size, and are also evicted during both evictions (LRU and Old). * * @throws Exception */ @Test public void testCacheFile() throws Exception { if (!mCacheDirectory.exists() && !mCacheDirectory.mkdirs()) { throw new RuntimeException("Cannot create cache dir"); } // Write non-cache, non-lru file in the cache directory File unexpected1 = new File(mCacheDirectory, "unexpected1"); RandomAccessFile rf1 = new RandomAccessFile(unexpected1, "rw"); rf1.setLength(110); // Touch the non-cache, non-lru file, and assert that it succeeds. when(mClock.now()).thenReturn(TimeUnit.HOURS.toMillis(1)); assertTrue(unexpected1.setLastModified(mClock.now())); // 1. Add first cache file CacheKey key1 = new SimpleCacheKey("foo"); byte[] value1 = new byte[101]; value1[80] = 'c'; // just so it's not all zeros for the equality test below. mCache.insert(key1, WriterCallbacks.from(value1)); // verify resource assertArrayEquals(value1, getContents(getResource(key1))); // 1. Touch the LRU file, and assert that it succeeds. when(mClock.now()).thenReturn(TimeUnit.HOURS.toMillis(2)); assertTrue(mCache.probe(key1)); // The cache size should be the size of the first file only // The unexpected files should not count towards size assertTrue(mCache.getSize() == 101); // Write another non-cache, non-lru file in the cache directory File unexpected2 = new File(mCacheDirectory, "unexpected2"); RandomAccessFile rf2 = new RandomAccessFile(unexpected2, "rw"); rf2.setLength(120); // Touch the non-cache, non-lru file, and assert that it succeeds. when(mClock.now()).thenReturn(TimeUnit.HOURS.toMillis(3)); assertTrue(unexpected2.setLastModified(mClock.now())); // 2. Add second cache file CacheKey key2 = new SimpleCacheKey("bar"); byte[] value2 = new byte[102]; value2[80] = 'd'; // just so it's not all zeros for the equality test below. mCache.insert(key2, WriterCallbacks.from(value2)); // 2. Touch the LRU file, and assert that it succeeds. when(mClock.now()).thenReturn(TimeUnit.HOURS.toMillis(4)); assertTrue(mCache.probe(key2)); // The cache size should be the size of the first + second cache files // The unexpected files should not count towards size assertTrue(mCache.getSize() == 203); // At this point, the filecache size has exceeded // FILE_CACHE_MAX_SIZE_HIGH_LIMIT. However, eviction will be triggered // only when the next value will be inserted (to be more particular, // before the next value is inserted). // 3. Add third cache file CacheKey key3 = new SimpleCacheKey("foobar"); byte[] value3 = new byte[103]; value3[80] = 'e'; // just so it's not all zeros for the equality test below. mCache.insert(key3, WriterCallbacks.from(value3)); // At this point, the first file should have been evicted. Only the // files associated with the second and third entries should be in cache. // 1. Verify that the first cache, lru files are deleted assertNull(getResource(key1)); // Verify the first unexpected file is deleted, but that eviction stops // before the second unexpected file assertFalse(unexpected1.exists()); assertFalse(unexpected2.exists()); // 2. Verify the second cache, lru files exist assertArrayEquals(value2, getContents(getResource(key2))); // 3. Verify that cache, lru files for third entry still exists assertArrayEquals(value3, getContents(getResource(key3))); // The cache size should be the size of the second + third files assertTrue( String.format(Locale.US, "Expected cache size of %d but is %d", 205, mCache.getSize()), mCache.getSize() == 205); // Write another non-cache, non-lru file in the cache directory File unexpected3 = new File(mCacheDirectory, "unexpected3"); RandomAccessFile rf3 = new RandomAccessFile(unexpected3, "rw"); rf3.setLength(120); assertTrue(unexpected3.exists()); // After a clear, cache file size should be uninitialized (-1) mCache.clearAll(); assertEquals(-1, mCache.getSize()); assertFalse(unexpected3.exists()); assertNull(getResource(key2)); assertNull(getResource(key3)); } @Test public void testWithMultiCacheKeys() throws Exception { CacheKey insertKey1 = new SimpleCacheKey("foo"); byte[] value1 = new byte[101]; value1[50] = 'a'; // just so it's not all zeros for the equality test below. mCache.insert(insertKey1, WriterCallbacks.from(value1)); List<CacheKey> keys1 = new ArrayList<>(2); keys1.add(new SimpleCacheKey("bar")); keys1.add(new SimpleCacheKey("foo")); MultiCacheKey matchingMultiKey = new MultiCacheKey(keys1); assertArrayEquals(value1, getContents(mCache.getResource(matchingMultiKey))); List<CacheKey> keys2 = new ArrayList<>(2); keys2.add(new SimpleCacheKey("one")); keys2.add(new SimpleCacheKey("two")); MultiCacheKey insertKey2 = new MultiCacheKey(keys2); byte[] value2 = new byte[101]; value1[50] = 'b'; // just so it's not all zeros for the equality test below. mCache.insert(insertKey2, WriterCallbacks.from(value2)); CacheKey matchingSimpleKey = new SimpleCacheKey("one"); assertArrayEquals(value2, getContents(mCache.getResource(matchingSimpleKey))); } @Test public void testCacheFileWithIOException() throws IOException { CacheKey key1 = new SimpleCacheKey("aaa"); // Before inserting, make sure files not exist. final BinaryResource resource1 = getResource(key1); assertNull(resource1); // 1. Should not create cache files if IOException happens in the middle. final IOException writeException = new IOException(); try { mCache.insert( key1, new WriterCallback() { @Override public void write(OutputStream os) throws IOException { throw writeException; } }); fail(); } catch (IOException e) { assertNull(getResource(key1)); } verifyListenerOnWriteAttempt(key1); verifyListenerOnWriteException(key1, writeException); // 2. Test a read failure from DiskStorage CacheKey key2 = new SimpleCacheKey("bbb"); int value2Size = 42; byte[] value2 = new byte[value2Size]; value2[25] = 'b'; mCache.insert(key2, WriterCallbacks.from(value2)); verifyListenerOnWriteAttempt(key2); String resourceId2 = verifyListenerOnWriteSuccessAndGetResourceId(key2, value2Size); ((DiskStorageWithReadFailures) mStorage).setPoisonResourceId(resourceId2); assertNull(mCache.getResource(key2)); verifyListenerOnReadException(key2, DiskStorageWithReadFailures.POISON_EXCEPTION); assertFalse(mCache.probe(key2)); verifyListenerOnReadException(key2, DiskStorageWithReadFailures.POISON_EXCEPTION); verifyNoMoreInteractions(mCacheEventListener); } @Test public void testCleanOldCache() throws IOException, NoSuchFieldException, IllegalAccessException { long cacheExpirationMs = TimeUnit.DAYS.toMillis(5); CacheKey key1 = new SimpleCacheKey("aaa"); int value1Size = 41; byte[] value1 = new byte[value1Size]; value1[25] = 'a'; mCache.insert(key1, WriterCallbacks.from(value1)); String resourceId1 = verifyListenerOnWriteSuccessAndGetResourceId(key1, value1Size); CacheKey key2 = new SimpleCacheKey("bbb"); int value2Size = 42; byte[] value2 = new byte[value2Size]; value2[25] = 'b'; mCache.insert(key2, WriterCallbacks.from(value2)); String resourceId2 = verifyListenerOnWriteSuccessAndGetResourceId(key2, value2Size); // Increment clock by default expiration time + 1 day when(mClock.now()) .thenReturn(cacheExpirationMs + TimeUnit.DAYS.toMillis(1)); CacheKey key3 = new SimpleCacheKey("ccc"); int value3Size = 43; byte[] value3 = new byte[value3Size]; value3[25] = 'c'; mCache.insert(key3, WriterCallbacks.from(value3)); long valueAge3 = TimeUnit.HOURS.toMillis(1); when(mClock.now()).thenReturn( cacheExpirationMs+ TimeUnit.DAYS.toMillis(1) + valueAge3); long oldestEntry = mCache.clearOldEntries(cacheExpirationMs); assertEquals(valueAge3, oldestEntry); assertArrayEquals(value3, getContents(getResource(key3))); assertNull(getResource(key1)); assertNull(getResource(key2)); String[] resourceIds = new String[] { resourceId1, resourceId2 }; long[] itemSizes = new long[] { value1Size, value2Size }; long cacheSizeBeforeEviction = value1Size + value2Size + value3Size; verifyListenerOnEviction( resourceIds, itemSizes, CacheEventListener.EvictionReason.CONTENT_STALE, cacheSizeBeforeEviction); } @Test public void testCleanOldCacheNoEntriesRemaining() throws IOException { long cacheExpirationMs = TimeUnit.DAYS.toMillis(5); CacheKey key1 = new SimpleCacheKey("aaa"); byte[] value1 = new byte[41]; mCache.insert(key1, WriterCallbacks.from(value1)); CacheKey key2 = new SimpleCacheKey("bbb"); byte[] value2 = new byte[42]; mCache.insert(key2, WriterCallbacks.from(value2)); // Increment clock by default expiration time + 1 day when(mClock.now()) .thenReturn(cacheExpirationMs+ TimeUnit.DAYS.toMillis(1)); long oldestEntry = mCache.clearOldEntries(cacheExpirationMs); assertEquals(0L, oldestEntry); } /** * Test to make sure that the same item stored with two different versions * of the cache will be stored with two different file names. * * @throws UnsupportedEncodingException */ @Test public void testVersioning() throws IOException { // Define data that will be written to cache CacheKey key = new SimpleCacheKey("version_test"); byte[] value = new byte[32]; value[0] = 'v'; // Set up cache with version == 1 DiskStorage storage1 = createDiskStorage(TESTCACHE_CURRENT_VERSION); DiskStorageCache cache1 = createDiskCache(storage1); // Write test data to cache 1 cache1.insert(key, WriterCallbacks.from(value)); // Get cached file BinaryResource resource1 = getResource(storage1, key); assertNotNull(resource1); // Set up cache with version == 2 DiskStorage storageSupplier2 = createDiskStorage(TESTCACHE_NEXT_VERSION); DiskStorageCache cache2 = createDiskCache(storageSupplier2); // Write test data to cache 2 cache2.insert(key, WriterCallbacks.from(value)); // Get cached file BinaryResource resource2 = getResource(storageSupplier2, key); assertNotNull(resource2); // Make sure filenames of the two file are different assertFalse(resource2.equals(resource1)); } /** * Verify that multiple threads can write to the cache at the same time. */ @Test public void testConcurrency() throws Exception { final CyclicBarrier barrier = new CyclicBarrier(3); WriterCallback writerCallback = new WriterCallback() { @Override public void write(OutputStream os) throws IOException { try { // Both threads will need to hit this barrier. If writing is serialized, // the second thread will never reach here as the first will hold // the write lock forever. barrier.await(10, TimeUnit.SECONDS); } catch (Exception e) { throw new RuntimeException(e); } } }; CacheKey key1 = new SimpleCacheKey("concurrent1"); CacheKey key2 = new SimpleCacheKey("concurrent2"); Thread t1 = runInsertionInSeparateThread(key1, writerCallback); Thread t2 = runInsertionInSeparateThread(key2, writerCallback); barrier.await(10, TimeUnit.SECONDS); t1.join(1000); t2.join(1000); } @Test public void testIsEnabled() throws Exception { DiskStorage storageMock = mock(DiskStorage.class); when(storageMock.isEnabled()).thenReturn(true).thenReturn(false); DiskStorageCache cache = createDiskCache(storageMock); assertTrue(cache.isEnabled()); assertFalse(cache.isEnabled()); } private Thread runInsertionInSeparateThread(final CacheKey key, final WriterCallback callback) { Runnable runnable = new Runnable() { @Override public void run() { try { mCache.insert(key, callback); } catch (IOException e) { fail(); } } }; Thread thread = new Thread(runnable); thread.setDaemon(true); thread.start(); return thread; } @Test public void testInsertionInIndex() throws Exception { CacheKey key = putOneThingInCache(); assertTrue(mCache.hasKeySync(key)); assertTrue(mCache.hasKey(key)); } @Test public void testDoesntHaveKey() { CacheKey key = new SimpleCacheKey("foo"); assertFalse(mCache.hasKeySync(key)); assertFalse(mCache.hasKey(key)); } @Test public void testHasKeyWithAwaitingIndex() throws Exception { CacheKey key = putOneThingInCache(); // A new cache object in the same directory. Equivalent to a process restart. // Index should be updated. DiskStorageCache cache2 = createDiskCache(mStorage); cache2.awaitIndex(); assertTrue(cache2.hasKeySync(key)); assertTrue(cache2.hasKey(key)); } @Test public void testHasKeyWithoutAwaitingIndex() throws Exception { CacheKey key = putOneThingInCache(); // A new cache object in the same directory. Equivalent to a process restart. // Index may not yet updated. DiskStorageCache cache2 = createDiskCache(mStorage); assertTrue(cache2.hasKey(key)); assertTrue(cache2.hasKeySync(key)); } @Test public void testGetResourceWithoutAwaitingIndex() throws Exception { CacheKey key = putOneThingInCache(); // A new cache object in the same directory. Equivalent to a process restart. // Index may not yet updated. DiskStorageCache cache2 = createDiskCache(mStorage); assertNotNull(cache2.getResource(key)); } @Test public void testClearIndex() throws Exception { CacheKey key = putOneThingInCache(); mCache.clearAll(); assertFalse(mCache.hasKeySync(key)); assertFalse(mCache.hasKey(key)); } @Test public void testRemoveFileClearsIndex() throws Exception { CacheKey key = putOneThingInCache(); mStorage.clearAll(); assertNull(mCache.getResource(key)); assertFalse(mCache.hasKeySync(key)); } @Test public void testSizeEvictionClearsIndex() throws Exception { when(mClock.now()).thenReturn(TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); CacheKey key1 = putOneThingInCache(); CacheKey key2 = new SimpleCacheKey("bar"); CacheKey key3 = new SimpleCacheKey("duck"); byte[] value2 = new byte[(int) FILE_CACHE_MAX_SIZE_HIGH_LIMIT]; value2[80] = 'c'; WriterCallback callback = WriterCallbacks.from(value2); when(mClock.now()).thenReturn(TimeUnit.MILLISECONDS.convert(2, TimeUnit.DAYS)); mCache.insert(key2, callback); // now over limit. Next write will evict key1 when(mClock.now()).thenReturn(TimeUnit.MILLISECONDS.convert(3, TimeUnit.DAYS)); mCache.insert(key3, callback); assertFalse(mCache.hasKeySync(key1)); assertFalse(mCache.hasKey(key1)); assertTrue(mCache.hasKeySync(key3)); assertTrue(mCache.hasKey(key3)); } @Test public void testTimeEvictionClearsIndex() throws Exception { when(mClock.now()).thenReturn(5l); CacheKey key = putOneThingInCache(); mCache.clearOldEntries(4); assertFalse(mCache.hasKeySync(key)); assertFalse(mCache.hasKey(key)); } private CacheKey putOneThingInCache() throws IOException { CacheKey key = new SimpleCacheKey("foo"); byte[] value1 = new byte[101]; value1[80] = 'c'; mCache.insert(key, WriterCallbacks.from(value1)); return key; } private void verifyListenerOnHit(CacheKey key, String resourceId) { ArgumentCaptor<CacheEvent> cacheEventCaptor = ArgumentCaptor.forClass(CacheEvent.class); mCacheEventListenerInOrder.verify(mCacheEventListener).onHit(cacheEventCaptor.capture()); for (CacheEvent event : cacheEventCaptor.getAllValues()) { CacheEventAssert.assertThat(event) .isNotNull() .hasCacheKey(key) .hasResourceId(resourceId); } } private void verifyListenerOnMiss(CacheKey key) { ArgumentCaptor<CacheEvent> cacheEventCaptor = ArgumentCaptor.forClass(CacheEvent.class); mCacheEventListenerInOrder.verify(mCacheEventListener).onMiss(cacheEventCaptor.capture()); for (CacheEvent event : cacheEventCaptor.getAllValues()) { CacheEventAssert.assertThat(event) .isNotNull() .hasCacheKey(key); } } private void verifyListenerOnWriteAttempt(CacheKey key) { ArgumentCaptor<CacheEvent> cacheEventCaptor = ArgumentCaptor.forClass(CacheEvent.class); mCacheEventListenerInOrder.verify(mCacheEventListener) .onWriteAttempt(cacheEventCaptor.capture()); CacheEventAssert.assertThat(cacheEventCaptor.getValue()) .isNotNull() .hasCacheKey(key); } private String verifyListenerOnWriteSuccessAndGetResourceId( CacheKey key, long itemSize) { ArgumentCaptor<CacheEvent> cacheEventCaptor = ArgumentCaptor.forClass(CacheEvent.class); mCacheEventListenerInOrder.verify(mCacheEventListener) .onWriteSuccess(cacheEventCaptor.capture()); CacheEvent cacheEvent = cacheEventCaptor.getValue(); CacheEventAssert.assertThat(cacheEvent) .isNotNull() .hasCacheKey(key) .hasItemSize(itemSize) .hasResourceIdSet(); return cacheEvent.getResourceId(); } private void verifyListenerOnWriteException(CacheKey key, IOException exception) { ArgumentCaptor<CacheEvent> cacheEventCaptor = ArgumentCaptor.forClass(CacheEvent.class); mCacheEventListenerInOrder.verify(mCacheEventListener) .onWriteException(cacheEventCaptor.capture()); CacheEventAssert.assertThat(cacheEventCaptor.getValue()) .isNotNull() .hasCacheKey(key) .hasException(exception); } private void verifyListenerOnReadException(CacheKey key, IOException exception) { ArgumentCaptor<CacheEvent> cacheEventCaptor = ArgumentCaptor.forClass(CacheEvent.class); mCacheEventListenerInOrder.verify(mCacheEventListener) .onReadException(cacheEventCaptor.capture()); CacheEventAssert.assertThat(cacheEventCaptor.getValue()) .isNotNull() .hasCacheKey(key) .hasException(exception); } private void verifyListenerOnEviction( String[] resourceIds, long[] itemSizes, CacheEventListener.EvictionReason reason, long cacheSizeBeforeEviction) { int numberItems = resourceIds.length; ArgumentCaptor<CacheEvent> cacheEventCaptor = ArgumentCaptor.forClass(CacheEvent.class); mCacheEventListenerInOrder.verify(mCacheEventListener, times(numberItems)) .onEviction(cacheEventCaptor.capture()); boolean[] found = new boolean[numberItems]; long runningCacheSize = cacheSizeBeforeEviction; // The eviction order is unknown so make allowances for them coming in different orders for (CacheEvent event : cacheEventCaptor.getAllValues()) { CacheEventAssert.assertThat(event).isNotNull(); for (int i = 0; i < numberItems; i++) { if (!found[i] && resourceIds[i].equals(event.getResourceId())) { found[i] = true; CacheEventAssert.assertThat(event) .hasItemSize(itemSizes[i]) .hasEvictionReason(reason); } } runningCacheSize -= event.getItemSize(); CacheEventAssert.assertThat(event) .hasCacheSize(runningCacheSize); } // Ensure all resources were found for (int i = 0; i < numberItems; i++) { assertTrue( String.format("Expected eviction of resource %s but wasn't evicted", resourceIds[i]), found[i]); } } private static class DiskStorageWithReadFailures extends DynamicDefaultDiskStorage { public static final IOException POISON_EXCEPTION = new IOException("Poisoned resource requested"); private String mPoisonResourceId; public DiskStorageWithReadFailures( int version, Supplier<File> baseDirectoryPathSupplier, String baseDirectoryName, CacheErrorLogger cacheErrorLogger) { super(version, baseDirectoryPathSupplier, baseDirectoryName, cacheErrorLogger); } public void setPoisonResourceId(String poisonResourceId) { mPoisonResourceId = poisonResourceId; } @Override public BinaryResource getResource(String resourceId, Object debugInfo) throws IOException { if (resourceId.equals(mPoisonResourceId)) { throw POISON_EXCEPTION; } return get().getResource(resourceId, debugInfo); } @Override public boolean touch(String resourceId, Object debugInfo) throws IOException { if (resourceId.equals(mPoisonResourceId)) { throw POISON_EXCEPTION; } return super.touch(resourceId, debugInfo); } } }
package org.flymine.dataloader; import java.beans.IntrospectionException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.flymine.objectstore.ObjectStore; import org.flymine.objectstore.ObjectStoreWriter; import org.flymine.objectstore.ObjectStoreException; import org.flymine.util.TypeUtil; /** * Simple implementation of IntegrationWriter - assumes that this is the only (or first) data source * to be written to the database. * * @author Matthew Wakeling */ public class IntegrationWriterSingleSourceImpl extends IntegrationWriterAbstractImpl { protected Set nonSkeletons = new HashSet(); /** * Constructs a new instance of IntegrationWriterSingleSourceImpl. * * @param dataSource the name of the data source. This value is ignored by this class * @param os an instance of an ObjectStore, which we can use to access the database * @param osw an instance of an ObjectStoreWriter, which we can use to access the database */ public IntegrationWriterSingleSourceImpl(String dataSource, ObjectStore os, ObjectStoreWriter osw) { super(dataSource, os, osw); } /** * Retrieves an object from the database to match the given object, by primary key, and builds * an IntegrationDescriptor for instructions on how to modify the original object. * * @param obj the object to search for in the database * @return details of object in database and which fields canbe overwritten * @throws ObjectStoreException if error occurs finding object */ public IntegrationDescriptor getByExample(Object obj) throws ObjectStoreException { Object dbObj = os.getObjectByExample(obj); IntegrationDescriptor retval = new IntegrationDescriptor(); if (dbObj != null) { try { Class cls = obj.getClass(); retval.put(TypeUtil.getField(cls, "id"), cls.getMethod("getId", new Class[] {}).invoke(dbObj, new Object[] {})); if (nonSkeletons.contains(dbObj)) { // This data was written by us in the past. Therefore, the database version // overrides everything, except collections. Map fieldToGetter = TypeUtil.getFieldToGetter(obj.getClass()); Iterator iter = fieldToGetter.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Field field = (Field) entry.getKey(); Method method = (Method) entry.getValue(); Object value = method.invoke(obj, new Object[] {}); retval.put(field, value); } } // } else { // This data was not written for real in the past by us. Therefore, we do not // need to fill in anything (except id) in the return value. } catch (IntrospectionException e) { throw new ObjectStoreException("Something horribly wrong with the model", e); } catch (NoSuchMethodException e) { throw new ObjectStoreException("Something nasty with the model", e); } catch (IllegalAccessException e) { throw new ObjectStoreException("Something upset in java", e); } catch (InvocationTargetException e) { throw new ObjectStoreException("Something weird in java", e); } } return retval; } /** * Stores an object into the database, either for real or as a skeleton. * Collections in the object are merged with collections in any version of the object already in * the database. The operation sets the reverse object reference on one-to-many collections. * * @param obj the object to store * @param skeleton whether the object is a skeleton * @throws ObjectStoreException if anything goes wrong during store */ public void store(Object obj, boolean skeleton) throws ObjectStoreException { // Here, we are assuming that the store(Object) method sets the ID in the object. store(obj); if (!skeleton) { nonSkeletons.add(obj); } } }
package jadx.core.dex.visitors.regions; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import jadx.core.dex.attributes.AType; import jadx.core.dex.nodes.BlockNode; import jadx.core.dex.nodes.IBranchRegion; import jadx.core.dex.nodes.IContainer; import jadx.core.dex.nodes.IRegion; import jadx.core.dex.nodes.MethodNode; import jadx.core.dex.regions.AbstractRegion; import jadx.core.dex.regions.Region; import jadx.core.dex.regions.TryCatchRegion; import jadx.core.dex.regions.loops.LoopRegion; import jadx.core.dex.trycatch.CatchAttr; import jadx.core.dex.trycatch.ExceptionHandler; import jadx.core.dex.trycatch.SplitterBlockAttr; import jadx.core.dex.trycatch.TryCatchBlock; import jadx.core.utils.BlockUtils; import jadx.core.utils.ErrorsCounter; import jadx.core.utils.RegionUtils; import jadx.core.utils.exceptions.JadxRuntimeException; /** * Extract blocks to separate try/catch region */ public class ProcessTryCatchRegions extends AbstractRegionVisitor { private static final Logger LOG = LoggerFactory.getLogger(ProcessTryCatchRegions.class); public static void process(MethodNode mth) { if (mth.isNoCode() || mth.isNoExceptionHandlers()) { return; } Map<BlockNode, TryCatchBlock> tryBlocksMap = new HashMap<>(2); searchTryCatchDominators(mth, tryBlocksMap); IRegionIterativeVisitor visitor = new IRegionIterativeVisitor() { @Override public boolean visitRegion(MethodNode mth, IRegion region) { boolean changed = checkAndWrap(mth, tryBlocksMap, region); return changed && !tryBlocksMap.isEmpty(); } }; DepthRegionTraversal.traverseIncludingExcHandlers(mth, visitor); } private static void searchTryCatchDominators(MethodNode mth, Map<BlockNode, TryCatchBlock> tryBlocksMap) { Set<TryCatchBlock> tryBlocks = new HashSet<>(); // collect all try/catch blocks for (BlockNode block : mth.getBasicBlocks()) { CatchAttr c = block.get(AType.CATCH_BLOCK); if (c != null) { tryBlocks.add(c.getTryBlock()); } } // for each try block search nearest dominator block for (TryCatchBlock tb : tryBlocks) { if (tb.getHandlersCount() == 0) { LOG.warn("No exception handlers in catch block, method: {}", mth); continue; } BitSet bs = new BitSet(mth.getBasicBlocks().size()); for (ExceptionHandler excHandler : tb.getHandlers()) { BlockNode handlerBlock = excHandler.getHandlerBlock(); if (handlerBlock != null) { SplitterBlockAttr splitter = handlerBlock.get(AType.SPLITTER_BLOCK); if (splitter != null) { BlockNode block = splitter.getBlock(); bs.set(block.getId()); } } } List<BlockNode> domBlocks = BlockUtils.bitSetToBlocks(mth, bs); BlockNode domBlock; if (domBlocks.size() != 1) { domBlock = BlockUtils.getTopBlock(domBlocks); if (domBlock == null) { throw new JadxRuntimeException( "Exception block dominator not found, method:" + mth + ". bs: " + domBlocks); } } else { domBlock = domBlocks.get(0); } TryCatchBlock prevTB = tryBlocksMap.put(domBlock, tb); if (prevTB != null) { ErrorsCounter.methodError(mth, "Failed to process nested try/catch"); } } } private static boolean checkAndWrap(MethodNode mth, Map<BlockNode, TryCatchBlock> tryBlocksMap, IRegion region) { // search dominator blocks in this region (don't need to go deeper) for (Map.Entry<BlockNode, TryCatchBlock> entry : tryBlocksMap.entrySet()) { BlockNode dominator = entry.getKey(); if (region.getSubBlocks().contains(dominator)) { TryCatchBlock tb = tryBlocksMap.get(dominator); if (!wrapBlocks(region, tb, dominator)) { ErrorsCounter.methodError(mth, "Can't wrap try/catch for " + region); } tryBlocksMap.remove(dominator); return true; } } return false; } /** * Extract all block dominated by 'dominator' to separate region and mark as try/catch block */ private static boolean wrapBlocks(IRegion replaceRegion, TryCatchBlock tb, BlockNode dominator) { if (replaceRegion == null) { return false; } if (replaceRegion instanceof LoopRegion) { LoopRegion loop = (LoopRegion) replaceRegion; return wrapBlocks(loop.getBody(), tb, dominator); } if (replaceRegion instanceof IBranchRegion) { return wrapBlocks(replaceRegion.getParent(), tb, dominator); } Region tryRegion = new Region(replaceRegion); List<IContainer> subBlocks = replaceRegion.getSubBlocks(); for (IContainer cont : subBlocks) { if (RegionUtils.hasPathThroughBlock(dominator, cont)) { if (isHandlerPath(tb, cont)) { break; } tryRegion.getSubBlocks().add(cont); } } if (tryRegion.getSubBlocks().isEmpty()) { return false; } TryCatchRegion tryCatchRegion = new TryCatchRegion(replaceRegion, tryRegion); tryRegion.setParent(tryCatchRegion); tryCatchRegion.setTryCatchBlock(tb.getCatchAttr().getTryBlock()); // replace first node by region IContainer firstNode = tryRegion.getSubBlocks().get(0); if (!replaceRegion.replaceSubBlock(firstNode, tryCatchRegion)) { return false; } subBlocks.removeAll(tryRegion.getSubBlocks()); // fix parents for tryRegion sub blocks for (IContainer cont : tryRegion.getSubBlocks()) { if (cont instanceof AbstractRegion) { AbstractRegion aReg = (AbstractRegion) cont; aReg.setParent(tryRegion); } } return true; } private static boolean isHandlerPath(TryCatchBlock tb, IContainer cont) { for (ExceptionHandler h : tb.getHandlers()) { BlockNode handlerBlock = h.getHandlerBlock(); if (handlerBlock != null && RegionUtils.hasPathThroughBlock(handlerBlock, cont)) { return true; } } return false; } }